1

I'm building an app that's supposed to display various images from a local folder depending on which button is clicked in the app.

So far, I have started out with an example I've found and try to modify it, but I can't figure out how to summon a .jpg or .png via a button click in the first place. Here's my very basic code so far:

import tkinter as tk
    

def write_slogan():
    print("Tkinter is easy to use!")

root = tk.Tk()
frame = tk.Frame(root)
frame.pack()

button = tk.Button(frame, 
                   text="QUIT", 
                   fg="red",
                   command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
                   text="Hello",
                   command=write_slogan)
slogan.pack(side=tk.LEFT)

root.mainloop()

Essentially, instead of writing the slogan in the console, I would like the button click to trigger an image being displayed. How would I go about achieving that?

okapirider
  • 11
  • 1
  • 4

2 Answers2

2

You can pass the image filename to the function, so that different buttons show different images:

import tkinter as tk
from PIL import ImageTk
    
def show_image(imagefile):
    image = ImageTk.PhotoImage(file=imagefile)
    imagebox.config(image=image)
    imagebox.image = image # save a reference of the image to avoid garbage collection

root = tk.Tk()

frame = tk.Frame(root)
frame.pack()

button = tk.Button(frame, text="QUIT", fg="red", command=quit)
button.pack(side=tk.LEFT)

slogan = tk.Button(frame, text="Hello", command=lambda: show_image("slogan.png"))
slogan.pack(side=tk.LEFT)

other = tk.Button(frame, text="World", command=lambda: show_image("other.jpg"))
other.pack(side=tk.LEFT)

# label to show the image
imagebox = tk.Label(root)
imagebox.pack()

root.mainloop()

Since tk.PhotoImage() does not support JPG image, external Pillow module is used instead.

acw1668
  • 40,144
  • 5
  • 22
  • 34
1

I have amended your code so when you click your button the image "test.png" will display on a label.

Here is the code for testing, in my case "test.png" was in the same directory as my Python script.

import tkinter as tk

render = None
def write_slogan():
    # get image and display
    image = tk.PhotoImage(file = "test.png")
    imageLabel.configure(image = image)
    imageLabel.image = image
    

root = tk.Tk()
frame = tk.Frame(root)
frame.pack()

button = tk.Button(frame, 
                   text="QUIT", 
                   fg="red",
                   command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
                   text="Hello",
                   command=write_slogan)
slogan.pack(side=tk.LEFT)

imageLabel = tk.Label(frame)
imageLabel.pack(side=tk.LEFT)

root.mainloop()

Also, this thread was helpful.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Jack Dane
  • 402
  • 3
  • 12