🐍 Python UI Programming Series — Part 1: Getting Started with Tkinter
📘 Overview
Python is a versatile language with powerful libraries for creating Graphical User Interfaces (GUIs). One of the most beginner-friendly and widely used is Tkinter — it comes bundled with Python and provides all the basic tools to build windows, buttons, input fields, and more.
In this first article, we’ll cover:
-
What is a UI in Python?
-
Introduction to Tkinter
-
Creating your first GUI window
-
Adding widgets: Labels, Buttons, and Entry
-
Handling events with functions
🧠 What is a UI in Python?
A User Interface (UI) allows users to interact with software through graphical elements like windows, buttons, text fields, etc., instead of typing commands.
Python supports many UI libraries:
-
Tkinter – built-in and beginner-friendly
-
PyQt – feature-rich, better for complex UIs
-
Kivy – used for multitouch apps and mobile support
-
Dear PyGui, PySide, and others...
We’ll start with Tkinter, then explore others in future parts.
🧰 Why Tkinter?
✅ Built-in with Python
✅ Easy to learn
✅ Cross-platform
✅ Great for prototyping and small projects
🖼️ Your First GUI with Tkinter
✅ Step 1: Basic Window
import tkinter as tk
# Create a main window
root = tk.Tk()
root.title("My First GUI")
root.geometry("300x200") # Width x Height
# Start the GUI event loop
root.mainloop()
🎯 This creates a blank window titled "My First GUI".
🧱 Adding Widgets: Labels, Buttons, and Entry
Let’s add some common UI elements:
✅ Step 2: Label + Entry + Button
import tkinter as tk
def greet_user():
username = entry.get()
label_result.config(text=f"Hello, {username}!")
root = tk.Tk()
root.title("Greeting App")
root.geometry("300x150")
label_prompt = tk.Label(root, text="Enter your name:")
label_prompt.pack(pady=5)
entry = tk.Entry(root)
entry.pack(pady=5)
button_greet = tk.Button(root, text="Greet", command=greet_user)
button_greet.pack(pady=5)
label_result = tk.Label(root, text="")
label_result.pack(pady=5)
root.mainloop()
🧠 What’s happening here:
-
Label
shows text. -
Entry
allows input. -
Button
triggers a function (greet_user()
). -
config()
updates the label text dynamically.
💡 Recap
In this first part, you've learned:
-
What a Python GUI is
-
Why Tkinter is a good choice
-
How to create a window and basic widgets
-
How to handle user input and events
🚀 Coming Up in Part 2:
“Layouts, Frames, and UI Organization”
-
Learn how to organize widgets neatly using
pack()
,grid()
, andplace()
. -
Nest widgets using frames and build a cleaner layout.
No comments:
Post a Comment