I am creating GUI with tkinter
. (I use tkinter 8.6
, python 3.7.9
, windows 10
)
When the button is clicked, I would like it to display the text "registered" for 2 seconds .
The following code works fine if the *** code block ***
is commented out. It just displays the text when the button is clicked.
However, when I run the code with the *** code block ***
, it does not even display the text at all when the button is clicked and no error is raised (I also tried root.after(2000, my_canvas.delete(msg))
instead of the *** code block ***
, and it's the same.)
What might be the cause of this? Any idea how to fix the issue?
from tkinter import *
from tkinter.ttk import *
import time
root = Tk()
bg = PhotoImage(file='bg.png')
my_canvas = Canvas(root, width=300, height=185)
my_canvas.pack(fill="both", expand=True)
my_canvas.create_image(0, 0, image=bg, anchor=("nw"))
def button_click():
msg = my_canvas.create_text(100, 80, anchor="nw", fill="darkgreen", font=('Meiryo', 10, 'bold'), text="registered")
#******** code block ***********
# After 2 seconds, delete the text displayed
timeout = 2
start = time.time()
while time.time() < start + timeout:
pass
my_canvas.delete(msg)
#*********************************
button1 = Button(root, text="register", command=button_click)
button1_window = my_canvas.create_window(120, 100, anchor="nw", window=button1)
root.mainloop()
You are very very close, you just have the arguments in the wrong place: You need to do this:
root.after(2000, my_canvas.delete, msg)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.