Creating Your First GUI

In this lesson, we will learn how to build a basic GUI app with Tkinter.

Creating a Tkinter window

Python has a library called tkinter for building desktop apps. First, we need to import the Tkinter library using the import keyword. It’s better to give a short name to the library while importing. In the following example, we can import tkinter as tk.

import tkinter as tk

Now, we create a Tkinter window object by calling the Tk() method.

import tkinter as tk
window = tk.Tk()

Let’s give a title and define the geometry of the Tkinter window. We can do that by calling the title() and geometry() methods. We will mention the title inside the title() method and specify the height and width of the window inside the geometry() method.

import tkinter as tk
window = tk.Tk()
window.title("My first GUI App")
window.geometry("1000x600")

Now we have a simple Tkinter window. To run it, we need to call the mainloop() method on our window object.

This method should be called before running any Tkinter application.

import tkinter as tk

window = tk.Tk()
window.title("My first GUI")
window.geometry("1000x600")

window.mainloop()
Creating the first GUI using Tkinter

Click the “Run” button to run the above code and see the output. This code creates a basic GUI window with 1000px height and 600px width.

Don’t forget to close the window by clicking the “x” icon before we move on.

Printing text on the window

Let’s print some text on this window using labels. A label is a class in Tkinter for displaying text or images on the GUI.

The syntax of labels is as follows:

label_name = tk.Label(text ="some text")
label_name.grid(column=0,row=0)

The Label() method takes a keyword argument. We can specify what text to display as the value of the argument.

The grid() method positions a label using row and column values. The arguments column=0 and row=0 mean that the label will be placed in the 0th row and 0th column, is the top-left of the window.

Let’s run the app

Let’s print something on our window using a label. Click the “Run” button to run the code and see the output.

import tkinter as tk

window=tk.Tk()
window.title(" My Window ")
window.geometry("1000x600")

mylabel = tk.Label(text = "Hello World!")
mylabel.grid(column=0,row=0)

window.mainloop()
Hello World App in Tkinter

When you run the code, you will see a GUI window that prints “Hello World.” You can close the GUI window by clicking the “x” icon.

We have created our first Tkinter App. Yes, it is a very basic app, but this is a good starting point. We will explore more things and create amazing apps in the upcoming lessons.