Tkinter

A Graphical User Interface (GUI) is a user-friendly interface that allows users to interact with a computer program through visual elements like windows, buttons, and menus. Tkinter is a Python library that allows you to create GUIs. It's a standard part of Python, so you don't need to install it separately.

Tkinter Basics


Tkinter programs typically start by importing the tkinter module and creating a main window. Widgets like buttons, labels, and text boxes are added and positioned on this window. Event handlers are defined to respond to user interactions, and the mainloop() function is called to start the event loop, ensuring the program remains interactive.

Import Tkinter

import tkinter as tk

Create Window

window = tk.Tk()

Create Widgets

button = tk.Button(window, text="Click Me")

Add Widgets

button.pack()

Create Event Handlers

button.bind("<Button-1>", button_click)

Start Event Loop

window.mainloop()
## TKINTER BASIC EXAMPLE ##
# Import Tkinter
import tkinter as tk

# Event Handler Function
def button_click(event):
    print("Button clicked!")

# Create Window
window = tk.Tk()

# Create Widget
button = tk.Button(window, text="Click Me")

# Add Widget to Window
button.pack()

# Create Event Handler
button.bind("<Button-1>", button_click)

# Start Event Loop
window.mainloop()

All Tkinter programs, even complex ones with thousands of lines of code, adhere to the fundamental principles of creating a main window, adding widgets, defining event handlers, and starting the main event loop.

Widgets


Widgets are the building blocks of a Tkinter application. They are visual elements that users can interact with. Each widget has its own properties and methods to customize its appearance and behavior. By combining different widgets and arranging them on the window, you can create user-friendly and interactive interfaces.

Core Tkinter Widgets:

  • Labels: Display text.
    label = tk.Label(window, text="This is a label")
  • Buttons: Trigger actions when clicked.
    button = tk.Button(window, text="Click Me", command=button_click)

    Note: The command parameter is another way to add an event handler to the button.

  • Text Boxes: Allow user input.
    text_box = tk.Entry(window)
  • Text Areas: Allow multi-line text input.
    text_area = tk.Text(window)
## TKINTER WIDGETS EXAMPLE ##
import tkinter as tk

window = tk.Tk()
window.title("Tkinter Example")

label = tk.Label(window, text="Enter text:")
label.pack()

entry_box = tk.Entry(window)
entry_box.pack()

button = tk.Button(window, text="Submit")
button.pack()

text_area = tk.Text(window)
text_area.pack()

window.mainloop()

Layout Management


Tkinter provides three main layout managers to organize widgets on a window: pack, grid, and place. The pack manager places widgets sequentially, filling available space. The grid manager arranges widgets in a grid-like structure, specifying rows and columns. The place manager allows precise positioning of widgets using absolute coordinates. Choosing the right layout manager depends on the desired layout complexity and flexibility.

Pack Geometry Manager

  • Simple to use but less flexible.
  • Packs widgets into available space, one after the other.
  • Suitable for basic layouts.
## PACK LAYOUT EXAMPLE ##
import tkinter as tk

window = tk.Tk()
window.title("Pack Layout")

label = tk.Label(window, text="Hello, World!")
button = tk.Button(window, text="Click Me")
entry = tk.Entry(window)

label.pack()
button.pack()
entry.pack()

window.mainloop()

Grid Geometry Manager

  • More powerful and flexible.
  • Organizes widgets in a grid-like structure, specifying rows and columns.
  • Ideal for complex layouts.
## GRID LAYOUT EXAMPLE ##
import tkinter as tk

window = tk.Tk()
window.title("Grid Layout")

label = tk.Label(window, text="Hello, World!")
button = tk.Button(window, text="Click Me")
entry = tk.Entry(window)

label.grid(row=0, column=0)
button.grid(row=1, column=0)
entry.grid(row=2, column=0)

window.mainloop()

Place Geometry Manager

  • Allows precise positioning of widgets using absolute coordinates (x, y).
  • Suitable for specific layouts but can be less intuitive.
## PLACE LAYOUT EXAMPLE ##
import tkinter as tk

window = tk.Tk()
window.title("Place Layout")

label = tk.Label(window, text="Hello, World!")
button = tk.Button(window, text="Click Me")
entry = tk.Entry(window)

label.place(x=20, y=20)
button.place(x=20, y=50)
entry.place(x=20, y=80)

window.mainloop()

Event Handling


Event handling is a mechanism that allows a program to respond to user interactions with the interface. In Tkinter, events can be mouse clicks, key presses, window resizing, and more.

How it works:

  • Define an Event Handler Function: This function will contain the code that should be executed when the event occurs.
  • Bind the Event Handler to a Widget: You associate the event handler function with a specific widget. This is often done using the bind() method.

In the previous Tkinter Widget Example nothing happened when we clicked the button because their wasn't an event handler attached to the button. This program is updated to provide functionality for button clicks.

## EVENT HANDLER EXAMPLE ##
import tkinter as tk

def button_click():
    text = entry_box.get()
    label.config(text=f"You entered: {text}")
    text_area.insert(tk.END, f"{text}\n")

window = tk.Tk()
window.title("Tkinter Example")

label = tk.Label(window, text="Enter text:")
label.pack()

entry_box = tk.Entry(window)
entry_box.pack()

button = tk.Button(window, text="Submit", command=button_click)
button.pack()

text_area = tk.Text(window)
text_area.pack()

window.mainloop()

Advanced Features


While Tkinter is a powerful tool for building basic GUIs, it also offers several advanced features that can be used to create more sophisticated applications.

  • Frame: Group widgets together within an object.
  • Menus: Create menus and toolbars to provide additional functionality and a more professional look to your application.
  • Dialog Boxes: Tkinter offers various dialog boxes, such as message boxes, file dialogs, and color choosers, to interact with the user and gather input.
  • Canvas: Provides a drawing surface where you can draw lines, shapes, and text. It's useful for creating custom graphics and visualizations.
  • Custom Widgets: Create custom widgets by subclassing the tk.Frame class and adding your desired components to it. This allows you to create reusable and complex widgets.
  • Theming and Styling: While Tkinter's default appearance might be somewhat basic, you can customize the look and feel of your application using themes and styles.
## ADVANCED TKINTER EXAMPLE ##
import tkinter as tk
from tkinter import ttk, messagebox, filedialog, colorchooser, Canvas, Frame

def open_file():
	file_path = filedialog.askopenfilename()
	# Do something with the file path

def save_file():
	file_path = filedialog.asksaveasfilename()
	# Do something with the file path

def show_message():
	messagebox.showinfo("Message", "This is a message box")

def choose_color():
	color = colorchooser.askcolor()
	canvas.config(bg=color[1])

def draw_line():
	x1, y1, x2, y2 = 10, 10, 100, 100
	canvas.create_line(x1, y1, x2, y2, fill="blue", width=2)

# Create the main window
root = tk.Tk()
root.title("Advanced Tkinter Application")

# Create a menu bar
menubar = tk.Menu(root)
filemenu = tk.Menu(menubar, tearoff=0)
filemenu.add_command(label="Open", command=open_file)
filemenu.add_command(label="Save", command=save_file)
filemenu.add_separator()

filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)

helpmenu = tk.Menu(menubar, tearoff=0)
helpmenu.add_command(label="About", command=show_message)
menubar.add_cascade(label="Help", menu=helpmenu)

root.config(menu=menubar)

# Create a frame for the canvas
canvas_frame = Frame(root, bg="lightgray")
canvas_frame.pack(fill=tk.BOTH, expand=True)

# Create a canvas
canvas = Canvas(canvas_frame, width=400, height=300, bg="white")
canvas.pack(fill=tk.BOTH, expand=True)

# Create a button to change the canvas color
color_button = tk.Button(root, text="Change Color", command=choose_color)
color_button.pack()

# Create a button to draw a line
draw_button = tk.Button(root, text="Draw Line", command=draw_line)
draw_button.pack()

root.mainloop()

Tkinter is a powerful library that has grown over the years. In fact, newer versions of most widgets can be found in the updated ttk module within tkinter. To learn more about tkinter, tk and ttk I suggest reading the docs.