Lecture 43

Threads in tkinter GUIs

MCS 260 Fall 2021
David Dumas

Reminders

  • Please complete the course evaluation.
  • TA award nominations are open.
  • Project 4 is due today at 6pm central, then you're done with MCS 260!
  • Worksheet 15 solutions coming soon.

After today

  • No course activities.
  • No office hours.
  • Blackboard site stays up until Dec 31.
  • My MCS 260 site stays up "forever" and will soon have everything except the videos.
  • Hope to finish grading by Fri 10 Dec.
  • Look for blackboard announcement about grades and archival site readiness.

GUI work so far

Lecture 36: Let's make buttons and labels in a window
Lecture 38: Let's make lots of widgets in a nice layout
Lecture 40: Let's make the widgets do stuff (password generator)

Threading so far

Today

The password generator application relies on a single function to generate a random password meeting certain specifications.

What if that function was slow?

Even if that's not realistic in this case, many GUI applications need to perform actions of long or uncertain duration.

The problem

The GUI is unresponsive while the program is waiting for password generation to finish.

In addition to being a bad user experience, this can cause all sorts of problems.

A solution

Move the slow part to a separate "worker" thread.

Worker thread waits for signal that work is needed.

Main thread uses a threading.Event to signal it.

Main thread runs the GUI and remains responsive even if the worker is busy.

Why not a queue?

The producer-consumer pattern, with a queue, is useful if every piece of work dispatched by the main thread needs to be done.

But in this case, we only ever want to work on the most recent request for an update, ignoring any older ones that didn't get processed.

What else could we do?

  • Perform encoding using an API (the way most actions in mobile apps occur)
  • Make auto-update an option (settings menu?) with button to manually update if auto is disabled
  • Make an application icon
  • Make a help/about popup window

References

Revision history

  • 2021-12-02 Initial publication

        print("Have a good winter break!")
        mcs260.exit(0)