python - 从命令方法 Tkinter Python 调用的函数中取回参数
问题描述
当我按下菜单栏时,我试图从函数中获取值,但我不知道该怎么做:
假设我有下一个功能:
def other1():
return 10
def other2(a):
print(a)
Insert = Menu(menubar, tearoff=0)
x=Insert.add_command(label="InsertA1", command=other1)
Insert.add_command(label="InsertA2", command=other2(x))
当我尝试按下 InsertA2 菜单栏时,它只是给了我“无”值......有什么帮助吗?
解决方案
Menu.add_command
不返回任何东西(至少据我所知),这部分是你得到 None 的部分原因。
当你这样做时command=other2(x)
,它实际上并没有按照你的预期做,它实际上command
等于 的返回值other2(x)
,因为函数调用是在运行时评估的。你的意思是在做command=lambda x=x: other2(x)
。
如果您要x=Insert.add_command(...)
保留对该命令的引用,以便以后可以使用编辑它,那不是您这样做的方式。您可以通过 配置命令Menu.entryconfigure(index)
,并通过 访问其配置Menu.entrycget(index)
,而索引是您添加命令条目的位置/顺序。http://tcl.tk/man/tcl8.5/TkCmd/menu.htm#M55。
推荐阅读
- ffmpeg - 如何使用 ffprobe 检测带有 pts 图像的 pts scte35 消息 I
- oauth - 密码重置后强制注销 WSO2 IS
- python - 仅在没有重复项的情况下如何将行添加到文件中?
- openshift - Nifi图像未在openshift上运行
- github - Julia 文档“加载密钥:格式无效”
- kubernetes - 在 Airflow 的环境变量中设置变量
- c# - 访问函数体内的存储帐户连接字符串
- excel - 2个功能合二为一
- logistic-regression - 网格搜索准确率 100%?怎么了?
- javascript - 将 8 位数字数组转换为长布尔值数组并返回 JavaScript 的最有效方法是什么?