Tkinter Tutorial - Hello World

Jinku Hu Feb 15, 2024
Tkinter Tutorial - Hello World

We will start our Tkinter journey with popular Hello World program.

from sys import version_info

if version_info.major == 2:
    import Tkinter as tk
else:
    import tkinter as tk

app = tk.Tk()
app.title("Hello World")
app.mainloop()

The window will be like this:

Tkinter Hello World

Attention
The name of Tkinter module has changed from Tkinter in Python 2 to tkinter in Python 3. Therefore if you want to write Python 2 and 3 compatible Tkinter codes, you need to check the Python major version number before importing Tkinter.

For Python 2

import Tkinter as tk

For Python 3

import tkinter as tk

In the next line

app = tk.Tk()

The app window that is a main window could have other widgets like labels, buttons, and canvas in itself. It is the parent window of all its widgets.

app.title("Hello World")

It names the main window as Hello World.

app.mainloop()

After window instance is created, mainloop() should be called to let window enter the endless loop, otherwise nothing will show up.

Author: Jinku Hu
Jinku Hu avatar Jinku Hu avatar

Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.

LinkedIn Facebook