我正在努力在类中创建小部件。我想创建两个运行相同代码的按钮,但我希望列出的标签不同。我似乎无法弄清楚如何正确使用索引,因此第二个标签不会覆盖第一个标签。我错过了一个明显的错误吗?
类应用程序(ttk.Frame):
def __init__(self, master):
ttk.Frame.__init__(self, master)
self.widgets()
def widgets(self):
btn_list = [] #List to hold the button objects
lbl_list = [] #List to hold the label objects
for i in range(2):
# Lambda command to hold reference to the index matched with range value
self.b = ttk.Button(self, text = 'Button #%s' % i, command = lambda idx = i: self.browse_function(idx))
self.b.grid(row = i, column = 0)
self.pathlabel = ttk.Label(self, text="HI!")
self.pathlabel.grid(row=i, column=1)
self.btn_list.append(self.b) # Append the button to a list
self.lbl_list.append(self.pathlabel) #Append the label to a list
def browse_function(self, idx):
filename = filedialog.askopenfilename(title = "Select file", filetypes = (("csv files","*.csv"),("all files","*.*")))
self.lbl_list[idx].cget("text").config(text=filename)
谢谢您的时间!