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

2021-04-09 11:11:21 IT技术网 互联网
浏览

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

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

sudo apt-get install python-tk

手动安装

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

具体的编程操作

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

比如

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能够正常显示,

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

实际切换图片,应该用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 图片切换内容请搜索IT技术网以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT技术网!

您可能感兴趣的文章:

  • python tkinter实现界面切换的示例代码