Gracie
Gracie

Reputation: 5

Continuous blinking text in tkinter python

I am currently creating a GUI and would like to create a continous blinking text as long as a certain condition holds. Here is a summary on how it works; 1. plot a graph and click a button to display the status of the data. If any points lie outside the limits, print a warning text that blinks continuously until you click another button to clear the status. However, I have managed to make it blink just once not continuously. see the snippet of the code Code snippet. The snippet of the buttons and the text is GUI snippet

I am new to python and tkinter as a whole so my knowledge is rusty. However, I have tried the for and while loops but the while loop froze the GUI while the for loop yielded no results. I have failed to find an answer to help. Looking forward to your help. Thank you

Upvotes: 0

Views: 496

Answers (2)

acw1668
acw1668

Reputation: 46761

You need to call .after() inside change_color() in order to blink the text periodically.

Below is the simplify code:

def status(self):

    msg = "Warning!!!\nOut of Control, study the process and eliminate assignable cause"
    write = tk.Label(self, text=msg, font=("Montserrat", 15, "bold"), fg="red")
    write.place(x=200, y=530)

    def change_color():
        write.config(fg="red" if write["fg"] == "black" else "black")
        write.after(1000, change_color)

    write.after(1000, change_color)

Upvotes: 0

nrhoopes
nrhoopes

Reputation: 209

Your change_color() method is your problem, and so is your current_color variable. You are technically only ever telling the label to change color once, after 1000ms. Then you never tell it to change again. The best way to fix this is to copy the write.after(1000, change_color) line into the bottom of your change_color() function. This will allow you to call it again after every 1000ms.

This alone won't work because you are also not resetting the current_color variable, and as such it will forever be set to 'red' the first time it is set. You fix this by copying the change_color = write.cget("foreground") into the bottom of the change_color() function as well. And due to how scoping works, you will need to make it self.current_color.

Your code will look like this:

self.current_color = write.cget("foreground")

def change_color():
    next_color = ['black', 'red']
    if self.current_color == 'red':
        write.config(foreground=next_color[0])
    elif self.current_color == 'black':
        write.config(foreground=next_color[1])

    self.current_color = write.cget("foreground")
    write.after(1000, change_color)

write.after(1000, change_color)

Upvotes: 0

Related Questions