Tkinter Hello, World!

Tkinter Hello, World!

Summary

In this tutorial, you’ll learn step-by-step how to develop the Tkinter “Hello, World!” program.

Creating a Window

The following program shows how to display a window on the screen:

import tkinter as tk

app = tk.Tk()
app.mainloop()
Code copied!

How It Works

First, import the tkinter module as tk:

import tkinter as tk
Code copied!

Second, create an instance of the tk.Tk class that will create the application window:

app = tk.Tk()
Code copied!

Third, call the mainloop() method of the main window object:

app.mainloop()
Code copied!

The mainloop() method ensures the main window remains visible on the screen. If you don’t call this method, the main window will display and disappear almost instantly.

Troubleshooting

Sometimes, you may encounter the following error:

ImportError: No module named tkinter
Code copied!

In this case, you need to install the tkinter module using the following command:

sudo apt-get install python3-tk
Code copied!

Displaying a Label

Now, let’s place a component on the window. In Tkinter, these components are referred to as widgets.

The following code adds a label widget to the root window:

import tkinter as tk

app = tk.Tk()
label = tk.Label(app, text="Hello, World!")
label.pack()
app.mainloop()
Code copied!

How It Works

To create a widget that belongs to a container, you use the following syntax:

widget = WidgetName(master, **options)
Code copied!

In this syntax:

  • master: The parent window or frame where you want to place the widget.
  • options: One or more keyword arguments that specify the configurations of the widget.

The following creates a Label widget placed on the root window:

label = tk.Label(app, text="Hello, World!")
Code copied!

The following statement positions the Label on the main window:

label.pack()
Code copied!

Fixing Blurry UI on Windows

If you find the text and UI are blurry on Windows, you can use the ctypes Python library to fix it.

First, import the ctypes module:

from ctypes import windll
Code copied!

Second, call the SetProcessDpiAwareness() function:

windll.shcore.SetProcessDpiAwareness(1)
Code copied!

If you want the application to run across platforms such as Windows, macOS, and Linux, you can place the above code in a try...finally block:

try:
    from ctypes import windll
    windll.shcore.SetProcessDpiAwareness(1)
finally:
    app.mainloop()
Code copied!

Summary

  • Import the tkinter module to create a Tkinter desktop application.
  • Use the Tk class to create the main window and call the mainloop() method to maintain the display of the main window.
  • In Tkinter, components are called widgets.