使用 Python Tkinter 使用按钮单击更改图像 [英] Changing Image with Button Click with Python Tkinter

查看:60
本文介绍了使用 Python Tkinter 使用按钮单击更改图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在按下按钮时显示 2 个不同的图像.我有两个图像,以及相应的 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()

推荐答案

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

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

这篇关于使用 Python Tkinter 使用按钮单击更改图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆