简体   繁体   中英

Python Tkinter - hide a widget after some time

I want to draw a widget (in this example, a canvas) and then remove it after some time. Like a message that shows up and then is removed, just so that the user can read it, but there is no need to click "ok" or something like that to remove the message.

Here is an example code.

from tkinter import*

root = Tk()

canvas_1 = Canvas(root, width = 300, height = 300, bg = 'white')
canvas_1.grid(column = 0, row = 0)

canvas_2 = Canvas(canvas_1, width = 200, height = 200, bg = 'blue')
canvas_2.place(x = 50, y = 50)

canvas_1.after(1000, canvas_2.place_forget())

root.mainloop()

The problem is that it seems tkinter runs the after() method before everything else, no matter when it is called in the code. The result is that the canvas_2 never appears.

I've tried time.sleep() but it seems to work in the same way in this case.

Thanks in advance.

The issue is that your after statement is actually causing canvas_2 to be forgotten immediately. This is because the ()'s are telling Python to run the place_forget function (rather than run it in 1000ms). Remove the ()'s and you will be good to go. Best of luck.

Replace this:

canvas_1.after(1000, canvas_2.place_forget())

with this:

canvas_1.after(1000, canvas_2.place_forget)

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.

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