几秒钟后更改按钮图像(Tkinter)

时间:2020-10-09 17:32:34

标签: python button tkinter sleep

您如何编码按钮,按下按钮后它会更改其图像,但是3秒钟后它会变回其正常状态?

我设法通过单击来更改按钮图像,但是函数sleep()停止了整个Tkinter Mainloop,这导致按钮不执行任何操作。

1 个答案:

答案 0 :(得分:1)

如上所述,您需要执行另一个将图像改回原位的功能。然后,您可以使用after方法安排该函数在以后运行。这将是使用Button子类创建结合了这些功能和图像数据的Button自定义类型的理想场所。像这样:

import tkinter as tk

class EleckTroniiKz(tk.Button):
    """A new type of Button that shows one image, changes to another image
    when clicked, and changes back to the original image after 3 seconds"""
    def __init__(self, master=None, image1=None, image2=None, **kwargs):
        self.command = kwargs.pop('command', None)
        super().__init__(master, **kwargs)
        self.image1 = tk.PhotoImage(file=image1)
        self.image2 = tk.PhotoImage(file=image2)
        self.config(image=self.image1, command=self.on_click)

    def on_click(self):
        self.config(image=self.image2)
        if self.command: self.command()
        # schedule the after_click function to run 3 seconds from now
        self.after(3000, self.after_click)

    def after_click(self):
        self.config(image=self.image1)

### test / demo
def main():
    root = tk.Tk()
    btn = EleckTroniiKz(root, 'OFF.gif', 'ON.gif')
    btn.pack()
    root.mainloop()

if __name__ == '__main__':
    main()