您当前的位置:首页 > IT编程 > python
| C语言 | Java | VB | VC | python | Android | TensorFlow | C++ | oracle | 学术与代码 | cnn卷积神经网络 | gnn | 图像修复 | Keras | 数据集 | Neo4j | 自然语言处理 | 深度学习 | 医学CAD | 医学影像 | 超参数 | pointnet | pytorch | 异常检测 | Transformers | 情感分类 | 知识图谱 |

自学教程:python基于tkinter点击按钮实现图片的切换

51自学网 2021-10-30 22:46:09
  python
这篇教程python基于tkinter点击按钮实现图片的切换写得很实用,希望能帮到您。

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

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

sudo apt-get install python-tk

手动安装

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

具体的编程操作

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

比如

import tkinter as tktop = tk.Tk() top.title("划水摸鱼")  # 设置窗口width = 260height = 500top.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能够正常显示,

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

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

正确的操作如下

import tkinter as tktop = tk.Tk() top.title("划水摸鱼")  # 设置窗口width = 260height = 500top.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 图片切换内容请搜索51zixue.net以前的文章或继续浏览下面的相关文章希望大家以后多多支持51zixue.net!


Python的字符串示例讲解
python操作数据库获取结果之fetchone和fetchall的区别说明
万事OK自学网:51自学网_软件自学网_CAD自学网自学excel、自学PS、自学CAD、自学C语言、自学css3实例,是一个通过网络自主学习工作技能的自学平台,网友喜欢的软件自学网站。