简体   繁体   English

Gui 未在 Tkinter GUI 中显示图像

[英]Gui isn't showing images in Tkinter GUI

My code:我的代码:

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 Used: A director named resources stored in same directory as the program file containing images in PNG format and correspondingly a.txt file eg 1.png has a 1.txt.使用的资源:一个名为resources 的director 存储在与包含PNG 格式图像的程序文件相同的目录中,并且相应的一个.txt 文件,例如1.png 有一个1.txt。

IDE: Visual Studios Code IDE:Visual Studios 代码

Error: The window leaves space required to fill the image but image doesn't appear.错误:window 留下了填充图像所需的空间,但图像没有出现。 I tried the same code with other images that I know will load but same error occurs, I tried using these images in another GUI, there they loaded without error.我尝试了与我知道将加载但发生相同错误的其他图像相同的代码,我尝试在另一个 GUI 中使用这些图像,它们在那里加载而没有错误。

Required Output: The images should appear followed by corresponding text article beneath them.必需的 Output:图像应该出现在其下方相应的文本文章之后。

Current Output: Spaces are left where images should appear but text prints fine.当前 Output:在应显示图像但文本打印正常的位置留有空格。

As @jasonharper said, your images are being garbage collected because there is no reference to them.正如@jasonharper 所说,您的图像正在被垃圾收集,因为没有对它们的引用。 To avoid that, try something like this in your for loop:为避免这种情况,请在 for 循环中尝试以下操作:

image_file = tkinter.PhotoImage(file=path)
lab = tkinter.Label(image=image_file)
lab.img = image_file
lab.pack()

lab.img = image_file creates a reference to the image, so it is therefore not garbage collected. lab.img = image_file创建对图像的引用,因此它不会被垃圾收集。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM