Tkinter is Python's standard GUI library, included in the standard library without requiring separate installation. This guide covers creating windows, adding widgets, and handling user interactions.
Creating a Window
Import the tkinter module and instantiate the Tk class to create a main application window. Set the window title using the title method.
from tkinter import *
root = Tk()
root.title("Main Application")
root.mainloop()
The mainloop method enters the Tkinter event loop, which handles all window events and user interactions. Without calling this method, the window will not display.
Adding Labels
The Label widget displays static text. Create a label and position it using the grid layout manager.
from tkinter import *
root = Tk()
root.title("Main Application")
message = Label(root, text="Welcome")
message.grid(column=0, row=0)
root.mainloop()
The grid method must be called for the widget to appear. Omitting this call results in an invisible label.
Customizing Label Font
Use the font parameter to modify the label's typography. This parameter works with other widgets as well.
message = Label(root, text="Welcome", font=("Helvetica", 48))
Setting Window Dimensions
The geometry method adjusts the window size in pixels.
root.geometry("500x300")
This creates a window 500 pixels wide and 300 pixels tall.
Adding Buttons
Buttons are created using the Button class and positioned with grid.
from tkinter import *
root = Tk()
root.title("Main Application")
root.geometry("500x300")
message = Label(root, text="Welcome")
message.grid(column=0, row=0)
button = Button(root, text="Submit")
button.grid(column=1, row=0)
root.mainloop()
Customizing Button Colors
The fg parameter controls foreground color (text), while bg sets the background color.
## Handling Button Events
Define a callback function and assign it to the command parameter to handle click events.
```python
from tkinter import *
root = Tk()
root.title("Main Application")
root.geometry("500x300")
message = Label(root, text="Welcome")
message.grid(column=0, row=0)
def on_submit():
message.config(text="Button clicked!")
button = Button(root, text="Submit", command=on_submit)
button.grid(column=1, row=0)
root.mainloop()
Adding Text Entry Fields
The Entry widget provides a single-line text input field.
from tkinter import *
root = Tk()
root.title("Main Application")
root.geometry("500x300")
message = Label(root, text="Welcome")
message.grid(column=0, row=0)
input_field = Entry(root, width=15)
input_field.grid(column=1, row=0)
def on_submit():
user_input = input_field.get()
message.config(text=f"Input: {user_input}")
button = Button(root, text="Submit", command=on_submit)
button.grid(column=2, row=0)
root.mainloop()
Setting Input Focus
The focus method automatically places the cursor in the entry field when the application starts.
input_field.focus()
Adding Combo Boxes
The Combobox widget from tkinter.ttk provides a dropdown selection list.
from tkinter import *
from tkinter.ttk import Combobox
root = Tk()
root.title("Main Application")
root.geometry("500x300")
dropdown = Combobox(root)
dropdown['values'] = ('Option A', 'Option B', 'Option C', 'Option D')
dropdown.current(0)
dropdown.grid(column=0, row=0)
def on_select():
selected = dropdown.get()
print(f"Selected: {selected}")
button = Button(root, text="Get Value", command=on_select)
button.grid(column=1, row=0)
root.mainloop()
The current method sets the initially selected index. Use get to retrieve the selected value.
Adding Checkboxes
The Checkbutton widget creates a checkbox. Use BooleanVar or IntVar to track the checkbox state.
from tkinter import *
from tkinter.ttk import Checkbutton
root = Tk()
root.title("Main Application")
root.geometry("500x300")
is_checked = BooleanVar()
is_checked.set(True)
checkbox = Checkbutton(root, text="Enable Feature", variable=is_checked)
checkbox.grid(column=0, row=0)
def show_state():
status = is_checked.get()
print(f"Checked: {status}")
button = Button(root, text="Check State", command=show_state)
button.grid(column=1, row=0)
root.mainloop()
Using IntVar allows setting numeric values (0 for unchecked, 1 for checked).
Adding Radio Buttons
Radio buttons allow exclusive selection from multiple options. Each button requires a unique value.
from tkinter import *
from tkinter.ttk import Radiobutton
root = Tk()
root.title("Main Application")
root.geometry("500x300")
selection = IntVar()
label = Label(root, text="Select an option:")
label.grid(column=0, row=0)
option1 = Radiobutton(root, text="Alpha", value=1, variable=selection)
option2 = Radiobutton(root, text="Beta", value=2, variable=selection)
option3 = Radiobutton(root, text="Gamma", value=3, variable=selection)
option1.grid(column=0, row=1)
option2.grid(column=1, row=1)
option3.grid(column=2, row=1)
def display_selection():
label.config(text=f"Selected: {selection.get()}")
button = Button(root, text="Submit", command=display_selection)
button.grid(column=3, row=1)
root.mainloop()
All radio buttons share the same variable to ensure only one can be selected at a time.
Adding Scrolled Text Areas
The ScrolledText widget provides a multi-line text area with scrollbars.
from tkinter import *
from tkinter import scrolledtext
root = Tk()
root.title("Main Application")
root.geometry("500x300")
text_area = scrolledtext.ScrolledText(root, width=40, height=10)
text_area.grid(column=0, row=0)
# Insert text
text_area.insert(1.0, "Initial text content\n")
# Delete text
def clear_text():
text_area.delete(1.0, END)
button = Button(root, text="Clear", command=clear_text)
button.grid(column=0, row=1)
root.mainloop()
Creating Message Boxes
The messagebox module provides various dialog boxes.
from tkinter import *
from tkinter import messagebox
root = Tk()
root.title("Main Application")
root.geometry("500x300")
def show_message():
messagebox.showinfo("Notification", "Operation completed successfully")
button = Button(root, text="Show Message", command=show_message)
button.grid(column=0, row=0)
root.mainloop()
Other messagebox functions include showwarning, showerror, and askquestion.
Adding Spin Boxes
The Spinbox widget provides numeric input with increment and decrement buttons.
from tkinter import *
root = Tk()
root.title("Main Application")
root.geometry("500x300")
# Numeric range
numeric_spin = Spinbox(root, from_=0, to=100, width=8)
numeric_spin.grid(column=0, row=0)
# Specific values
choice_spin = Spinbox(root, values=("Small", "Medium", "Large"), width=8)
choice_spin.grid(column=1, row=0)
# Default value
default_value = IntVar()
default_value.set(50)
default_spin = Spinbox(root, from_=0, to=100, width=8, textvariable=default_value)
default_spin.grid(column=2, row=0)
root.mainloop()
Adding Progress Bars
The Progressbar widget displays task progress.
from tkinter import *
from tkinter.ttk import Progressbar
root = Tk()
root.title("Main Application")
root.geometry("500x300")
progress = Progressbar(root, length=200, mode='determinate')
progress.grid(column=0, row=0)
def update_progress():
progress['value'] = 60
button = Button(root, text="Start", command=update_progress)
button.grid(column=0, row=1)
root.mainloop()
To customize the progress bar color, apply a style:
from tkinter import *
from tkinter.ttk import Progressbar, Style
root = Tk()
root.title("Main Application")
root.geometry("500x300")
style = Style()
style.theme_use('default')
style.configure("custom.Horizontal.TProgressbar", background='green')
progress = Progressbar(root, length=200, style="custom.Horizontal.TProgressbar")
progress['value'] = 45
progress.grid(column=0, row=0)
root.mainloop()
Adding File Dialogs
The filedialog module provides file and directory selection dialogs.
from tkinter import *
from tkinter import filedialog
import os
root = Tk()
root.title("Main Application")
root.geometry("500x300")
def open_file():
file_path = filedialog.askopenfilename(
initialdir=os.path.dirname(__file__),
title="Select File",
filetypes=("Text files", "*.txt"), ("All files", "*.*"))
print(f"Selected: {file_path}")
def open_multiple():
files = filedialog.askopenfilenames(
title="Select Files",
filetypes=("Images", "*.png *.jpg"), ("All files", "*.*"))
print(f"Selected: {files}")
def select_directory():
directory = filedialog.askdirectory(title="Select Directory")
print(f"Selected: {directory}")
Button(root, text="Open File", command=open_file).grid(column=0, row=0)
Button(root, text="Open Multiple", command=open_multiple).grid(column=0, row=1)
Button(root, text="Select Folder", command=select_directory).grid(column=0, row=2)
root.mainloop()
The initialdir parameter specifies the starting directory. The filetypes parameter filters available file extensions.