Tkinter bind problem Tkinter bind problem tkinter tkinter

Tkinter bind problem


When you are binding with Tkinter you typically do not call the function you wish to bind.

You're supposed to use the line

root.bind('<Control-Q>', _quit) 

instead of

root.bind('<Control-Q>', _quit())

Take note of the lack of parentheses behind _quit.

This code below should work.

from Tkinter import *root = Tk()root.title("Test")def _quit(event):    root.destroy()m = Menu(root)root.config(menu=m)fm = Menu(m, tearoff=0)m.add_cascade(label="File", menu=fm)fm.add_command(label="Quit", command=lambda: _quit(None), accelerator='Ctrl+Q')root.bind('<Control-Q>', _quit)root.bind('<Control-q>', _quit)root.mainloop()

EDIT:

Oops sorry, I only ran the code testing the keyword command for quit in the menu bar. Not the bound key commands. When doing bindings for Tkinter and I'm pretty sure most GUI toolkits, the binding inserts and event argument when the function is called. However the Tkinter command keyword argument does not typicaly insert an event. So you have to compromise by having the command keyword argument "artificially" insert an event argument of None (lambda: _quit(None)). This allows you to use one function in both scenarios.


Because you're calling it. Don't call it:

root.bind('<Control-Q>', _quit)