简体   繁体   中英

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.

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. So, how could I display an image to my GUI with grids?

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:

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 .

To display an image in tkinter you'll need to do something like:

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:

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:

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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