Simula Simula - 1 month ago 5x
Python Question

Adding image to Tkinter

I have added a image file to my code in tkinter but it basically fills my the whole frame so if its possible can you recommend a tutorial that shows or explains how to do this.... unless you can show me on here.

I havent added my full code but the code below should display a test image once you have it saved in the python directory.

I would like to create 'next' button which would open up a new frame with another image on it.

from Tkinter import *

root = Tk()
ButtonImage = PhotoImage(file='test.gif')
testButton = Button(root, image=ButtonImage)


You could try something like this:

from Tkinter import *
from glob import glob

class ImageFrame(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.images = glob("*.gif")
        self.cur = 0
        # label showing the image
        self.image = PhotoImage()
        imagelabel = Label(self, image=self.image)
        imagelabel.grid(row=1, column=1)
        # button cycling through the images
        button = Button(self, text="NEXT", command=self.show_next)
        button.grid(row=2, column=1)
        # layout and show first image

    def show_next(self):
        self.cur = (self.cur + 1) % len(self.images)


Some explanations:

  • glob is used to get a list of all files matching some pattern in the current directory
  • grid is a simple but quite flexible layout manager for Tkinter (see Tkinter reference)
  • the show_next method, which is bound to the button, cycles through the images and binds a new image to the PhotoImage using configure

The result is a simple frame showing a large image and a button, cycling though the gif images in the current directory.