Tkinter: ImageBrowser 2 – with canvas

This time we will create an Imagebrowser using Tkinter and canvas instead of loading the image in a label. So, nothing very different, but I think that using canvas you can be able to add a lot of more feature to this app: you could add drawings on top of the image and save them. I want also to add the chance to resize the images and other stuffs in the next future… so let’s go and watch the video.

import tkinter as tk
import glob


def insertfiles():
    for filename in glob.glob("*.png"):
        lst.insert(tk.END, filename)


def showimg(event):
    n = lst.curselection()
    filename = lst.get(n)
    img = tk.PhotoImage(file=filename)
    w, h = img.width(), img.height()
    print(filename)
    canvas.image = img
    canvas.config(width=w, height=h)
    canvas.create_image(0, 0, image=img, anchor=tk.NW)


root = tk.Tk()
root.geometry("800x600+300+50")
lst = tk.Listbox(root, width=20)
lst.pack(side="left", fill=tk.BOTH, expand=0)
lst.bind("<<ListboxSelect>>", showimg)
insertfiles()
canvas = tk.Canvas(root)
canvas.pack()

root.mainloop()

Remember to add that canvas.image = img. Without that line you won’t be able to see the image.

Live coding: Image browser with tkinter and canvas

There is the video about making an image browser with tkinter and cavas.

Tkinter test for students

Tkinter articles

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.