首页 > 解决方案 > 从命令方法 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 菜单栏时,它只是给了我“无”值......有什么帮助吗?

标签: pythonmethodstkinterreturn-value

解决方案


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


推荐阅读