2014-02-10 31 views
0

我想使选择下的文本变量'a'显示为菜单的标签。 这里是代码:将文本传递到tkinter中的菜单标签

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'中的任何内容作为菜单标签打印?

+0

AFAIK,回调方法不应该返回任何东西。尝试在'popup'方法内的菜单中添加'a',即在那里移动'menu.add_command(label = a,command = ...)'。 –

+0

@tobias_k - 它的工作,非常感谢。我已经尝试过,但显然有一个错字或什么的。 – kaboom

+0

很高兴我能帮到你。我已经添加了这个答案。 –

回答

0

回调方法,如popup不应该返回任何东西。相反,你应该操纵menu里面的的功能。

另外,正如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 
0

如果要更改菜单上的文本,则必须使用entryconfig方法。例如,为了改变第一项的文本,你会怎么做:

menu.entryconfig(0, label=a) 
相关问题