如何使用网格在 tkinter 中显示图像

xup*_*aii 2 python tkinter

我试图通过 向我的 GUI 显示图像PhotoImage,但是它告诉我 PhotoImage 没有“网格”成员。

我正在使用.grid()所有其他小部件,例如标签和按钮,所以我不能使用.pack(),如果这会产生影响的话。那么,如何使用网格在 GUI 上显示图像呢?

我不知道这个问题是否需要代码,但是

# it works by getting a random image from a list of files
Label(root, text=f"Enter a number between one and {len(files)}")
self.entry = Entry(root)
self.entry.grid()
Button(root, text="Submit", command=self.getEntry).grid()
Run Code Online (Sandbox Code Playgroud)

那么,getEntry() 是:

def getEntry(self):
    PhotoImage(name="",
     file=f{self.path}\\{self.showImage(self.entry.get())}).grid(row=1)
    """
    showImage() just returns the correct file 
    (e.g: files[index] where index is the input)
    """

Run Code Online (Sandbox Code Playgroud)

nci*_*ica 7

注意: grid()返回 NoneValue,这意味着您的变量“file”将为NoneValue.

要在 tkinter 中显示图像,您需要执行以下操作:

from PIL import Image, ImageTk

image = Image.open(image_path)
photo = ImageTk.PhotoImage(image)

label = Label(root, image = photo)
label.image = photo
label.grid(row=1)
# label.pack()
Run Code Online (Sandbox Code Playgroud)

笔记:

PhotoImage 类可以从文件中读取 GIF 和 PGM/PPM 图像:

photo = PhotoImage(file="image.gif")

photo = PhotoImage(file="lenna.pgm")
Run Code Online (Sandbox Code Playgroud)

如果您需要使用其他文件格式,Python 图像库 (PIL)包含的类可让您加载 30 多种格式的图像,并将它们转换为与 Tkinter 兼容的图像对象:

from PIL import Image, ImageTk

image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)
Run Code Online (Sandbox Code Playgroud)

您可以在 Tkinter 接受图像对象的任何地方使用 PhotoImage 实例。

一个例子:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
Run Code Online (Sandbox Code Playgroud)

您必须在 Python 程序中保留对图像对象的引用,方法是将其存储在全局变量中,或者将其附加到另一个对象。