How to make a graphic interface in Python

Learn how to create a graphical user interface (GUI) in Python with an example - from basics to advanced techniques.

Graphic Interface in Python using Tkinter

Tkinter is a Python library used for creating a graphical user interface. It is one of the most commonly used graphical libraries for Python, and it provides a powerful set of widgets for creating a user interface. Tkinter is a part of the Python Standard Library, so it is included in all versions of Python.

In order to create a graphical user interface, we need to import the Tkinter library. This can be done using the following code:

import tkinter
root = tkinter.Tk()

The root variable is the root window of the application. This is the window that will contain all of the other widgets.

Next, we must create a frame, which will contain all of the other widgets. This can be done using the following code:

frame = tkinter.Frame(root)
frame.pack()

The frame has now been created, and it can be used to contain other widgets.

We can now create a label widget, which is used to display text. This can be done using the following code:

label = tkinter.Label(frame, text="Hello World!")
label.pack()

The label widget has now been created, and it will display the text “Hello World!”.

We can now create a button widget, which is used to trigger an action when clicked. This can be done using the following code:

def on_button_click():
    print("Button was clicked!")

button = tkinter.Button(frame, text="Click me!", command=on_button_click)
button.pack()

The button widget has now been created, and it will trigger the on_button_click() function when clicked.

Finally, we must start the application loop, which will run the application until it is closed. This can be done using the following code:

root.mainloop()

The application loop has now been started, and the graphical user interface will now be visible.

This is a basic example of creating a graphical user interface in Python using the Tkinter library. There are many more widgets that can be used to create a more complex user interface, such as text boxes, drop-down menus, and radio buttons.

Answers (0)