Hello World program in Python Tkinter
Last Update : 31 Aug, 2022In this tutorial, You will learn to develop the first Tkinter "Hello World" program.
This program displays "Hello Word" text on the Tkinter GUI window.
Creating Tkinter Window
Firstly, you need to import all the classes, functions, and variables from the Tkinter package.
So, use the following code line to import the Tkinter module as tk to the program.
import tkinter as tk
Secondly, you can create the instance of tk.Tk() class as follows. This class will create the Tkinter graphical window with the title bar, minimize, maximize, and close buttons.
root = tk.Tk()
As a convention, use root for the name of the main window. But, you can also use other words like main, etc.
Thirdly, you can call the mainloop() method that includes in the main window object.
root.mainloop()
The Tkinter window does not show before you enter the mainloop(). Also, this method keeps the main window visible on the screen.
The mainloop() method keeps displaying and running program until you close it.
The following shows the complete program that displays the Tkinter window on the screen.
import tkinter as tk
root = tk.Tk()
root.mainloop()
This program produces the following result -:
Displaying a Label on Window
If you successfully created the Tkinter window, Now you can try to place components on it. In Tkinter, components are called widgets.
In this program, you can make a "Hello World" text on the Tkinter root window using the Label component.
let's see how it works.
The syntax of creating a component that belongs to a container is as follows.
widget = WidgetName(container, **options)
In the above syntax,
- For container -: Use the Tkinter parent window or frame where you want to place the widget.
- For **options -: Use one or more keyword arguments that are used for the Tkinter widget configurations.
You can use a Label widget as a child on root window as follows.
helloLabel = tk.Label(root, text="Hello World")
Here root is the parent of our Label widget. Also, you can position the Label on the main window by using following statement.
helloLabel.pack()
If you do not call the pack() method, you can't visible the text widget. However, the Tkinter already created the text widget.
Note : You can learn more about the pack() method in a later tutorial.
The following shows the complete program that displays the "Hello World" text.
import tkinter as tk
root = tk.Tk()
# add a label on the root
helloLabel = tk.Label(root, text="Hello World")
helloLabel.pack()
# display the window
root.mainloop()
This program produces the following result -: