python - 从菜单调用的 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
我想知道可以做些什么来让他们两个都按预期工作。
解决方案
def do_nothing(*args):
print("Doing nothing.")
命令回调、绑定回调和跟踪回调都有不同的签名。为了满足他们所有你需要定义很多默认值,或者使用*args
.
推荐阅读
- javascript - 根据传递的参数数量运行可变数量的行
- ios - 如何将角半径添加到 UIView 周围的虚线边框
- c++ - SDL_FreeSurface 没有释放 RAM / RAM 溢出
- java - 从 json 模式动态生成 JSON
- javascript - 在 Chrome JavaScript 中更改样式显示属性未正确执行
- r - 在 LAN 上部署 R 闪亮的应用程序:未捕获的类型错误:无法读取 null 的属性“readyState”
- c# - 启用 TinyCache 插件后 ImageResizer 不再工作
- c# - 如何在 ASP.NET 样板中获取当前事务?
- python - ConnectionAbortedError: [Errno 53] 软件导致连接中止
- android - ViewPager2 行为中的水平 RecyclerView