How to Show and image with Tkinter

To show an image in tkinter, you will need to use the PhotoImage class from the tkinter.PhotoImage module. This class allows you to load an image from a file and display it in a tkinter GUI.

Here is an example of how you can use the PhotoImage class to display an image in a tkinter window:

import tkinter as tk
from tkinter import PhotoImage

class Window:
    
    def __init__(self, image):
        self.image = image
        self.root = tk.Tk()
        self.widgets()
        self.root.mainloop()

    def widgets(self):
        self.img = PhotoImage(file=self.image)
        label = tk.Label(self.root, image=self.img)
        label.pack()


image = "001.png"
Window(image)
If you do not want to use classes, this is some alternative code for you.

This is the image

This is the image in the window

Let’s make a slideshow

Let’s add some code to make a sort of slideshow. Well, it’s not exactly a slideshow, because you have to manually click on a button to make the images to change. With some little changes we can, after this example, see how to make it actually change at a certain pace.

import tkinter as tk
from tkinter import PhotoImage
from glob import glob


class Window:
    
    def __init__(self, images: list):
        self.images = images
        self.imagepos = 0
        self.root = tk.Tk()
        self.widgets()
        self.root.mainloop()

    def widgets(self):
        self.lab_image()
        self.start_slide_button()

    def lab_image(self):
        self.img = PhotoImage(file=self.images[self.imagepos])
        self.label = tk.Label(self.root, image=self.img)
        self.label.pack()



    def start_slide_button(self):
        self.butstart = tk.Button(self.root,
            text="Start slideshow",
            command=self.slideshow)
        self.butstart.pack()

    def slideshow(self):
        if self.imagepos < len(self.images) - 1:
            self.imagepos += 1
        else:
            self.imagepos = 0
        self.img = PhotoImage(file=self.images[self.imagepos])
        self.label["image"] = self.img


images = glob("images\\*png")
win = Window(images)

You can get the code and the images here:

https://github.com/formazione/tkinter_tutorial.git

Check for the file called image_slideshow.py

This is how the window shows up:

Bye


Subscribe to the newsletter for updates
Tkinter templates
Avatar My youtube channel

Twitter: @pythonprogrammi - python_pygame

Videos

Speech recognition game

Pygame's Platform Game

Other Pygame's posts

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.