在 Tkinter 中使用 <menu_item>.add_command()
构建菜单栏我们需要一个字符串来表示 accelerator
将为命令创建热键绑定(bind)的参数。
我创建了一个方法,用于检查用户的平台是 Mac 还是其他平台,如果是,则返回 Command
键字符串与其他键组合。
但它不起作用 -> 菜单正在构建,如果我单击它正在工作的菜单项,但不能使用热键。虽然我可以在菜单中看到 ⌘ + N..
我的第一个想法是,self.hot_key()
作为参数传递时不调用方法..
import sys
import Tkinter
class app(object):
def __init__(self):
self.gui = Tkinter.Tk()
self.gui.minsize(width=640, height=320)
menu = Tkinter.Menu(self.gui)
filemenu = Tkinter.Menu(menu, tearoff=0)
filemenu.add_command(
label = 'New',
command = self.New,
accelerator = self.hot_key('n')
)
menu.add_cascade(
label = 'File',
menu = filemenu
)
self.gui.config(menu=menu)
self.text = Tkinter.Text(self.gui)
self.text.pack(expand=Tkinter.YES, fill=Tkinter.BOTH)
def hot_key(self, *keys):
super_key = 'Command' if sys.platform == 'darwin' else 'Control'
return '{super}+{keys}'.format(super=super_key, keys='+'.join(keys))
def New(self):
print "I'm working!"
App = app()
App.gui.mainloop()
最佳答案
根据 this页面,
The "accelerator" option is used to indicate the menu accelerator that should be associated with this menu. This does not actually create the accelerator, but only displays what it is next to the menu item. You still need to create a binding for the accelerator yourself.
因此您的 accelerator
关键字参数按设计工作 - Command-N 符号出现在您的菜单中。
正如 mgilson 在评论中建议的那样,您可以使用 bind_all
让键盘组合实际执行某些操作。
self.gui.bind_all("<Command-n>", lambda event: self.New())
关于python - 在 Tkinter 中如何将被调用函数作为参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17234943/