Running methods on threads
Since the main thread should be responsible only for updating the GUI and handling events, the rest of the background actions must be executed in separate threads.
Python's Standard Library includes thethreading
module to create and control multiple threads using a high-level interface that will allow us to work with simple classes and methods.
It is worth mentioning that CPython—the reference Python implementation—is inherently limited by the GIL (Global Interpreter Lock), a mechanism that prevents multiple threads from executing Python byte codes once and therefore, they cannot run in separate cores to take full advantage of multiprocessor systems. This should be kept in mind if trying to use the threading
module to improve the performance of your application.
How to do it...
The following example combines the suspension of a thread with time.sleep()
with an action scheduled via after()
:
import time import threading import tkinter as tk class App(tk.Tk): def...