0

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.