In my app I'm trying to have a blinking image. This image should be blinking just five times and then stay still in the frame for five seconds. Right now I've menaged to make the image flash, but I don't know how to make it blink just five times and then stay still. I've tried using a for loop but it did not solve it. This is my code:
import tkinter as tk
from PIL import ImageTk, Image, ImageGrab
class Blinking(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.first_img = ImageTk.PhotoImage(
Image.open("img_1.png")
)
self.first_img_label = tk.Label(self, image=self.first_img, foreground="black")
self.first_img_label.pack(padx=50, side="left", anchor="w")
self.button = tk.Button(self, text="start", command=self.blink_img)
self.button.pack()
def blink_img(self):
current_color = self.first_img_label.cget("foreground")
background_color = self.first_img_label.cget("background")
blink_clr = "black" if current_color == background_color else background_color
blink_img = "" if current_color == background_color else self.first_img
self.first_img_label.config(image=blink_img, foreground=blink_clr)
self.after_f = self.first_img_label.after(601, self.blink_img)
if __name__ == "__main__":
root = tk.Tk()
root.attributes("-fullscreen", True)
root.attributes("-topmost", True)
Blinking(root).pack(side="top", fill="both", expand=True)
root.mainloop()
How can I achieve this?
CodePudding user response:
Keep track of how many times you've 'blinked', then use after_cancel()
to stop when you want.
def __init__(self, parent, *args, **kwargs):
... # code removed for brevity
self.blink_count = 0 # initialize blink counter
def blink_img(self):
current_color = self.first_img_label.cget("foreground")
background_color = self.first_img_label.cget("background")
blink_clr = "black" if current_color == background_color else background_color
blink_img = "" if current_color == background_color else self.first_img
self.first_img_label.config(image=blink_img, foreground=blink_clr)
if self.blink_count < 5:
self.after_f = self.first_img_label.after(601, self.blink_img)
self.blink_count = 1
else:
self.after_cancel(self.after_f)
self.blink_count = 0 # reset counter