【问题标题】:Tkinter: use after five times and then stopTkinter: use after five times and then stop
【发布时间】:2022-12-01 22:22:54
【问题描述】:

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?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2016-03-25
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      • 2014-08-17
      • 2015-05-24
      • 2022-11-21
      • 2022-11-20
      • 1970-01-01
      相关资源
      最近更新 更多