问题
I am trying to bind a key to a command conditionally. But when I bind, the command gets automatically executed (when I toggle both commands). Why does that happen? And how can I only bind a command without executing it? Also after binding both commands, only the first one (function p) is being executed. Why is that? My code is as follows:
from tkinter import *
top = Tk()
editor = Text(top)
editor.pack()
def br(event=None):
try:
editor.insert(INSERT, "<br />")
except:
pass
def ins_br():
br()
return 'break'
def p(event=None):
try:
editor.insert(INSERT, "\n<p></p>")
return 'break'
except:
pass
def br_and_p(event=None):
br()
p()
def enter_key():
if ins_br_var.get() == 1 and p_var.get() == 1:
editor.bind('<Return>', br_and_p())
elif ins_br_var.get() == 1 and p_var.get() == 0:
editor.bind('<Return>', br)
elif ins_br_var.get() == 0 and p_var.get() == 1:
editor.bind('<Return>', p)
else:
editor.unbind('<Return>')
toolbar = Frame(top, bd=1, relief=RAISED)
toolbar.pack(side=TOP, fill=X)
ins_br_var = IntVar()
ins_br_cbox = Checkbutton(toolbar, text="ins_br", variable=ins_br_var, command=enter_key)
ins_br_cbox.pack(side=LEFT, padx=2, pady=2)
p_var = IntVar()
p_cbox = Checkbutton(toolbar, text="p", variable=p_var, command=enter_key)
p_cbox.pack(side=LEFT, padx=2, pady=2)
回答1:
Omit the ()
.
When you do this:
editor.bind('<Return>', br_and_p())
... You are immediately executing the function br_and_ p
, and binding the result of that function to the event.
来源:https://stackoverflow.com/questions/21225198/tkinter-command-executed-automatically-when-binding-binding-not-acting-as-exp