Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将文本传递到tkinter中的菜单标签_Python_Tkinter - Fatal编程技术网

Python 将文本传递到tkinter中的菜单标签

Python 将文本传递到tkinter中的菜单标签,python,tkinter,Python,Tkinter,我想让变量“a”中的选择项下的文本显示为菜单的标签。 代码如下: def popup(event): a=t_start.get("sel.first", "sel.last") menu.post(event.x_root, event.y_root) return a def insert_word(): pass t_start.bind("<Button-3>", popup) menu = Menu(root, tearoff=0)

我想让变量“a”中的选择项下的文本显示为菜单的标签。 代码如下:

def popup(event):
    a=t_start.get("sel.first", "sel.last")
    menu.post(event.x_root, event.y_root)
    return a

def insert_word():
    pass

t_start.bind("<Button-3>", popup)


menu = Menu(root, tearoff=0)
menu.add_command(label="Set selection 1", command=set_selection_1)
menu.add_command(label="Set selection 2", command=set_selection_2)
menu.add_command(label="%s" %popup, command=set_selection_2)
现在,我得到的只是函数弹出地址。
如果我尝试popup.a,我会得到一个错误,函数没有属性“a”。如何克服这一问题并将“a”中的内容打印为菜单标签?

如果要更改菜单上的文本,必须使用entryconfig方法。例如,要更改第一项的文本,请执行以下操作:

menu.entryconfig(0, label=a)
像popup这样的回调方法不应该返回任何东西。相反,您应该从函数内部操作菜单

此外,正如Brian所建议的,您可能更希望修改菜单中的现有条目,而不是每次单击按钮时添加新条目。在这种情况下,可以像现在一样在函数外部创建条目,但要为标签使用一些占位符

def popup(event):
    a = t_start.get("sel.first", "sel.last")
    menu.post(event.x_root, event.y_root)
    menu.add_command(label=a, command=set_selection_2) # add to menu
    # menu.entryconfig(2, label=a) # modify existing entry

好了,回调方法不应该返回任何东西。尝试将a添加到弹出方法内的菜单,即移动菜单。添加_commandlabel=a,command=。。。好了。@tobias_k-成功了,非常感谢。我以前试过这个,但很明显有打字错误什么的。很高兴我能帮上忙。我加上这个作为回答。