2017-08-17 173 views
0

我不明白如何引用在tkinter中點擊的按鈕。點擊時如何獲得按鈕ID?

我的代碼:

for file in files: 
    btn = Button(root, text=file).pack() 

現在如從源文件生成50個按鈕。
但是,當我點擊任何按鈕,只有最後一個按鈕被引用,但不是我真正想要使用/點擊的按鈕。

在JavaScript中,我們使用this來引用我們真正點擊的對象,但是我找不到Python中的任何解決方案。

+1

@EthanField請不要添加代碼的問題。沒有跡象表明OP使用[tag:python-3.x]或'files'列表。如果您不確定,請使用評論來澄清。 – Lafexlos

+0

OP已經提供了代碼,我使它可以運行,除了「Tkinter」和「tkinter」之間的代碼將在2.x或3.x中運行之間的區別之外,我沒有看到任何問題。另外,OP聲明'用於文件中的文件:'表示文件是一個'list',所以雖然OP沒有向我們提供任何'files'的數據,但我添加了一個for循環來使用50個按鈕來填充它OP表示應該添加腳本。我也不同意這個問題的分類是重複的,這兩個問題顯然是不同的 –

+0

@EthanField _OP聲明文件中的文件:這意味着這個文件是一個list_umm ..號.'文件'可以是任何可迭代的(即發電機,放大器對象,拉鍊對象等),我們不知道它是如何產生的。關於重複..鏈接的問題_exactly_做OP解釋。它如何不重複? – Lafexlos

回答

0

這可以像下面這樣做:

from tkinter import * 

root = Tk() 

files = [] #creates list to replace your actual inputs for troubleshooting purposes 
btn = [] #creates list to store the buttons ins 

for i in range(50): #this just popultes a list as a replacement for your actual inputs for troubleshooting purposes 
    files.append("Button"+str(i)) 

for i in range(len(files)): #this says for *counter* in *however many elements there are in the list files* 
    #the below line creates a button and stores it in an array we can call later, it will print the value of it's own text by referencing itself from the list that the buttons are stored in 
    btn.append(Button(root, text=files[i], command=lambda c=i: print(btn[c].cget("text")))) 
    btn[i].pack() #this packs the buttons 

root.mainloop() 

那麼這樣做是創建按鈕的列表,每個按鈕都分配了一個命令,它是lambda c=i: print(btn[c].cget("text")

讓我們來分析一下。

lambda被用來使得直到命令被調用時才執行下面的代碼。

我們宣佈c=i使這是在列表中的元素的位置的值i被儲存在一個臨時的和一次性的變量c,如果我們不這樣做,那麼在該按鈕會始終引用最後一個按鈕列表,因爲這是i對應列表的最後一次運行。

.cget("text")是用於從特定tkinter元素獲取屬性text的命令。

上面的組合會產生你想要的結果,每個按鈕在被按下後會打印它自己的名字,你可以使用類似的邏輯來應用它來調用你需要的任何屬性或事件。

+0

非常感謝!你真的救了我的蟒蛇日! :) – cytzix

相關問題