Tkinter Cheat Sheet

Here’s a cheat sheet for using Tkinter, the standard GUI (Graphical User Interface) toolkit for Python:

Creating a Basic Tkinter Window

import tkinter as tk

# Create main window
root = tk.Tk()
root.title("My Tkinter App")

# Run the Tkinter event loop
root.mainloop()

Adding Widgets

Labels:

label = tk.Label(root, text="Hello, Tkinter!")
label.pack()

Buttons:

button = tk.Button(root, text="Click me!", command=lambda: print("Button clicked"))
button.pack()

Entry (Input Field):

entry = tk.Entry(root)
entry.pack()

Text Widget:

text_widget = tk.Text(root, height=5, width=30)
text_widget.pack()

Checkbutton:

check_var = tk.IntVar()
checkbutton = tk.Checkbutton(root, text="Check me", variable=check_var)
checkbutton.pack()

Layout Management

Pack:

widget.pack(side=tk.LEFT)  # Can be TOP, BOTTOM, LEFT, RIGHT

Grid:

widget.grid(row=0, column=0)

Place:

widget.place(x=50, y=50)

Handling Events

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

button = tk.Button(root, text="Click me", command=button_click)
button.pack()

Dialogs

Messagebox:

from tkinter import messagebox

messagebox.showinfo("Info", "This is an information message")

File Dialog:

from tkinter import filedialog

file_path = filedialog.askopenfilename()

Menu Bar

menu_bar = tk.Menu(root)

# Create a file menu
file_menu = tk.Menu(menu_bar, tearoff=0)
file_menu.add_command(label="Open", command=lambda: print("File opened"))
file_menu.add_separator()
file_menu.add_command(label="Exit", command=root.destroy)

# Add file menu to the menu bar
menu_bar.add_cascade(label="File", menu=file_menu)

# Display the menu bar
root.config(menu=menu_bar)

Canvas

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

# Draw a rectangle
rectangle = canvas.create_rectangle(50, 50, 200, 150, fill="blue")

Geometry Management

root.geometry("400x300+200+100")  # Width x Height + X Offset + Y Offset

Closing the Window

root.destroy()  # Close the window

This is a basic cheat sheet, and Tkinter offers many more features and options for creating rich GUI applications. For more in-depth information, refer to the official Tkinter documentation and additional tutorials.