5

I'm trying to use tkinter but this code doesn't work and I'm wondering if anyone knows why thanks.

from tkinter import *
window = Tk()
window.title("tkinter stuff")
photo1 = PhotoImage("file=hs.gif")
Label(window, image=photo1).grid(row=0,column=0,sticky=W)
window.mainloop()

Just to clarify, a window titled 'tkinter stuff' comes up but the image doesn't display. Also, there is a file called 'hs.gif' in the same folder as my code.

Thanks for the help

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
Daniel
  • 69
  • 1
  • 2

3 Answers3

3

You need to move the quotes :

photo1 = PhotoImage(file="hs.gif")
PRMoureu
  • 12,817
  • 6
  • 38
  • 48
1

Below code serves as a example to your problem, and a clean way for using images as well. You can also configure background of window

import Tkinter as tk
from PIL import ImageTk, Image
window = tk.Tk()
window.title("tkinter stuff")
window.geometry("300x300")
window.configure(background='grey')
path = "hs.gif"
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
window.mainloop()
Chetan_Vasudevan
  • 2,414
  • 1
  • 13
  • 34
1

I had problem to display images with Label widget too. This seem be a BUG with the garbage collector. I found this solution at:

https://blog.furas.pl/python-tkinter-why-label-doesnt-display-image-bug-with-garbage-collector-in-photoimage-GB.html.

import tkinter as tk  # PEP8: `import *` is not preferred

def main(root):
    img = tk.PhotoImage(file="image.png")
    label = tk.Label(image=img)
    label.pack()

    label.img = img  # <-- solution for bug 

if __name__ == "__main__":
    root = tk.Tk()
    main(root)
Nidomus
  • 11
  • 2
  • This is not a bug of the garbage collector. It is intended, because variables with 0 reference count that go out of scope are garbage collected. by assigning the image to any persisting object (like the root app or label), the reference count goes up so it doesn't get garbage collected. Why then does the Label not get garbage collected? Because behind the scenes, the label is reference counted by its master widget, by adding it to its children. Here, it wasn't supplied, so it is automatically set to the root tk instance. – ProblemsLoop May 31 '23 at 09:34
  • Thank you so much for this explanation! I ended up interpreting it incorrectly what was happening, and it really isn't just a bug ;D. I spent a long time racking my brain trying to understand why the image wasn't loading in my case. I ended up resolving it this way, but I didn't quite understand the solution. Thanks! – Nidomus Jun 01 '23 at 12:19