Search code examples
pythontkinter

When should I use root.update() in tkInter for python


I am new to tkinter. Sometimes when I read the code from github, it contains code like root.update().

When I search for documents for tkinter, I usually find the methods list for each widget, but not for the Tk() root object itself. Also, usually when I set config for each widget, it automatically updates the view. So I am a bit confused by when should I be using root.update()?


Solution

  • The answer should be never. Even if your code works with .update() there will be no guarantee that it will ever do so. The quick answer is, you will never know what you are doing with this command at the very moment. Use .update_idletasks() instead.

    Out of the docs:

    update services all outstanding events, including those that come due while update is operating. It was provided to allow tasks such as refreshing a GUI to happen immediately. coroutine provides another way to structure code so that events can be serviced at strategic points in the control flow. Even before coroutine was available, many Tcl programmers found that if the need to use update arises, it's a clue that the script should be restructured.

    update works by performing the following steps in a loop until no events are serviced in one iteration:

    Service the first event whose scheduled time has come. If no such events are found, service all events currently in the idle queue, but not those added once this step starts.

    update_idletasks skips the first step, processing only events in the idle queue.

    Why is it harmful?

    The issue is that update has virtually unconstrained side effects. Code that calls update doesn't know what any random event handler might have done to its data while the update was in progress. This fact is the source of insidious bugs.