我試圖在 Tkinter 的水平行中放置一組影像。我通過回圈串列并從作業目錄加載相應的影像來做到這一點。我根據索引乘以一定的間距放置影像。然而,當我實際放置影像時,它們都在最后一個位置彼此重疊,而不是間隔開。計數值作業正常,當我print(spacing*(count 1))輸出正確的值但放置時它們都聚集在最后一個位置。
這跟Label()班級有關系嗎?
for count, mood in enumerate(mood_options):
mood_img = Image.open(f"img/{mood}.png")
mood_img_copy = mood_img.resize(img_size, Image.ANTIALIAS)
mood_img_resized = ImageTk.PhotoImage(mood_img_copy)
mood_img_label = Label(root, image=mood_img_resized).place(relx=spacing*(count 1), rely=0.35)
print(spacing * (count 1))
編輯:我已經使用這種確切的方法來放置按鈕,見下文:
for count, mood in enumerate(mood_options):
mood_btn = Button(root, text=mood.capitalize(), command=lambda mood=mood: register_mood(mood), width=7) \
.place(relx=(count 1) * spacing, rely=0.5)
這完美無缺,這讓我想知道為什么它不適用于影像而不是按鈕。
uj5u.com熱心網友回復:
如果相同的邏輯適用于按鈕,那么問題可能是影像被垃圾收集,在這種情況下,您不能將影像存盤為某個類的屬性來保存參考,因為在每次迭代中,每個影像都會被覆寫,保存參考僅最后一張圖片。同樣的情況global也會發生。所以去這里的方法是附加到一個串列中。嘗試類似:
lst = []
for count, mood in enumerate(mood_options):
mood_img = Image.open(f"img/{mood}.png")
mood_img_copy = mood_img.resize(img_size, Image.ANTIALIAS)
mood_img_resized = ImageTk.PhotoImage(mood_img_copy)
lst.append(mood_img_resized)
Label(root, image=mood_img_resized).place(relx=spacing*(count 1), rely=0.35)
print(spacing * (count 1))
盡管使用grid類似網格的方式放置東西會更好。如果您擔心視窗的回應能力,請查看weight:
from tkinter import *
root = Tk()
mood_options = ['a', 'b', 'c']
for count, mood in enumerate(mood_options):
Label(root, text=mood).grid(row=0,column=count,padx=50)
root.grid_columnconfigure(count,weight=1)
root.grid_rowconfigure(0,weight=1)
root.mainloop()
uj5u.com熱心網友回復:
你spacing的實際空間量是像素嗎?如果是這樣,請不要使用relx并且只使用x。relx必須是介于 0.0 和 1.0 之間的浮點數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335953.html
