in this lesson we want to learn How to Build a GUI Application with Python – Python for Beginners, Creating a GUI (graphical user interface) application in Python can be a great way to get started with building desktop applications. Here is a step-by-step guide on how to create a basic GUI application using the Tkinter library, which is included in the Python standard library:
- Start by importing the Tkinter module:
1 |
import tkinter as tk |
- Next, create a new Tkinter application by instantiating the Tk() class:
1 |
root = tk.Tk() |
- Set the title of the application window by calling the title() method on the root object:
1 |
root.title("My First GUI App") |
- Create a label widget by instantiating the Label() class and passing in the parent widget (the root window) and the text to display:
1 |
label = tk.Label(root, text="Hello, World!") |
- Use the pack() method to add the label widget to the root window:
1 |
label.pack() |
- Create a button widget by instantiating the Button() class and passing in the parent widget (the root window), the text to display, and a function to call when the button is clicked:
1 2 3 4 |
def on_button_click(): label.configure(text="Button was clicked!") button = tk.Button(root, text="Click me!", command=on_button_click) |
- Use the pack() method to add the button widget to the root window:
1 |
button.pack() |
- Start the main event loop of the application by calling the mainloop() method on the root object:
1 |
root.mainloop() |
Your complete code should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import tkinter as tk root = tk.Tk() root.title("My First GUI App") label = tk.Label(root, text="Hello, World!") label.pack() def on_button_click(): label.configure(text="Button was clicked!") button = tk.Button(root, text="Click me!", command=on_button_click) button.pack() root.mainloop() |
Learn More on Python GUI Development
- How to Use Qt Designer in PyQt and PyQt6
- Build Text to Speech App with Python & PyQt5
- How to Build GUI Window in PyQt6
- How to Show Image in PyQt6
- How to Create Calendar with Python & PyQt6
- How to Create CheckBox with Qt Designer & PyQt6
Run the complete code and this will be the result
