Multi-threading in Python Tkinter Button

Bhavesh Singh Bisht
2 min readAug 15, 2020

I encountered an issue, where i wanted to attach two commands/functions to a Tkinter button. One function was designed to train a machine learning model and other was a Determinate Progress Bar. The whole intent was to display a progress bar on the UI that shows model training which is running in the back-end.

Using Lambda to bind multiple functions on a button

The image illustrates a button which is attached to two independent functions

The use of lambda provides the functionality to attach many functions to the button but they are executed sequentially. Hence, the progress bar would be completed before the model training has even started or vice-versa.

Using Multi-threading to bind functions

To encounter the sequential execution of the functions, they can be run on different threads. Here i have created a single function which is set as the command for the button. This function contains the threads of different desired functions.

The image shows a tkinter button which is linked to a function

The button defined on press on the UI, runs the bar function. Here i have set the bar function as the command instead of using lambda. The threads of different desired functions are defined inside the bar function.

The image demonstrates the code for determinate progress bar

The progress and sleep values can be defined according to the recorded time for model training.

--

--

Bhavesh Singh Bisht

I am passionate about data science and have a profound history of working in an AI/ML firm