Reputation: 69
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
Upvotes: 5
Views: 6647
Reputation: 21
I had problem to display images with Label widget too. This seem be a BUG with the garbage collector. I found this solution at:
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)
Upvotes: 2
Reputation: 2414
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()
Upvotes: 1
Reputation: 13327
You need to move the quotes :
photo1 = PhotoImage(file="hs.gif")
Upvotes: 4