首页 > 解决方案 > 从菜单调用的 tkinter 命令和键绑定冲突

问题描述

我是一个新手,试图制作也可以通过快捷方式触发的菜单操作,比如最常见的“文件>新建”和“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

我想知道可以做些什么来让他们两个都按预期工作。

标签: pythonpython-3.xtkintermenukey-bindings

解决方案


def do_nothing(*args):
    print("Doing nothing.")

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


推荐阅读