
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to use Thread in Tkinter Python?
With Tkinter, we can call multiple functions at a time using Threading. It provides asynchronous execution of some functions in an application.
In order to use a thread in Python, we can import a module called threading and subclass its Thread class. Inside our new class, we need to overwrite the Run method and perform our logic in there.
So, basically with threading, we can do multiple work at a time. To achieve threading in our application, Tkinter provides the Thread() function.
Let us take an example and create a thread which will sleep for some time and then execute another function in parallel.
For this example, we will import the Time module and the threading module defined in the Tkinter library.
Example
#Import all the necessary libraries from tkinter import * import time import threading #Define the tkinter instance win= Tk() #Define the size of the tkinter frame win.geometry("700x400") #Define the function to start the thread def thread_fun(): label.config(text="You can Click the button or Wait") time.sleep(5) label.config(text= "5 seconds Up!") label= Label(win) label.pack(pady=20) #Create button b1= Button(win,text= "Start", command=threading.Thread(target=thread_fun).start()) b1.pack(pady=20) win.mainloop()
Output
Running the above code will create a button and a thread which works on a label.
After 5 seconds, the thread will automatically pause.
- Related Articles
- How to use Tkinter in python to edit the title bar?
- How to use a Background Thread in Swift?
- How to use isAlive() method of Thread class in Java?
- How to catch a thread's exception in the caller thread in Python?
- How to Use Images as Backgrounds in Tkinter?
- How to use the Entry widget in Tkinter?
- How to use rgb color codes in tkinter?
- How to use a custom font in Tkinter?
- How to install Tkinter in Python?
- How to use Bitmap images in Button in Tkinter?
- How to use set the priority for a thread in android?
- How to use Unicode and Special Characters in Tkinter?
- How to use images in Tkinter using photoimage objects?
- Use boolean value to stop a thread in Java
- How to use an Image as a button in Tkinter?
