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

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

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

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

猜你喜欢

  • SQL重复记录处理(查找,过滤,删除)

    2008-11-17 20:47:00
  • 大内存SQL Server数据库的加速剂

    2009-03-06 14:18:00
  • python用线性回归预测股票价格的实现代码

    2023-01-24 02:14:31
  • MATLAB中print函数使用示例详解

    2023-11-18 04:18:04
  • Oracle数据库密码文件的使用与维护

    2010-07-28 13:27:00
  • Python 3.x 新特性及10大变化

    2023-02-05 09:17:36
  • python中sys模块是做什么用的

    2021-04-30 10:04:48
  • banner字体设计与应用

    2009-07-06 14:42:00
  • 视觉设计的一致性与用户体验

    2010-01-06 13:38:00
  • Python游戏开发之魔塔小游戏的实现

    2022-08-26 16:14:35
  • Python数据类型转换汇总

    2023-05-13 16:33:00
  • Mootools 1.2教程(10)——Fx.Tween的使用

    2008-12-02 18:03:00
  • Python入门Anaconda和Pycharm的安装和配置详解

    2022-12-21 20:25:07
  • TOPI如何使TVM代码不那么样板化

    2022-02-02 00:22:07
  • Python自然语言处理之切分算法详解

    2023-02-02 04:46:34
  • Python实现扫描局域网活动ip(扫描在线电脑)

    2022-10-02 02:38:52
  • 网站改版常见问题答疑

    2008-08-22 18:31:00
  • 在VSCode中配置PHP开发环境的实战步骤

    2023-06-06 02:13:06
  • matplotlib事件处理基础(事件绑定、事件属性)

    2023-02-02 19:34:32
  • Pandas.DataFrame转置的实现 <font color=red>原创</font>

    2022-03-02 03:07:34
  • asp之家 网络编程 m.aspxhome.com