Showing posts with label python gui. Show all posts
Showing posts with label python gui. Show all posts

Python GUI Tutorial for Beginners – Create Simple UIs with Tkinter

← Back to Home

 

🐍 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(), and place().

  • Nest widgets using frames and build a cleaner layout.


Build a Simple Python Calculator Using Lambda and Tkinter (Step-by-Step Guide)

← Back to Home

🧮 Build a Calculator in Python Using Lambda & Tkinter

Creating a calculator is a great way to learn about Python functions, GUI programming, and event handling. In this tutorial, we’ll build a simple calculator using lambda functions for operations and Tkinter for the user interface.


📦 What You’ll Learn

  • How to use lambda functions for basic operations

  • How to build a Tkinter GUI

  • How to wire up buttons with actions dynamically


🛠️ Prerequisites

  • Python 3.x installed

  • Basic knowledge of Python functions and Tkinter

You can install Tkinter (if not already installed) using:

pip install tk

Note: Tkinter comes pre-installed with most Python distributions.


🔣 Step-by-Step: Create a Lambda-Based Calculator

✅ Step 1: Import Tkinter

import tkinter as tk
from functools import partial

✅ Step 2: Define Operations Using Lambda

operations = {
    '+': lambda x, y: float(x) + float(y),
    '-': lambda x, y: float(x) - float(y),
    '*': lambda x, y: float(x) * float(y),
    '/': lambda x, y: float(x) / float(y) if float(y) != 0 else "Error"
}

✅ Step 3: Create the GUI Window

root = tk.Tk()
root.title("Lambda Calculator")
root.geometry("300x300")

✅ Step 4: Create Input Fields and Result Display

entry1 = tk.Entry(root, width=10)
entry1.grid(row=0, column=0, padx=10, pady=10)

entry2 = tk.Entry(root, width=10)
entry2.grid(row=0, column=1, padx=10, pady=10)

result_label = tk.Label(root, text="Result: ")
result_label.grid(row=1, column=0, columnspan=2)

✅ Step 5: Define a Generic Operation Handler

def calculate(op):
    try:
        val1 = entry1.get()
        val2 = entry2.get()
        result = operations[op](val1, val2)
        result_label.config(text=f"Result: {result}")
    except Exception as e:
        result_label.config(text="Error")

✅ Step 6: Create Buttons for Operations

row = 2
col = 0

for symbol in operations:
    action = partial(calculate, symbol)
    tk.Button(root, text=symbol, width=5, command=action).grid(row=row, column=col, padx=5, pady=5)
    col += 1

✅ Step 7: Run the Application

root.mainloop()

🖥️ Full Working Code

Here’s the full code for your reference:

import tkinter as tk
from functools import partial

# Define lambda operations
operations = {
    '+': lambda x, y: float(x) + float(y),
    '-': lambda x, y: float(x) - float(y),
    '*': lambda x, y: float(x) * float(y),
    '/': lambda x, y: float(x) / float(y) if float(y) != 0 else "Error"
}

# Create the window
root = tk.Tk()
root.title("Lambda Calculator")
root.geometry("300x300")

# Entry widgets
entry1 = tk.Entry(root, width=10)
entry1.grid(row=0, column=0, padx=10, pady=10)

entry2 = tk.Entry(root, width=10)
entry2.grid(row=0, column=1, padx=10, pady=10)

# Result label
result_label = tk.Label(root, text="Result: ")
result_label.grid(row=1, column=0, columnspan=2)

# Calculation function
def calculate(op):
    try:
        val1 = entry1.get()
        val2 = entry2.get()
        result = operations[op](val1, val2)
        result_label.config(text=f"Result: {result}")
    except Exception:
        result_label.config(text="Error")

# Buttons for operations
row = 2
col = 0
for symbol in operations:
    action = partial(calculate, symbol)
    tk.Button(root, text=symbol, width=5, command=action).grid(row=row, column=col, padx=5, pady=5)
    col += 1

# Run the app
root.mainloop()

📚 Summary

  • Lambda functions let us define concise, anonymous operations.

  • Tkinter helps us build user interfaces with minimal code.

  • This calculator is fully functional and can be expanded to support more features like clearing fields or advanced operations.


Would you like to watch video explanation to create a calculator using python Lambda ? watch video below: 



← Back to Home

Featured Post

Solution MongoDB document Modelling Assignment

 Here's the complete solution to your MongoDB document modeling assignment, including: ✅ Sample documents for students and courses ...

Popular Posts