开发者

Tkinter bind problem

开发者 https://www.devze.com 2023-03-05 12:57 出处:网络
I have something like this: from Tkinter import * root = Tk() root.title(\"Test\") def _quit(): roo开发者_如何学Pythont.destroy()

I have something like this:

from Tkinter import *

root = Tk()
root.title("Test")

def _quit():
    roo开发者_如何学Pythont.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=_quit, accelerator='Ctrl+Q')

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

root.mainloop()

My question is:

"Why _quit() always is being called?"


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消