How Can I Make Text Blinking On Canvas?

Viewed 83
import tkinter as tk
from PIL import ImageTk
flag=True
win=tk.Tk()
def function():
    global flag
    if flag:
        canvas.create_text(134,26,fill="black",font="Times 26 bold",text="Blinking...")
    flag=not(flag)
canvas=tk.Canvas(win)
img=ImageTk.PhotoImage(file=r"images.png")
canvas.create_image(0,0,anchor=tk.NW,image=img)
canvas.pack()
btn=tk.Button(win,text="Click Me To Blink...",command=function)
btn.pack()
win.mainloop()

How Can I Make Text Blinking On Canvas ? I Tried Creating A Variable flag And :

if flag:
     canvas.create_text(134,26,fill="black",font="Times 26 bold",text="Blinking...")
flag=not(flag)

But It Didn't Worked

1 Answers

You can use .after(...) to call function() periodically and then toggle the state of the canvas text item (which should be created outside function()) between "normal" and "hidden" to simulate blinking effect:

import tkinter as tk
from PIL import ImageTk

def function(show=False):
    btn.config(state="disabled")
    canvas.itemconfig(text, state="normal" if show else "hidden")
    canvas.after(200, function, not show) # change 200 to other value to adjust the blinking speed

win = tk.Tk()

canvas = tk.Canvas(win)
canvas.pack()

img = ImageTk.PhotoImage(file=r"images.png")
canvas.create_image(0, 0, anchor=tk.NW, image=img)

text = canvas.create_text(134, 26, fill="black", font="Times 26 bold", text="Blinking...")

btn = tk.Button(win, text="Click Me To Blink...", command=function)
btn.pack()

win.mainloop()
Related