python - 在 Tkinter 中如何将被调用函数作为参数传递?

标签 python tkinter

在 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/

相关文章:

python - Entry.place(X,Y) 不起作用

python - Python 的 Tkinter 中的图像问题

python - CherryPy: `error_page.default` 与 `error_page.404` 配置设置之间有什么区别?

python - 评估 k-means 算法找到的邻居

python - python是如何从静态类型语言实现无类型变量的

python - ffprobe 按时长过滤视频,命令打印但不返回时长

python - 如何使用defaultdict选择python tkinter列?

python - 使用 dill 库时出现 TypeError : can't pickle _tkinter. tkapp 对象

python - 如何使用 tkinter Canvas 小部件制作按钮?

python - 更新流程中的 GUI 项目