How to Master the Python Tkinter Mainloop?

In this tutorial, I will explain how to master the Python Tkinter mainloop in detail with real-world examples. One of my team members asked me about Tkinter mainloop which made me explore more about this topic and I will share my experiences and provide a step-by-step guide to help you master Python Tkinter mainloop.

Python Tkinter Mainloop

The Tkinter mainloop() is an infinite loop that runs in the background of your Python GUI application. It waits for events to occur, such as user interactions (clicks, key presses) or system events, and processes them accordingly. The mainloop() keeps the application running until the user closes the window or the program explicitly calls the quit() method.

Read How to Cancel Scheduled Functions with after_cancel() in Python Tkinter?

Master the Python Tkinter Mainloop

Let’s get into some practical examples of using the Tkinter mainloop() in real-world scenarios specific to the United States.

Example 1: A Simple User Registration Form

Suppose you’re creating a user registration form for a website targeting users in the United States. Here’s how you can use Tkinter and the mainloop() to achieve this:

import tkinter as tk
from tkinter import ttk

def submit_form():
    name = name_entry.get()
    email = email_entry.get()
    state = state_combobox.get()
    print(f"Name: {name}")
    print(f"Email: {email}")
    print(f"State: {state}")

root = tk.Tk()
root.title("User Registration Form")

name_label = ttk.Label(root, text="Name:")
name_label.grid(row=0, column=0, padx=5, pady=5)
name_entry = ttk.Entry(root)
name_entry.grid(row=0, column=1, padx=5, pady=5)

email_label = ttk.Label(root, text="Email:")
email_label.grid(row=1, column=0, padx=5, pady=5)
email_entry = ttk.Entry(root)
email_entry.grid(row=1, column=1, padx=5, pady=5)

state_label = ttk.Label(root, text="State:")
state_label.grid(row=2, column=0, padx=5, pady=5)
state_combobox = ttk.Combobox(root, values=["California", "Texas", "Florida", "New York"])
state_combobox.grid(row=2, column=1, padx=5, pady=5)

submit_button = ttk.Button(root, text="Submit", command=submit_form)
submit_button.grid(row=3, column=0, columnspan=2, padx=5, pady=5)

root.mainloop()

You can look at the output in the screenshot below.

Master the Python Tkinter Mainloop

In this example, we create a user registration form with fields for name, email, and state. The mainloop() is called at the end to start the event loop and keep the application running until the user closes the window. When the user clicks the “Submit” button, the submit_form() function is called, which retrieves the entered values and prints them.

Check out How to Create GUI Layouts with Python Tkinter Separator?

Example 2: A Tkinter Application with Multiple Windows

Let’s say you’re building a Tkinter application for a US-based company that requires multiple windows. Here’s how you can structure your code and use the mainloop():

import tkinter as tk
from tkinter import ttk

def open_settings_window():
    settings_window = tk.Toplevel(root)
    settings_window.title("Settings")
    # Add widgets to the settings window
    settings_window.mainloop()

root = tk.Tk()
root.title("Main Window")

main_label = ttk.Label(root, text="Welcome to the Main Window")
main_label.pack(padx=20, pady=20)

settings_button = ttk.Button(root, text="Open Settings", command=open_settings_window)
settings_button.pack(padx=20, pady=10)

root.mainloop()

You can look at the output in the screenshot below.

How to Master the Python Tkinter Mainloop

In this example, we have a main window with a label and a button. When the “Open Settings” button is clicked, the open_settings_window() function is called, which creates a new window (Toplevel) for the settings. The mainloop() is called for both the main window and the settings window to ensure they remain responsive to user interactions.

Read How to Add Functions to Python Tkinter?

Example 3: A Tkinter Mainloop exit

Suppose you are building a Tkinter application for a US-based company that requires an exit button to exit from the window. Here’s how you can structure your code and use the mainloop():

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('300x200')

Button(
    ws,
    text='Exit',
    command=lambda:ws.destroy()
).pack(expand=True)

ws.mainloop()

Python Tkinter provides a destroy() function using which we can exit the mainloop in Python Tkinter. destroy() function can be applied on parent windows, frames, canvas, etc.

You can look at the output in the screenshot below.

Master the Python Tkinter Mainloop exit

Check out How to Create a Filter() Function in Python Tkinter?

Handle the Mainloop Blocking Effect

One common issue developers face when using the Tkinter mainloop() is its blocking effect. Once the mainloop() is called, the program execution stays within that loop until the window is closed. This can be problematic if you need to perform other tasks concurrently.

To overcome this, you can use techniques like threading or the after() method to schedule tasks to run alongside the mainloop(). For example, if you want to update a label every second while the main window is running, you can use the after() method:

import tkinter as tk
from tkinter import ttk
import time

def update_time():
    current_time = time.strftime("%H:%M:%S")
    time_label.config(text=current_time)
    root.after(1000, update_time)

root = tk.Tk()
root.title("Current Time")

time_label = ttk.Label(root, font=("Arial", 24))
time_label.pack(padx=20, pady=20)

update_time()  # Start updating the time

root.mainloop()

You can look at the output in the screenshot below.

Master the Python Tkinter Mainloop blocking effect

In this example, the update_time() function is called initially and then scheduled to run every 1000 milliseconds (1 second) using the after() method. This allows the time to be updated continuously while the main event loop is running.

Read How to Create a Python Tkinter Panel with Search Functionality?

Best Practices for Using the Tkinter Mainloop

Here are some best practices to keep in mind when working with the Tkinter mainloop():

  • Always call mainloop() at the end of your Tkinter program to start the event loop and keep the application running.
  • If you have multiple windows in your application, call mainloop() for each window to ensure they remain responsive.
  • Use techniques like threading or the after() method to perform tasks concurrently with the mainloop() when necessary.
  • Avoid blocking the mainloop() with long-running tasks, as it will freeze your application. Instead, use appropriate concurrency mechanisms.
  • Keep your event handlers (callbacks) short and efficient to maintain a responsive user interface.

Check out How to Create Scrollable Frames with Python Tkinter?

Conclusion

In this tutorial, We discussed various examples to master the Python Tkinter mainloop like an example of a simple user registration form, a Tkinter application with multiple windows, and a Tkinter mainloop exit. We also learned how to handle the mainloop blocking effect and some best practices for using the Tkinter mainloop.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.