首页 > 解决方案 > 使用 tkinter 中的按钮将 GIF 替换为另一个 GIF

问题描述

我正在尝试创建一个程序,然后在启动时显示一个 gif 和一个按钮,上面写着:“关闭系统”。单击时,我希望 gif 更改为另一个 gif,并将按钮替换为显示“打开系统”的按钮。

我正是这样做的,但是当我单击按钮时,第一个 GIF 仍保留在屏幕上。但是,您可以在快速单击时看到第二个 GIF 弹出和弹出。

编辑* 由于格式问题,我不得不重新定义我的代码,你在我的代码中看到的 def main(): 不应该存在。

这是我的代码:

    import tkinter as tk
    from PIL import Image, ImageTk
    from tkinter import *
    from tkinter import ttk

    root = tk.Tk()
    root.title('Camera System')

def update(ind):

    frame = stgImg[ind]
    ind += 1
    if ind == frameCnt:
        ind = 0
    label.configure(image=frame)
    root.after(100, update, ind)

def SystemOn():
    
    stgImg = PhotoImage(file=(filename1.gif))
    label.configure(image=stgImg)
    label.image = stgImg

    global b3
    b3=tk.Button(root,text="Turn Off System",command=lambda:SystemOff())
    b3.pack()
    b1.pack_forget()
    b2.pack_forget()

def SystemOff():

    stgImg = PhotoImage(file=(filename2.gif))
    label.configure(image=stgImg)
    label.image = stgImg

    global b2
    b2=tk.Button(root,text="Turn On System",command=lambda:SystemOn())
    b2.pack()
    b1.pack_forget()
    b3.pack_forget()

def main():

    frameCnt = 12
    root.geometry('1010x740+200+200')
    stgImg = [PhotoImage(file=(filename1.gif),
    format = 'gif -index %i' %(i)) for i in range(frameCnt)]

    label=ttk.Label(root)
    label.pack()
    root.after(0, update, 0)

    global b1
    b1=tk.Button(root,text="Turn Off System",command=lambda:SystemOff())
    b1.pack()

    root.mainloop()

标签: pythonimagetkinterbuttongif

解决方案


Here is a small program that achieves the affects described.

I've set up filedialog to load the two images and defined a button with message.

Two functions work together to replace the image and text.

import tkinter as tk
from tkinter import filedialog as fido

master = tk.Tk()

imageon = fido.askopenfilename(title ="Pick a Picture")
on = tk.PhotoImage(file = imageon)

imageoff = fido.askopenfilename(title ="Pick a Picture")
off = tk.PhotoImage(file = imageoff)

def turnOn():
    button.config(image = on, text = "Turn on system", command = turnOff)

def turnOff():
    button.config(image = off, text = "Turn off system", command = turnOn)

button = tk.Button(master, image = off, compound = "top")
button.grid(sticky = tk.NSEW)
turnOff()

master.mainloop()

推荐阅读