Python GUI with Tkinter

Introduction

Tkinter is Python’s built-in GUI toolkit. You can build windows, buttons, forms, inputs, dialogs, and interactive apps without installing external packages.

1. Basic Tkinter Window

import tkinter as tk

root = tk.Tk()
root.title("My App")
root.geometry("400x300")

root.mainloop()
    

2. Adding a Label

label = tk.Label(root, text="Hello World!", font=("Arial", 16))
label.pack()
    

3. Buttons

def clicked():
    print("Button pressed")

btn = tk.Button(root, text="Click Me", command=clicked)
btn.pack()
    

4. Entry (Text Input)

entry = tk.Entry(root, width=30)
entry.pack()

def show():
    print(entry.get())

tk.Button(root, text="Show", command=show).pack()
    

5. Frames (Containers)

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

tk.Button(frame, text="A").pack(side="left")
tk.Button(frame, text="B").pack(side="left")
    

6. Grid Layout

tk.Label(root, text="Name").grid(row=0, column=0)
tk.Entry(root).grid(row=0, column=1)

tk.Label(root, text="Age").grid(row=1, column=0)
tk.Entry(root).grid(row=1, column=1)
    

7. Messagebox

from tkinter import messagebox

messagebox.showinfo("Hello", "This is a message")
    

8. File Dialog

from tkinter import filedialog

file = filedialog.askopenfilename()
print("Selected:", file)
    

9. Dropdown Menu (OptionMenu)

var = tk.StringVar(value="Option 1")

menu = tk.OptionMenu(root, var, "Option 1", "Option 2")
menu.pack()
    

10. Checkboxes

var = tk.BooleanVar()

cb = tk.Checkbutton(root, text="Enable Setting", variable=var)
cb.pack()
    

11. Radiobuttons

choice = tk.StringVar()

tk.Radiobutton(root, text="A", value="A", variable=choice).pack()
tk.Radiobutton(root, text="B", value="B", variable=choice).pack()
    

12. Canvas (Drawing)

canvas = tk.Canvas(root, width=300, height=200, bg="black")
canvas.pack()

canvas.create_line(10,10,200,150, fill="red")
canvas.create_rectangle(50,50,150,120, outline="white")
    

13. Listbox

lb = tk.Listbox(root)
lb.insert(1, "Item A")
lb.insert(2, "Item B")
lb.pack()
    

14. Scrollbars

scroll = tk.Scrollbar(root)
scroll.pack(side="right", fill="y")

lb = tk.Listbox(root, yscrollcommand=scroll.set)
scroll.config(command=lb.yview)
    

15. Full Example App

import tkinter as tk

root = tk.Tk()
root.title("Login")

tk.Label(root, text="Username:").pack()
u = tk.Entry(root)
u.pack()

tk.Label(root, text="Password:").pack()
p = tk.Entry(root, show="*")
p.pack()

def login():
    print("User:", u.get(), "Pass:", p.get())

tk.Button(root, text="Login", command=login).pack()

root.mainloop()
    

Summary