4

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()?

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46
Lance Shi
  • 1,127
  • 3
  • 13
  • 28

1 Answers1

6

The answer should be never. Even if your code works with .update() there will be no garentee 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 harmfull?

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.

Thingamabobs
  • 7,274
  • 5
  • 21
  • 54
  • 3
    Great answer! The tcl'ers wiki also has a long writeup on why [update is considered harmful](https://wiki.tcl-lang.org/page/Update+considered+harmful). Initially written by one of the authors of tcl and tk, it starts with _"Virtually any update is ill-considered!"_. It's written from the perspective of a tcl programmer, but it's equally applicable to tkinter. – Bryan Oakley Mar 24 '21 at 13:37