The tkinter window!
import tkinter as tk root = tk.Tk() root.geometry("400x400") root.mainloop()
The list of image file names!
We’ ve created the window, now let’s add a list with all the images name as items of the list.
import tkinter as tk import glob root = tk.Tk() root.geometry("400x400") lst = tk.Listbox(root) lst.pack(side="left", fill=tk.Y, expand=1) namelist = [i for i in glob.glob("*png")] for fname in namelist: lst.insert(tk.END, fname) root.mainloop()
A label with the images
Now we need to show the images; we will use a label for this in this way:
img = tk.PhotoImage(file="Idle (5)_ltl.png") lab = tk.Label(root, text="hello", image=img) lab.pack(side="left")
We create an image object with PhotoImage and then we put it as value of the image argument in the Label
Now we need that when we select an item in the list we see that images in the label.
- we bind the listbox to a function (show)
- the show function load the new image and show it in the label
- REMEMBER: that lab.image = img is important to see the image (you won’t see it without it, because the garbage collectors would delete it)
def show(e): n = lst.curselection() fname = lst.get(n) img = tk.PhotoImage(file=fname) lab.config(image=img) lab.image = img lst.bind("<<ListboxSelect>>", showimg)
The whole code
import tkinter as tk import glob root = tk.Tk() root.geometry("400x400") def showimg(e): n = lst.curselection() fname = lst.get(n) img = tk.PhotoImage(file=fname) lab.config(image=img) lab.image = img print(fname) lst = tk.Listbox(root) lst.pack(side="left", fill=tk.Y, expand=1) namelist = [i for i in glob.glob("*png")] for fname in namelist: lst.insert(tk.END, fname) lst.bind("<<ListboxSelect>>", showimg) img = tk.PhotoImage(file="Idle (5)_ltl.png") lab = tk.Label(root, text="hello", image=img) lab.pack(side="left") root.mainloop()
How the GUI looks like
Video of the live conding of Tkinter Image Browser
Version 2 made using tkinter and canvas (instead of label)
Go here to this link to see the new version. In this one you will be able to use the canvas widget to show the images instead of the label b. I think that the canvas is more flexible than the label, because you can draw on it and you can place the image in a precise spot on the canvas etc. So, I think we can make some cool applications starting from this. Go the following link to the post below to see how to do it. It is very similar to the code for the label, there will be no difficulty in understanding it. Just stay tuned for the next articles about tkinter and images.