0、問題
在用Tkinter進行編程時,需要在一個Frame下顯示多個圖片,但是不管怎么設置都是只顯示最后一張,就像這樣:
代碼
for i in range(3): ... image=ImageTk.PhotoImage(f'img{i}.png')#分別打開img1,img2,img3並顯示 Label(window, image=image, bg='green').place(x=60 + rw * i, y=500)
結果
本來紅線處還有兩幅圖,總共三幅,但是現在只顯示了最后一幅。
1、原因
在上述代碼最后一行,我們這樣寫:
Label(window, image=image, bg='green').place(x=60 + rw * i, y=500)
在執行過程中,每個image變量會覆蓋上一個image變量,導致運行過程中總是只有1個image參與了繪制,從而只顯示一個image
2、解決
給不同的image分別命不同的名,或者干脆用一個List:
image=[] for i in range(3): ... image.append(ImageTk.PhotoImage(f'img{i}.png') Label(window,image=image[i],bg='green').place(x=60+rw*i,y=500)
補充
pack與place是沒有返回值的,所以在需要對要素進行后續操作時,不要直接將該要素的生成和放置寫在同一句話中,就像這樣:
Label(window, text='直方圖:', font=('宋體', 16)).place(x=0, y=60)
最好分開寫:
L1=Label(window, text='直方圖:', font=('宋體', 16)) L1.place(x=0, y=60)
如果像一開始那樣寫L1=XXX.place(),那么最終得到的L1將是NoneType