使用Python Tkinter通过单击按钮更改图像

使用Python Tkinter通过单击按钮更改图像,python,tkinter,Python,Tkinter,我想在按下按钮时显示两个不同的图像。我有两个图像和相应的两个按钮。我正在使用面板的配置功能尝试更改图像,但没有效果。我将如何做到这一点?谢谢大家! 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

我想在按下按钮时显示两个不同的图像。我有两个图像和相应的两个按钮。我正在使用面板的配置功能尝试更改图像,但没有效果。我将如何做到这一点?谢谢大家!

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()

要将参数传递给按钮回调命令,需要使用
lambda
关键字,否则将在创建按钮时调用函数

#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")