【问题标题】:tkinter command called from menu and key bind conflicting从菜单调用的 tkinter 命令和键绑定冲突
【发布时间】:2019-03-10 02:31:39
【问题描述】:

我是一个新手,尝试制作也可以通过快捷方式触发的菜单操作,例如最常见的“文件 > 新建”和“Ctrl+N”。 这是我正在尝试使用的代码:

import tkinter as tk

def do_nothing(self):
    print("Doing nothing.")

root = tk.Tk()
mainMenu = tk.Menu(root)
root.configure(menu=mainMenu)
fileMenu = tk.Menu(mainMenu, tearoff=0)
mainMenu.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="New", command=do_nothing, accelerator="Ctrl+N")
root.bind_all("<Control-n>", do_nothing)
tk.mainloop()

这是我的问题。运行上述代码时,“Ctrl+N”快捷键工作正常,但使用菜单并单击“新建”返回错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\username\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: do_nothing() missing 1 required positional argument: 'self'

我尝试将def do_nothing(self): 更改为def do_nothing():,但现在错误已反转。使用菜单并单击“新建”可以正常工作,但“Ctrl+N”快捷键返回错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\username\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
TypeError: do_nothing() takes 0 positional arguments but 1 was given

我想知道如何才能让它们都按预期工作。

【问题讨论】:

    标签: python python-3.x tkinter menu key-bindings


    【解决方案1】:
    def do_nothing(*args):
        print("Doing nothing.")
    

    命令回调、绑定回调和跟踪回调都有不同的签名。为了满足它们,你需要定义很多默认值,或者使用*args

    【讨论】:

    • 成功了。非常感谢,很抱歉回复晚了。
    • 如果它对其他人有帮助,这个答案帮助我意识到如何解决相同的问题,但对于 self 以外的参数。调用函数时,例如self.do_nothing('something'),将原始函数声明为do_nothing(self, *args): something = args[0]。 @Novel,如果有更好的方法,请纠正我!
    猜你喜欢
    • 2019-05-14
    • 2017-08-05
    • 1970-01-01
    • 1970-01-01
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-10
    相关资源
    最近更新 更多