Creating a simple GUI (Graphical User Interface) in Python is a great way to learn about programming with event-driven applications. Python has several libraries for creating GUIs, the most common of which are Tkinter, PyQt, and Kivy. Below, I'll provide an example using Tkinter, because it's included with Python and is a great way to start building GUI applications.
This simple example will create a window with a button that displays a message when clicked.
Step 1: Import the Tkinter Module
First, you'll need to import the Tkinter library.
python
import tkinter as tk
from tkinter import messagebox
Step 2: Create the Main Application Window
Next, set up the main application window.
python
# Create the main window
window = tk.Tk()
window.title("Simple GUI")
window.geometry("300x200")
Step 3: Add a Button Widget
Here, we'll add a button to our window. When clicked, the button will trigger a function.
python
def on_button_click():
messagebox.showinfo("Button Clicked", "Hello, Tkinter!")
# Create a button and attach it to the window
button = tk.Button(window, text="Click Me", command=on_button_click)
button.pack(pady=20)
Step 4: Run the Application
Finally, add the main loop to run the application.
python
# Start the main event loop
window.mainloop()
Full Example Code:
Here’s the complete code for this simple Tkinter application:
python
import tkinter as tk
from tkinter import messagebox
def on_button_click():
messagebox.showinfo("Button Clicked", "Hello, Tkinter!")
# Create the main window
window = tk.Tk()
window.title("Simple GUI")
window.geometry("300x200")
# Create a button and attach it to the window
button = tk.Button(window, text="Click Me", command=on_button_click)
button.pack(pady=20)
# Start the main event loop
window.mainloop()
Running the Code
Save the code to a file with a .py extension, for example, simple_gui.py.
Run the file with Python by executing python simple_gui.py in your terminal or command prompt.
When you run this program, a window should appear with a button labeled "Click Me". When you click the button, a message box will appear that says "Hello, Tkinter!". You can build on this simple example by adding more widgets and functionality, such as input fields, labels, or additional buttons. As you get more comfortable, feel free to explore other layout managers and widget types available in Tkinter.