[英]Using a Variable in the Instance Name of a Tkinter Entry Box
我正在嘗試使用一個變量作為 tkinter Entry 框的實例名稱,這樣當我通過 for 循環進行隨機播放時,每個框都有一個唯一的實例名稱。 有沒有辦法做到這一點,以便以后我可以提取單個條目值?
hoursList = [1, 2, 3, 4, 5]
x = 0
for item in hoursList:
varName = "userEntry" + str(x)
self.varName = tk.Entry(self.frame)
self.varName.grid()
x += 1
self.getInput = tk.Button(self.frame, text="Submit", command= self.submitHours())
self.getInput.grid()
def submitHours(self):
if self.varName.get() is not None:
print(self.varName.get())
理想情況下,該段將創建 5 個名為“userEntry1”、“userEntry2”等的條目框,並打印每個提交的值。
如果可以,盡量避免動態創建變量名。 這是可能的,但實現通常是復雜的,並且隨着您的代碼庫變得越來越復雜,可能會導致難以理解代碼。 相反,使用像list
這樣的容器來保存所有條目。 它們不需要有名字,你只需要能夠引用它們。
此外,您的command = self.submit_hours()
並沒有按照您的想法行事。 正如所寫, self.submit_hours
將在您創建提交按鈕時運行。 您想將可調用對象傳遞給命令(如函數)。 單擊按鈕時,您傳遞給 command 的任何內容都將被調用。 要在您的代碼中解決此問題,只需刪除self.submit_hours()
上的括號,因為self.submit_hours
本身是可調用的。
下面是一個顯示如何將您的條目存儲在列表中、如何訪問它們以及它們如何與您的hour_list
對應的hour_list
示例。
import tkinter as tk
class MyApp:
def __init__(self):
self.root = tk.Tk()
self.frame = tk.Frame(master = self.root)
self.frame.grid()
self.hour_list = [1, 2, 3, 4, 5]
self.entries = []
self.make_entries()
self.root.mainloop()
def submit_hours(self):
for n, entry in enumerate(self.entries):
print(f"Entry {n} (hour {self.hour_list[n]}) has the value '{entry.get()}'")
return
def make_entries(self):
for hour in self.hour_list:
temp_entry= tk.Entry(master = self.frame)
temp_entry.grid()
self.entries.append(temp_entry)
self.submit_button = tk.Button(master = self.frame, text = "Submit",
command = self.submit_hours)
self.submit_button.grid()
return
test = MyApp()
當我在條目中輸入內容然后點擊提交按鈕時,這是我的控制台輸出:
Entry 0 (hour 1) has the value 'first box'
Entry 1 (hour 2) has the value 'this is the 2nd'
Entry 2 (hour 3) has the value 'and the third box'
Entry 3 (hour 4) has the value 'fourth'
Entry 4 (hour 5) has the value '5th'
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.