2014-02-10 28 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) 
相關問題