[英]Gui isn't showing images in Tkinter GUI
我的代碼:
import tkinter
import os
from PIL import Image, ImageTk
articles=[]
images=[]
for filename in os.listdir('resources'):
if filename.endswith('.txt'):
articles.append(filename)
if filename.endswith('.png'):
images.append(filename)
root=tkinter.Tk()
root.geometry('500x500')
for i in range(len(images)):
path=os.path.join('resources',images[i])
image_file = tkinter.PhotoImage(file=path)
tkinter.Label(image=image_file).pack()
path=os.path.join('resources',articles[i])
file1=open(path)
tkinter.Label(text=file1.read()).pack()
root.mainloop()
使用的資源:一個名為resources 的director 存儲在與包含PNG 格式圖像的程序文件相同的目錄中,並且相應的一個.txt 文件,例如1.png 有一個1.txt。
IDE:Visual Studios 代碼
錯誤:window 留下了填充圖像所需的空間,但圖像沒有出現。 我嘗試了與我知道將加載但發生相同錯誤的其他圖像相同的代碼,我嘗試在另一個 GUI 中使用這些圖像,它們在那里加載而沒有錯誤。
必需的 Output:圖像應該出現在其下方相應的文本文章之后。
當前 Output:在應顯示圖像但文本打印正常的位置留有空格。
正如@jasonharper 所說,您的圖像正在被垃圾收集,因為沒有對它們的引用。 為避免這種情況,請在 for 循環中嘗試以下操作:
image_file = tkinter.PhotoImage(file=path)
lab = tkinter.Label(image=image_file)
lab.img = image_file
lab.pack()
lab.img = image_file
創建對圖像的引用,因此它不會被垃圾收集。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.