Flashing Tkinter Labels

10,730

The basic idea is to create a function that does the flash (or half of a flash), and then use after to repeatedly call the function for as long as you want the flash to occur.

Here's an example that switches the background and foreground colors. It runs forever, simply because I wanted to keep the example short. You can easily add a counter, or a stop button, or anything else you want. The thing to take away from this is the concept of having a function that does one frame of an animation (in this case, switching colors), and then scheduling itself to run again after some amount of time.

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.label = tk.Label(self, text="Hello, world", 
                              background="black", foreground="white")
        self.label.pack(side="top", fill="both", expand=True)
        self.flash()

    def flash(self):
        bg = self.label.cget("background")
        fg = self.label.cget("foreground")
        self.label.configure(background=fg, foreground=bg)
        self.after(250, self.flash)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()
Share:
10,730
user2993584
Author by

user2993584

Updated on June 04, 2022

Comments

  • user2993584
    user2993584 almost 2 years

    I'm a beginner programmer in python and have recently began using tkinter though I have come across a problem which I can't solve.

    Basically I have two entry boxes.

    • Entry1 = message
    • Entry2 = no. of flashes

    (This is just an example of what I need.)

    All I need is a for loop for a label to pop up and flash entry1 as many times as entry2, yes I realize how to get the entry inputs but I have no idea how to get the label to continuously flash, I have tried pack_forget and .destroy methods for the label in a loop, but unfortunately it does not display as it almost instantly clears it from the screen again.

  • gnr
    gnr almost 8 years
    What about using Styles? Do you just switch the style of a label every half second or is there a better way?