问题
i am new to python and started working with tkinter as canvas.
up to now i used .update() to update my canvas. but there is also a .after() method. could anyone explain me this function (with an example please :) ) and is there a difference between:
root.after(integer,call_me)
and
while(True):
time.sleep(integer)
root.update()
call_me
i have searched already and couldn't find a good explanation (and my .after examples wont work neither :( ).
回答1:
update()
yields to the event loop (mainloop
), allowing it to process pending events.
after
, when given one or more arguments, simply places an event on the event queue with a timestamp. The event won't be processed until the given time has passed and the event loop has a chance to process it.
The important thing to know is that the event loop needs to be able to constantly respond to events. Events aren't just used for button clicks and keyboard keys, it is used to respond to requests to redraw the windows, scroll data, change borders and colors when you hover over widgets, etc.
When you call sleep()
, the program does exactly that - it sleeps. While it is sleeping it is unable to process any events. Any sleeping will cause your GUI to stutter. The longer the sleep, the more noticeable the stutter.
回答2:
root.after(integer, call_me)
is similar to
while(True):
time.sleep(integer)
root.update()
call_me()
but it does it within the main loop, integer
specifies the milliseconds rather than the seconds, and you can continue to do things after you call it, because it does it in the background.
回答3:
after
is time wait. update
is refresh tkinter
tasks.
after
is use to move objects (for example), while refresh
allow to refresh the screen.
time.sleep(integer)
don't allow to do anything else when sleeping (blocking)!
While after
allow tkinter
to do other things.
回答4:
if you want all program waits for excution your function , just use:
def MineAfter(var):
time.sleep(var)
root.update()
MineAfter(2)
My_function(var1,var2)
if you want your function waits for some time while program continue execution use:
root.after(100,lambda:my_function(var1,var2))
or for functions without variables:
root.after(100,my_function)
来源:https://stackoverflow.com/questions/35258218/after-vs-update-in-python