简体   繁体   English

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

[英]How to display an image in tkinter using grid

I am trying to display an image to my GUI, through PhotoImage , however it is telling me that PhotoImage has no "grid" member. 我正在尝试通过PhotoImage将图像显示到我的GUI,但它告诉我PhotoImage没有“ grid”成员。

I am using .grid() for all of my other widgets, like labels and buttons, so I can't use .pack() , if that would make a difference anyway. 我使用.grid()我所有的其他部件,如标签和按钮,所以我不能使用.pack()如果会有所作为反正。 So, how could I display an image to my GUI with grids? 那么,如何使用网格将图像显示到GUI?

I don't know if code is necessary for this question, but 我不知道此问题是否需要代码,但是

# 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()

Then, getEntry() is: 然后,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)
    """

NOTE: grid() is returning NoneValue, which means that your variable 'file' will be NoneValue . 注意: grid()返回NoneValue,这意味着变量'file'将是NoneValue

To display an image in tkinter you'll need to do something like: 要在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()

NOTE: 注意:

The PhotoImage class can read GIF and PGM/PPM images from files: PhotoImage类可以从文件读取GIF和PGM / PPM图像:

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

photo = PhotoImage(file="lenna.pgm")

If you need to work with other file formats, the Python Imaging Library (PIL) contains classes that lets you load images in over 30 formats, and convert them to Tkinter-compatible image objects: 如果您需要使用其他文件格式,则Python Imaging Library(PIL)包含一些类,这些类使您可以加载30多种格式的图像,并将其转换为Tkinter兼容的图像对象:

from PIL import Image, ImageTk

image = Image.open("lenna.jpg")
photo = ImageTk.PhotoImage(image)

You can use a PhotoImage instance everywhere Tkinter accepts an image object. 您可以在Tkinter接受图像对象的任何地方使用PhotoImage实例。

An example: 一个例子:

label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()

You must keep a reference to the image object in your Python program, either by storing it in a global variable, or by attaching it to another object. 您必须在Python程序中保留对图像对象的引用,方法是将其存储在全局变量中,或者将其附加到另一个对象。

You have to use a widget that can support images. 您必须使用可以支持图像的小部件。 Typically a label, but button can also configure a button to show an image, as well as add images to text and canvas widgets. 通常是标签,但是按钮也可以配置按钮以显示图像,以及将图像添加到文本和画布小部件。

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

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