2

I want to display 2 different images when a button is pressed. I have two images, and corresponding 2 buttons. I'm using the panel's configure function to try to change the image but to no avail. How would I accomplish this? Thank you!

import Tkinter as tk
from PIL import ImageTk, Image

def next(panel):
    path = "2.jpg"
    img = ImageTk.PhotoImage(Image.open(path))
    panel.configure(image=img)
    panel.image = img # keep a reference!

def prev(panel):
    path = "1.jpg"
    img = ImageTk.PhotoImage(Image.open(path))
    panel.configure(image=img)
    panel.image = img # keep a reference!

#Create main window
window = tk.Tk()

#divide window into two sections. One for image. One for buttons
top = tk.Frame(window)
top.pack(side="top")
bottom = tk.Frame(window)
bottom.pack(side="bottom")

#place image
path = "1.jpg"
img = ImageTk.PhotoImage(Image.open(path))
panel = tk.Label(window, image = img)
panel.image = img # keep a reference!
panel.pack(side = "top", fill = "both", expand = "yes")


#place buttons
prev_button = tk.Button(window, text="Previous", width=10, height=2, command=prev(panel))
prev_button.pack(in_=bottom, side="left")
next_button = tk.Button(window, text="Next", width=10, height=2, command=next(panel))
next_button.pack(in_=bottom, side="right")

#Start the GUI
window.mainloop()
user2122589
  • 275
  • 1
  • 5
  • 17

1 Answers1

2

To pass arguments to a button callback command, you need the lambda keyword, else the functions will be called at the time of button creation.

#place buttons
prev_button = tk.Button(window, text="Previous", width=10, height=2, command=lambda: prev(panel))
prev_button.pack(in_=bottom, side="left")
next_button = tk.Button(window, text="Next", width=10, height=2, command=lambda: next(panel))
next_button.pack(in_=bottom, side="right")
Khristos
  • 973
  • 2
  • 11
  • 22