is there a better option to work with other than time.sleep() in tkinter GUI

18 views Asked by At

Guys everytime I use time.sleep() my program misbehaves and I needed to delay my program for a few seconds before proceeding what can I do

I imported time and my program started to hang I cant even click on the button when I used window.sleep I was creating a bank program and I wanted to change the color of the display text to red when someone tries to withdraw an amount that is greater than the balance then the program should sleep for a few seconds then turn the text back to green.

1

There are 1 answers

0
Bryan Oakley On

You can use the after method, which schedules code to be run in the future.

In the following example, when you click the button the text will turn red, then 5 seconds (5000 milliseconds) later it will turn green.

import tkinter as tk

class Example:
    def __init__(self):
        root = tk.Tk()
        self.button = tk.Button(root, text="Click me", command=self.do_click)
        self.label = tk.Label(root, text="Hello, world")
        self.button.pack(side="left")
        self.label.pack(side="left", fill="x")

    def do_click(self):
        def turn_it_green():
            self.label.configure(foreground="green")
            
        self.label.configure(foreground="red")
        self.label.after(5000, turn_it_green)

e = Example()
tk.mainloop()