[英]How do I get my functions to configure the correct labels in tkinter in the following code?
當我單獨創建標簽時,我可以做到這一點,因此每個函數都會在調用它的按鈕旁邊配置標簽。 當我嘗試使用 zip 創建標簽時,這些功能都配置了最后一個標簽。 我覺得我在某個地方錯過了一步。 我怎樣才能做到這一點,以便每個函數都配置正確的標簽,而不必單獨創建每個標簽?
from tkinter import *
root = Tk()
root.configure(bg='light blue', height=1200, width=1200)
left_frame = Frame(root, width=250, height=500, bg='grey')
left_frame.place(x=10, y=10, relx=0.01, rely=0.01,)
def Create_Test():
l.configure(text='Test result number 1')
def Create_test2():
l.configure(text="Test result number 2")
def Create_test3():
l.configure(text="Test result number 3")
text=['butt1', 'butt2', 'butt3','butt4']
Comm=[Create_Test, Create_test2, Create_test3]
for t,z in zip( text, Comm):
butt=Button(left_frame, text=t, width=12, bg='red', fg='black', command=z, relief='ridge')
butt.pack(side=TOP)
labels = ['Label1', 'Label2', 'Label3']
ys = [20, 47, 74]
for l,z in zip(labels,ys):
l=Label(root, text="", width=25, bg='blue', fg='black',relief='ridge')
l.place(x=125, y=z)
root.mainloop()
嘗試一些 lambda 魔法
改變
butt=Button(left_frame, text=t, width=12, bg='red', fg='black', command=z, relief='ridge')
到
butt=Button(left_frame, text=t, width=12, bg='red', fg='black', command=lambda z=z(): z, relief='ridge')
請注意,您還錯誤地嘗試更改標簽的文本。 您在代碼中重復使用l
來表示許多不同的內容。 我在下面提供的示例為您提供了一種將每個標簽存儲在字典中的方法,以便您以后可以更改它們的內容
from tkinter import *
root = Tk()
root.configure(bg='light blue', height=1200, width=1200)
left_frame = Frame(root, width=250, height=500, bg='grey')
left_frame.grid()
def Create_Test():
print(1)
label_dict['Label1'].configure(text='Test result number 1')
def Create_test2():
print(2)
label_dict['Label2'].configure(text="Test result number 2")
def Create_test3():
print(3)
label_dict['Label3'].configure(text="Test result number 3")
text=['butt1', 'butt2', 'butt3']
labels = ['Label1', 'Label2', 'Label3']
Comm=[Create_Test, Create_test2, Create_test3]
label_dict = {}
for idx,(button_text,label_text,fcn) in enumerate(zip(text,labels, Comm)):
butt=Button(left_frame, text=button_text, width=12, bg='red', fg='black', command=lambda z=fcn:z(), relief='ridge')
butt.grid(row=idx,column=0)
currentLabel=Label(left_frame, text="", width=25, bg='blue', fg='black',relief='ridge')
currentLabel.grid(row=idx,column=1)
label_dict[label_text] = currentLabel
root.mainloop()
我使用了 .grid 而不是你當前的 place 和 pack 組合。 此外,我有一個循環來繪制按鈕和標簽,因為您可以將 2 個以上的可迭代對象壓縮在一起。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.