2012-10-12 162 views
0

我正在嘗試爲每個tkinter按鈕執行不同的代碼 - 其名稱不知道,直到從列表中調用。 gtk已經獲得標籤(不幸的是我不能使用gtk)。tkinter - 獲取按鈕名稱?

我該如何實現與tkinter相似?

def click_one(newbuttonname): 
     try: 
       writethisdown = open("participantsmovedlog.txt", 'a') 
     except: 
       pass 
     rotatee = newbuttonname 
     thispersonwasrotated(rotatee) 
     writethisdown.close() 

....和內makebutton功能同時:

for someuser in listofusers: 
      username = someuser 
      newbuttonname = username 
      newbuttonname = Tkinter.Button(win, text = newbuttonname, command = lambda:click_one(username)) 
      newbuttonname.pack() 

回答

5

你幾乎沒有。您只需通過拉姆達或functools.partial將名字傳下去:

newbuttonname = username 
newbuttonname = Tkinter.Button(win, text = newbuttonname, 
    command = lambda name=username:click_one(name)) 

您可以使用同樣的技術在實際wodget,或任何其它數據傳遞。

+0

非常好!但是我不能讓Tkinter甚至沒有win.quit()或win.destroy()? – Donnied

+1

@Donnied:我不明白你的意見。這個問題和答案與製作程序無關。如果您遇到問題,請在另一個問題中提問,我確信有人會回答。 –

+0

謝謝布萊恩 - 我已經接受了你的回答。這只是一個真正的 - 我會問這個問題,但它已被問了十幾次 - 我懷疑我會被燒傷 - 你沒有讀過線程x,y和z嗎?我會繼續問它... – Donnied

10

布賴恩的答案可能並不完全解決這個問題,特別是他的解決方案只有在按鈕的文本被創建後纔會改變。

button.config('text')[-1] 

返回實際按鈕的文本。