简体   繁体   English

tkinter - 在 canvas 上显示文本一段时间

[英]tkinter - Displaying text on canvas for a certain time period

I am creating GUI with tkinter .我正在使用tkinter创建 GUI。 (I use tkinter 8.6 , python 3.7.9 , windows 10 ) (我使用tkinter 8.6python 3.7.9windows 10
When the button is clicked, I would like it to display the text "registered" for 2 seconds .单击按钮时,我希望它显示文本“已注册” 2 seconds

The following code works fine if the *** code block *** is commented out.如果*** code block ***被注释掉,则以下代码可以正常工作。 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.)但是,当我使用*** code block ***运行代码时,单击按钮时它甚至根本不显示文本并且没有引发错误(我也尝试过root.after(2000, my_canvas.delete(msg))而不是*** code block *** ,它是一样的。)

What might be the cause of this?这可能是什么原因? Any idea how to fix the issue?知道如何解决这个问题吗?


Code代码

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:您非常接近,您只是将 arguments 放在错误的位置:您需要这样做:

root.after(2000, my_canvas.delete, msg)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM