Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load an image into a python 3.4 tkinter window?

I've spent some time looking online and so far haven't found anything that answers this without using PIL, which i can't get to work is there another way to do this simply?

like image 561
LuGibs Avatar asked Jan 26 '16 21:01

LuGibs


1 Answers

tkinter has a PhotoImage class which can be used to display GIF images. If you want other formats (other than the rather outdated PGM/PPM formats) you'll need to use something like PIL or Pillow.

import Tkinter as tk

root = tk.Tk()
image = tk.PhotoImage(file="myfile.gif")
label = tk.Label(image=image)
label.pack()
root.mainloop()

It's important to note that if you move this code into a function, you may have problems. The above code works because it runs in the global scope. With a function the image object may get garbage-collected when the function exits, which will cause the label to appear blank.

There's an easy workaround (save a persistent reference to the image object), but the point of the above code is to show the simplest code possible.

For more information see this web page: Why do my Tkinter images not appear?

like image 62
Bryan Oakley Avatar answered Nov 15 '22 09:11

Bryan Oakley