Python Tkinter Mainloop with Examples

In this Python Tkinter tutorial, we will learn everything about Python Tkinter Mainloop. Also, we will cover these topics.

  1. Python Tkinter Mainloop
  2. Python Tkinter Mainloop Thread
  3. Python Tkinter Mainloop exit
  4. Python Tkinter Mainloop Blocking
  5. Python Tkinter Mainloop Non Blocking
  6. Python Tkinter Mainloop Update
  7. Python Tkinter Mainloop Event
  8. Python Tkinter Mainloop Timer
  9. Python Tkinter Mainloop Background

Python Tkinter Mainloop

Mainloop in Python Tkinter is an infinite loop of the application window which runs forever so that we can see the still screen.

  • The application window is like a frame that keeps on destroying every microsecond but the main loop keeps on creating a new updated window.
  • This process of destroying old window screens and creating a new one happens so fast that human eyes don’t even realize it.
  • Since the process runs infinite time that is why we are able to see the application in front of us and when we close the window then the loop terminates or exits.
  • C or C++ programmers can relate this with a situation when we run a program in C or C++ the black output window closes after showing the result. But if intentionally or accidentally the infinite loop is triggered then the black window stays and keeps on displaying the message.
  • Infinite loop projects the updated window and the process is too fast that we feel like it is updating.

Here is the code to implement the mainloop in Python Tkinter. mainloop() is always applied at the last line of the code.

from tkinter import *

ws = Tk()
ws.title('PythonGuides')

ws.mainloop()
python tkinter mainloop
mainloop in Python Tkinter

Python Tkinter Mainloop Thread

Thread is the process that goes parallel with the program as a separate entity. In other words, by using thread we can run multiple things in the same program at the same time.

  • Thread is like a branch of a program that runs as a separate entity and it merges back to the mainloop once the task is complete.
  • Thread saves users time by avoiding screen freezing while one task is running.

Read: Python Tkinter Checkbutton

Python Tkinter Mainloop exit

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

Here is the code to demonstrate Python Tkinter Mainloop Exit

In this code, we have created an Exit button that will close the window when clicked.

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('300x200')
ws.config(bg='#4a7a8c')

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

ws.mainloop()

Here is the output of the above code to demonstrate Python Tkinter Mainloop Exit

In this output, mainloop exits when the exit button is clicked.

python tkinter mainloop exit
Python Tkinter Mainloop exit

Python Tkinter Mainloop Blocking

The Mainloop() method plays a major role in Python Tkinter as it updates the Graphical User Interface(GUI) of the application every time an event occurs.

  • But the sad part in the above statement is mainloop waits for an event to occur. This means it is blocking the code that is outside the mainloop.
  • Python executes the code line by line so until and unless the mainloop is not terminated it does not allow python to execute code outside the mainloop.
  • In the next section, we have learned how to fix the mainloop blocking in Python Tkinter.

Here is the code to demonstrate the Python Tkinter Mainloop Blocking

In this code, we have created GUI (Tkinter) and terminal based application.

# GUI based application

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('300x200')
ws.config(bg='#4a7a8c')

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

ws.mainloop()

# terminal based application

name = input('Enter your name ')
print('Good Morning ',name)

Output:

  • In this output, you can notice that when app.py is executed then the Tkinter application appeared on the screen but the terminal-based application appeared only when the Tkinter application is closed.
  • It happened because mainloop was blocking the code.
Python Tkinter Mainloop Blocking
Python Tkinter Mainloop Blocking

Read: Python Tkinter Radiobutton – How to use

Python Tkinter Mainloop Non Blocking

In the previous section, we have seen Python Tkinter Mainloop Blocking. Now we will learn how to create a Python Tkinter Mainloop Non Blocking.

  • Threading is the library in Python Tkinter using which mainloop non-blocking code can be written.
  • Threading promotes multitasking features in the program. This means the block of code runs as an individual entity.
  • Use of threading is preferred in the big applications but for small applications after() and update() did the same thing.
  • In our example, we will be explaining using after(). for Threading and update() we have different sections in this blog.
  • So if we continue the previous example, now the GUI (Tkinter) and Terminal-based applications should appear at the same time.

Here is the code to demonstrate the Python Tkinter Mainloop Non Blocking

In this code, we have created function that holds the code for terminal based application and this function is called using after function on line 18.

from tkinter import *

ws = Tk()
ws.title('PythonGuides')
ws.geometry('300x200')
ws.config(bg='#4a7a8c')

def greet_user():
    name = input('Enter your name ')
    print('Good Morning ',name)   

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

ws.after(0, greet_user)
ws.mainloop()

In this output, both terminal-based and GUI-based applications are running simultaneously. In this way, the mainloop is non-blocking the other applications.

Python Tkinter Mainloop Non Blocking
Python Tkinter Mainloop Non Blocking

Python Tkinter Mainloop Update

Update() method in mainloop in Python Tkinter is used to show the updated screen. It reflects the changes when an event occurs. In the below example we have demonstrated update() function in Python Tkinter.

Source code of Python Tkinter Mainloop Update Example

In this code, date, day and time is being displayed. This information is fetched from the system and the Tkinter window keeps on updating to display latest information.

from tkinter import *
import time

ws = Tk()
ws.title('PythonGuides')
ws.geometry('400x300')
ws.config(bg='#5f734c')

time_lbl = Label(
    ws,
    text=time.strftime( "%d/%m/%Y %A %H:%M:%S"),
    font=(21),
    padx=10,
    pady=5,
    bg='#d9d8d7'
    )

time_lbl.pack(expand=True)
ws.update()

while True:
    time.sleep(1)
    time_text=time.strftime("%d/%m/%Y %A %H:%M:%S")
    time_lbl.config(text=time_text)
    ws.update()
    
ws.mainloop()

Output of Python Tkinter Mainloop Update Example

In this output, Time is keep on changing and the updates are visible because we have applied update function on main window.

python tkinter mainloop update
Python Tkinter Mainloop Update

Read: Python Tkinter Button

Python Tkinter Mainloop Event

In this section, we will learn about event in mainloop in Python Tkinter. Also, we see an example for the same.

  • An event refers to any activity performed it could be scheduled activity or manually performed by the user. Click of a button, filling the information in the Entry box, selecting radio buttons, etc triggers an event.
  • Mainloop waits for an event to occur so that it could update the screen. This wait for an event causes blocking but it can be resolved by using thread, update, or after functions in Python Tkinter
  • In our example, we will demonstrate the program that will generate a password and at the same time, it will display a message on the terminal.

Source code of Python Tkinter Mainloop Event Example

In this code, we have created 2 programs, one is gui-based and other is terminal-based. Out of these Terminal based triggers an event in every 2 seconds where as gui based application triggers when user clicks on the button. The thing to notice here is both are running parallel with out blocking the code.

from tkinter import *
import random

ws = Tk()
ws.title('PythonGuides')
ws.config(bg='#5f734c')
ws.geometry('400x300')

def generate_password():
    digits = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] 
    lc = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
                     'i', 'j', 'k', 'm', 'n', 'o', 'p', 'q',
                     'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
                     'z']
 
    uc = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                     'I', 'J', 'K', 'M', 'N', 'O', 'p', 'Q',
                     'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y',
                     'Z']
 
    spch = ['@', '#', '$', '%', '=', ':', '?', '.', '/', '|', '~', '>',
           '*', '(', ')', '<']

    pwd = random.choice(digits) + random.choice(lc) + random.choice(uc) + random.choice(spch)
    password = pwd+pwd
    lbl.config(text=password)

lbl = Label(
    ws,
    bg='#5f734c', 
    font=(18)
    )
lbl.pack(expand=True)

btn = Button(
    ws,
    text='Generate Password',
    padx=10, 
    pady=5,
    command=generate_password
)
btn.pack(expand=True)

def message():
    print('Keep yourself hyderated.')
    ws.after(2000, message) 

ws.after(2000, message)
ws.mainloop()

Output for Python Tkinter Mainloop Event example

In this output, two events are occurring but mainloop is not blocking the code. You can see both Gui based and terminal based applications are running parallel.

Python Tkinter Mainloop Event
Python Tkinter mainloop event

Python Tkinter Mainloop Timer

Mainloop plays an important role in Python Tkinter as it displays updated information on the screen.

Python Tkinter Mainloop Background

In this section, we will learn how to run an application in the background using the mainloop in Python Tkinter.

  • We will use the example in Python Tkinter Mainloop Update to explain the Python Tkinter Mainloop background.
  • In Python Tkinter Mainloop Update we have displayed the date, day, and time. Out of these only time is updating constantly whereas date and day are running in the background.

You may like the following Python tkinter tutorials:

In this tutorial, we will learn everything about Python Tkinter Mainloop. Also, we will cover these topics.

  • Python Tkinter Mainloop
  • Python Tkinter Mainloop Thread
  • Python Tkinter Mainloop exit
  • Python Tkinter Mainloop Non Blocking
  • Python Tkinter Mainloop Blocking
  • Python Tkinter Mainloop Update
  • Python Tkinter Mainloop Event
  • Python Tkinter Mainloop Timer
  • Python Tkinter Mainloop Background