Now that we have the basic understanding of the concept of widgets and how to add them into a window, it's time to put this into practice and make ourselves an application!
As with almost all programming examples, we will start with a Hello World application. Don't feel cheated though, it will have interactive aspects too! Let's begin with the most important step for any GUI application—showing a window. Start by opening your choice of text editor or IDE and putting in the following code:
import tkinter as tk
class Window(tk.Tk):
def __init__(self):
super().__init__()
self.title("Hello Tkinter")
label = tk.Label(self, text="Hello World!")
label.pack(fill=tk.BOTH, expand=1, padx=100, pady=50)
if __name__ == "__main__":
window = Window()
window.mainloop()
Let's break this first step down. We begin by importing Tkinter and giving it the alias of tk for brevity. Every example in this book should include this line so that we have access to all of Tkinter's widgets, including the main window.
Speaking of widgets, we begin this example by subclassing Tkinter's main window widget—Tk. Doing so allows us to change various aspects of it, including the title which will display inside the window's top bar. We set the title to Hello Tkinter in this example.
Next, we want to display some text within our window. To do this, we use a Label widget. A Label widget is typically non-interactive and is used to display either text or an image.
When defining Tkinter widgets, the first argument is always the parent (sometimes called master) which will hold the widget. We use self to refer to our main window in this case. Afterward, we have a vast array of keyword arguments to use in order to change their properties. The text argument here will take a string which tells the label what to display. Our label will say Hello World!
Now that we have two widgets, we need to place the label inside of our main window (Tk) so that they both display. To do this with Tkinter, we utilize one of the geometry managers we covered earlier. For our first example, we will be using pack. Pack has been given the following arguments:
-
fill: This tells the widget to take all the space in both directions
-
expand: This tells the widget to expand when the window is resized
-
padx: Padding (empty space) of 100 pixels in the x direction (left, right)
-
pady: Padding of 50 pixels in the y direction (above, below)
With that, our Hello World is ready to run. In order to tell the main window to show itself, we call the mainloop method. This is all enclosed within the (hopefully familiar) if __name__ == "__main__" block. Utilizing this block allows widgets from one file to be imported into another file for reuse without creating multiple main windows.
Execute the code via your preferred method and you should see a little window appear. Congratulations! You have now written your first GUI application with Tkinter!: