我正在尝试通过PhotoImage
在我的GUI中显示图像,但是它告诉我PhotoImage没有“ grid”成员。
我在所有其他小部件(例如标签和按钮)上都使用了.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()
然后,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)
"""
答案 0 :(得分:1)
注意:
grid()
返回的是NoneValue,这意味着您的变量“文件”将为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()
注意:
PhotoImage类可以从文件中读取GIF和PGM / PPM图像:
photo = PhotoImage(file="image.gif")
photo = PhotoImage(file="lenna.pgm")
如果您需要使用其他文件格式,请使用 Python Imaging 库(PIL)包含可让您加载30多种图像的类 格式,并将其转换为Tkinter兼容的图像对象:
from PIL import Image, ImageTk
image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)
您可以在Tkinter接受图像的任何地方使用PhotoImage实例 对象。
一个例子:
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
您必须在Python程序中保留对图像对象的引用,方法是将其存储在全局变量中,或者将其附加到另一个对象。
答案 1 :(得分:0)
您必须使用可以支持图像的小部件。通常是标签,但是按钮也可以配置按钮以显示图像,以及将图像添加到文本和画布小部件。