网络编程
位置:首页>> 网络编程>> Python编程>> python基于tkinter点击按钮实现图片的切换

python基于tkinter点击按钮实现图片的切换

作者:Chauncey_Wang  发布时间:2022-03-18 10:22:31 

标签:tkinter,点击按钮,图片,切换

tkinter是python的标准Tk GUI工具包的接口,在windows下如果你安装的python3,那在安装python的时候,就已经自动安装了tkinter了

如果是在linux系统中,则不会自动安装tkinter,需要通过


sudo apt-get install python-tk

手动安装

首先先介绍一下,tkinter本身只支持gif等少数几个图片格式,如果图片并不复杂,建议直接右击图片,进入编辑,在画图界面将图片另存为gif格式就可以使用了(连png和jpeg都不支持。。。真的有点魔幻)

python基于tkinter点击按钮实现图片的切换

python基于tkinter点击按钮实现图片的切换

具体的编程操作

如果你尝试直接重写设置图片的有关代码会出问题

比如


import tkinter as tk
top = tk.Tk()

top.title("划水摸鱼")  # 设置窗口
width = 260
height = 500
top.geometry(f'{width}x{height}')  # 设置窗口大小

img_gif = tk.PhotoImage(file='./动作/问号.gif')  # 设置图片
label_img = tk.Label(top, image=img_gif)  # 设置预显示图片
label_img.place(x=30, y=120)

def change_img():   # 设置按钮事件
   img_gif0 = tk.PhotoImage(file='./动作/走.gif')
   label_img.configure(image=img_gif0)
   label_img.place(x=30, y=120)

button = tk.Button(top, text='Prediction', command=change_img)  # 设置按钮
button.place(x=90, y=330)

top.mainloop()

在这里我直接重写了label_img,但是实际效果是

问号.gif能够正常显示,

python基于tkinter点击按钮实现图片的切换

点击按钮后,走.gif无法显示

python基于tkinter点击按钮实现图片的切换

实际切换图片,应该用configure实现

正确的操作如下


import tkinter as tk
top = tk.Tk()

top.title("划水摸鱼")  # 设置窗口
width = 260
height = 500
top.geometry(f'{width}x{height}')  # 设置窗口大小

img_gif = tk.PhotoImage(file='./动作/问号.gif')  # 设置图片
img_gif0 = tk.PhotoImage(file='./动作/走.gif')

label_img = tk.Label(top, image=img_gif)  # 设置预显示图片
label_img.place(x=30, y=120)

def change_img():
   label_img.configure(image=img_gif0)  # 设置按钮事件

button = tk.Button(top, text='Prediction', command=change_img)  # 设置按钮
button.place(x=90, y=330)

top.mainloop()

具体效果

python基于tkinter点击按钮实现图片的切换

点击按钮后

python基于tkinter点击按钮实现图片的切换

来源:https://blog.csdn.net/weixin_39518984/article/details/115480844

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com