Okay, here’s a comprehensive article on getting started with Tkinter for Python GUI development, aiming for approximately 5000 words. I’ve broken it down into logical sections to make it easier to digest and reference.
Tkinter Tutorial: Getting Started with Python GUI
Introduction
Graphical User Interfaces (GUIs) are essential for creating user-friendly applications. They provide a visual way for users to interact with software, making it more intuitive and accessible than command-line interfaces. Python, a versatile and popular programming language, offers several libraries for GUI development. Tkinter stands out as the de facto standard GUI toolkit for Python. It’s included with standard Python installations, making it readily available and easy to start using. This tutorial provides a comprehensive introduction to Tkinter, covering everything from basic concepts to building functional applications.
This guide aims to equip you with the foundational knowledge to:
- Understand the core principles of Tkinter.
- Create basic GUI elements (widgets).
- Arrange widgets using layout managers.
- Handle user events (like button clicks).
- Build simple, functional applications.
Why Tkinter?
Tkinter offers several advantages for Python GUI development:
- Standard Library: It’s part of the Python standard library, meaning no external dependencies are required. This simplifies installation and deployment.
- Cross-Platform: Tkinter applications generally work across different operating systems (Windows, macOS, Linux) with minimal modifications.
- Easy to Learn: Tkinter has a relatively simple API, making it a good choice for beginners. Its syntax is generally considered intuitive and Pythonic.
- Extensive Documentation and Community Support: Being the standard GUI toolkit, Tkinter boasts extensive documentation and a large, active community, making it easy to find help and solutions.
- ttk (Themed Tkinter): The
ttk
module provides themed widgets, giving your applications a more modern and native look and feel.
While Tkinter might not be the best choice for extremely complex or visually demanding applications (where frameworks like PyQt or Kivy might be more suitable), it’s an excellent starting point and perfectly capable of handling a wide range of GUI development tasks.
Prerequisites
Before diving into Tkinter, you should have a basic understanding of Python programming concepts, including:
- Variables and data types
- Control flow (if statements, loops)
- Functions
- Object-oriented programming (OOP) principles (classes, objects) – While not strictly required for basic Tkinter use, OOP becomes increasingly important as your applications grow.
Getting Started: Your First Tkinter Window
Let’s start with the simplest possible Tkinter application – creating an empty window.
“`python
import tkinter as tk
Create the main application window
root = tk.Tk()
Set the window title
root.title(“My First Tkinter Window”)
Set the window size (width x height)
root.geometry(“400×300”) # 400 pixels wide, 300 pixels high
Start the Tkinter event loop
root.mainloop()
“`
Explanation:
import tkinter as tk
: This line imports the Tkinter module and gives it the aliastk
. This is a common practice to make the code shorter and more readable.root = tk.Tk()
: This creates the main application window, often referred to as the “root” window. Every Tkinter application must have a root window. It’s an instance of theTk
class.root.title("My First Tkinter Window")
: This sets the title that appears in the window’s title bar.root.geometry("400x300")
: This sets the initial size of the window. The format is “widthxheight” (in pixels). You can also specify the window’s position on the screen using “+x+y” (e.g., “400×300+100+50” would position the window 100 pixels from the left edge and 50 pixels from the top edge of the screen). If you don’t set geometry, the window will automatically size itself to fit its contents.root.mainloop()
: This is the most crucial part. It starts the Tkinter event loop. The event loop is what keeps the window open and responsive. It listens for user events (mouse clicks, key presses, etc.) and triggers the appropriate actions. Withoutmainloop()
, the window would appear briefly and then immediately close.
Key Concepts
Before we move on to adding widgets, let’s solidify some fundamental Tkinter concepts:
- Widgets: Widgets are the building blocks of a Tkinter GUI. They are the visual elements that users interact with, such as buttons, labels, text entry fields, checkboxes, and more. Each widget is an instance of a specific Tkinter class (e.g.,
Button
,Label
,Entry
). - Root Window: As mentioned earlier, the root window is the main container for all other widgets. It’s the top-level window of your application.
- Event Loop: The event loop is the heart of a Tkinter application. It continuously monitors for user interactions and dispatches events to the appropriate widgets.
- Layout Managers: Layout managers are responsible for arranging widgets within a window. Tkinter provides three main layout managers:
pack()
: The simplest layout manager. It packs widgets into a window in a top-to-bottom or side-by-side fashion.grid()
: Arranges widgets in a table-like grid of rows and columns.place()
: Allows you to place widgets at specific x and y coordinates within a window. This offers the most control but can be less flexible for resizing.
- Attributes/Options: Widgets have various attributes (also called options) that control their appearance and behavior. Examples include text, color, font, size, and command (for buttons). You can set these attributes when creating the widget or modify them later.
- Events and Bindings: Tkinter uses an event-driven programming model. Events, such as button clicks, key presses, mouse movements, are generated by user actions. You can bind these events to specific functions (called event handlers or callbacks) that will be executed when the event occurs.
Common Tkinter Widgets
Let’s explore some of the most commonly used Tkinter widgets:
1. Label
The Label
widget is used to display text or images. It’s a simple, read-only widget.
“`python
import tkinter as tk
root = tk.Tk()
root.title(“Label Example”)
root.geometry(“300×200”)
Create a Label
my_label = tk.Label(root, text=”Hello, Tkinter!”, font=(“Arial”, 16), fg=”blue”, bg=”lightgray”)
Pack the label into the window
my_label.pack(pady=20) # Add some padding around the label
root.mainloop()
“`
Explanation:
tk.Label(root, ...)
: Creates aLabel
widget. The first argument (root
) specifies the parent window (the root window in this case).text="Hello, Tkinter!"
: Sets the text displayed by the label.font=("Arial", 16)
: Sets the font to Arial, size 16. You can also specify the font style (e.g., “bold”, “italic”).fg="blue"
: Sets the foreground color (text color) to blue. Tkinter accepts color names (e.g., “red”, “green”, “blue”, “yellow”, “black”, “white”) or hexadecimal color codes (e.g., “#FF0000” for red).bg="lightgray"
: Sets the background color to light gray.my_label.pack(pady=20)
: Uses thepack()
layout manager to place the label in the window.pady=20
adds 20 pixels of vertical padding around the label.
2. Button
The Button
widget is used to create clickable buttons. Buttons are typically associated with actions that are performed when the button is clicked.
“`python
import tkinter as tk
def button_clicked():
print(“Button clicked!”)
my_label.config(text=”Button was clicked!”) #Change the label text
root = tk.Tk()
root.title(“Button Example”)
root.geometry(“300×200”)
my_label = tk.Label(root, text=”Click the button”)
my_label.pack(pady=10)
Create a Button
my_button = tk.Button(root, text=”Click Me!”, command=button_clicked)
Pack the button into the window
my_button.pack(pady=10)
root.mainloop()
“`
Explanation:
tk.Button(root, ...)
: Creates aButton
widget.text="Click Me!"
: Sets the text displayed on the button.command=button_clicked
: This is the key part. It associates the button with thebutton_clicked
function. When the button is clicked, thebutton_clicked
function will be executed. This is an example of an event handler or callback function.my_label.config(text="Button was clicked!")
: Inside thebutton_clicked
function, this line demonstrates how to change a widget’s attributes after it has been created.config()
(or its synonymconfigure()
) is used to modify widget options.
3. Entry
The Entry
widget is used to create single-line text entry fields. Users can type text into an Entry
widget.
“`python
import tkinter as tk
def get_text():
user_input = my_entry.get()
print(“You entered:”, user_input)
my_label.config(text=”You entered: ” + user_input)
root = tk.Tk()
root.title(“Entry Example”)
root.geometry(“300×200”)
my_label = tk.Label(root, text=”Enter some text:”)
my_label.pack()
Create an Entry widget
my_entry = tk.Entry(root, width=30) # Set the width of the entry field
my_entry.pack(pady=10)
Create a button to get the text
get_button = tk.Button(root, text=”Get Text”, command=get_text)
get_button.pack()
root.mainloop()
“`
Explanation:
tk.Entry(root, ...)
: Creates anEntry
widget.width=30
: Sets the width of the entry field (in characters).my_entry.get()
: This is how you retrieve the text that the user has entered into theEntry
widget. Theget()
method returns the current contents of the entry field as a string.
4. Text
The Text
widget is used for multi-line text input and display. It’s more versatile than Entry
for handling larger blocks of text.
“`python
import tkinter as tk
def insert_text():
my_text.insert(tk.END, “This text was inserted.\n”)
def clear_text():
my_text.delete(“1.0”, tk.END) #Delete from line 1, character 0, to the end
root = tk.Tk()
root.title(“Text Example”)
root.geometry(“400×300”)
Create a Text widget
my_text = tk.Text(root, height=10, width=40)
my_text.pack(pady=10)
Add some initial text
my_text.insert(tk.END, “Initial text.\nWrite something here.\n”)
insert_button = tk.Button(root, text=”Insert Text”, command=insert_text)
insert_button.pack()
clear_button = tk.Button(root, text=”Clear Text”, command=clear_text)
clear_button.pack()
root.mainloop()
“`
Explanation:
tk.Text(root, ...)
: Creates aText
widget.height=10
: Sets the height of the text area (in lines).width=40
: Sets the width of the text area (in characters).my_text.insert(tk.END, "This text...")
: Inserts text at the specified position.tk.END
represents the end of the text widget. You can also insert text at specific line and character positions (e.g., “1.0” for the beginning).my_text.delete("1.0", tk.END)
: Deletes text from the specified starting position to the ending position. “1.0” represents the very beginning of the text (line 1, character 0).
5. Checkbutton
The Checkbutton
widget creates a checkbox that can be toggled on or off.
“`python
import tkinter as tk
def show_state():
print(“Checkbox state:”, check_var.get())
my_label.config(text=f”Checkbox is {‘checked’ if check_var.get() else ‘unchecked’}”)
root = tk.Tk()
root.title(“Checkbutton Example”)
root.geometry(“300×200”)
Create a Tkinter variable to store the checkbox state
check_var = tk.IntVar() # Use IntVar for integer values (0 or 1)
Create a Checkbutton
my_checkbox = tk.Checkbutton(root, text=”Check me”, variable=check_var, command=show_state)
my_checkbox.pack(pady=10)
my_label = tk.Label(root, text=””)
my_label.pack()
root.mainloop()
“`
Explanation:
check_var = tk.IntVar()
: This creates a special Tkinter variable (IntVar
) to hold the state of the checkbox. Tkinter variables are used to track the values of widgets and automatically update them when the widget’s state changes.IntVar
is used for checkboxes because their state is typically represented as an integer (0 for unchecked, 1 for checked).variable=check_var
: This links theCheckbutton
to thecheck_var
variable. When the checkbox is toggled, the value ofcheck_var
will automatically change.check_var.get()
: Retrieves the current value of thecheck_var
variable (0 or 1).
6. Radiobutton
Radiobutton
widgets are used to create a group of mutually exclusive options. Only one radio button in a group can be selected at a time.
“`python
import tkinter as tk
def show_selection():
print(“Selected option:”, radio_var.get())
my_label.config(text=f”You selected option {radio_var.get()}”)
root = tk.Tk()
root.title(“Radiobutton Example”)
root.geometry(“300×200”)
Create a Tkinter variable to store the selected radio button value
radio_var = tk.StringVar(value=”Option 1″) #StringVar for string values. Set initial value.
Create Radiobuttons
radio1 = tk.Radiobutton(root, text=”Option 1″, variable=radio_var, value=”Option 1″, command=show_selection)
radio1.pack()
radio2 = tk.Radiobutton(root, text=”Option 2″, variable=radio_var, value=”Option 2″, command=show_selection)
radio2.pack()
radio3 = tk.Radiobutton(root, text=”Option 3″, variable=radio_var, value=”Option 3″, command=show_selection)
radio3.pack()
my_label = tk.Label(root, text=””)
my_label.pack()
root.mainloop()
“`
Explanation:
radio_var = tk.StringVar(value="Option 1")
: Creates aStringVar
to hold the value of the selected radio button.StringVar
is used because the values associated with the radio buttons are strings (“Option 1”, “Option 2”, “Option 3”). We set the initial value.variable=radio_var
: All radio buttons in the same group must be linked to the same Tkinter variable.value="Option 1"
: This sets the value that will be assigned toradio_var
when this particular radio button is selected. Each radio button in the group must have a uniquevalue
.radio_var.get()
retrieves the value of the currently selected radio button.
7. Frame
The Frame
widget is a container widget used to group other widgets together. It’s useful for organizing your layout and applying common styles to a group of widgets.
“`python
import tkinter as tk
root = tk.Tk()
root.title(“Frame Example”)
root.geometry(“400×300”)
Create a Frame
frame1 = tk.Frame(root, bg=”lightblue”, bd=2, relief=”groove”) # Add border and relief
frame1.pack(padx=10, pady=10)
Add widgets to the Frame
label1 = tk.Label(frame1, text=”Label in Frame 1″)
label1.pack()
button1 = tk.Button(frame1, text=”Button in Frame 1″)
button1.pack()
Create another Frame
frame2 = tk.Frame(root, bg=”lightgreen”, bd=2, relief=”ridge”)
frame2.pack(padx=10, pady=10, fill=”x”) # Fill the available horizontal space
label2 = tk.Label(frame2, text=”Label in Frame 2″)
label2.pack()
root.mainloop()
“`
Explanation:
* tk.Frame(root, ...)
: Creates a Frame widget.
* bg="lightblue"
: Sets the background color.
* bd=2
: Sets the border width (in pixels).
* relief="groove"
: Sets the border style. Other options include “flat”, “raised”, “sunken”, “ridge”, and “solid”.
* frame1.pack(padx=10, pady=10)
: padx
and pady
add external padding around the frame.
* frame2.pack(..., fill="x")
: The fill
option controls how the frame expands to fill available space. "x"
means it will fill horizontally, "y"
vertically, and "both"
in both directions.
8. Scrollbar
The Scrollbar
widget is used to add scrolling functionality to other widgets, such as Text
, Listbox
, and Canvas
. It’s almost always used in conjunction with another widget.
“`python
import tkinter as tk
root = tk.Tk()
root.title(“Scrollbar Example”)
root.geometry(“400×300”)
Create a Frame to hold the Text and Scrollbar
frame = tk.Frame(root)
frame.pack(expand=True, fill=”both”)
Create a Scrollbar
scrollbar = tk.Scrollbar(frame)
scrollbar.pack(side=”right”, fill=”y”)
Create a Text widget
my_text = tk.Text(frame, wrap=”word”, yscrollcommand=scrollbar.set) # Connect scrollbar to Text
my_text.pack(expand=True, fill=”both”)
Configure the Scrollbar to work with the Text widget
scrollbar.config(command=my_text.yview)
Add some text to the Text widget
for i in range(50):
my_text.insert(tk.END, f”Line {i+1}\n”)
root.mainloop()
“`
Explanation:
- We create a
Frame
to hold both theText
widget and theScrollbar
. This is a common pattern. tk.Scrollbar(frame)
: Creates theScrollbar
widget.scrollbar.pack(side="right", fill="y")
: Places the scrollbar on the right side of the frame and makes it fill the available vertical space.my_text = tk.Text(..., yscrollcommand=scrollbar.set)
: This is the crucial connection. Theyscrollcommand
option of theText
widget is set to theset
method of theScrollbar
. This tells theText
widget to update the scrollbar’s position whenever the text view changes.scrollbar.config(command=my_text.yview)
: This completes the connection. Thecommand
option of theScrollbar
is set to theyview
method of theText
widget. This tells the scrollbar to scroll theText
widget when the user interacts with the scrollbar.wrap="word"
: This makes the text wrap at word boundaries instead of character boundaries.
9. Listbox
The Listbox
widget displays a list of items from which the user can select one or more.
“`python
import tkinter as tk
def show_selected():
selected_indices = my_listbox.curselection() # Get indices of selected items
selected_items = [my_listbox.get(i) for i in selected_indices] # Get selected items
print(“Selected items:”, selected_items)
my_label.config(text=f”Selected: {‘, ‘.join(selected_items)}”)
root = tk.Tk()
root.title(“Listbox Example”)
root.geometry(“300×200”)
Create a Listbox
my_listbox = tk.Listbox(root, selectmode=”multiple”) # Allow multiple selections
my_listbox.pack(pady=10)
Insert items into the Listbox
items = [“Item 1”, “Item 2”, “Item 3”, “Item 4”, “Item 5”]
for item in items:
my_listbox.insert(tk.END, item)
select_button = tk.Button(root, text=”Show Selected”, command=show_selected)
select_button.pack()
my_label = tk.Label(root, text=””)
my_label.pack()
root.mainloop()
“`
Explanation:
tk.Listbox(root, ...)
: Creates aListbox
widget.selectmode="multiple"
: Allows the user to select multiple items. Other options are “single” (default), “browse” (similar to single), and “extended” (allows selection using Shift and Ctrl keys).my_listbox.insert(tk.END, item)
: Inserts an item at the end of the listbox.my_listbox.curselection()
: Returns a tuple containing the indices of the currently selected items.my_listbox.get(i)
: Returns the text of the item at indexi
.- List comprehension
[my_listbox.get(i) for i in selected_indices]
is used to efficiently get all selected items.
10. Scale
The Scale
widget allows the user to select a numerical value by dragging a slider.
“`python
import tkinter as tk
def show_value(value): #Value is passed automatically
print(“Scale value:”, value)
my_label.config(text=f”Scale value: {value}”)
root = tk.Tk()
root.title(“Scale Example”)
root.geometry(“300×200”)
Create a Scale
my_scale = tk.Scale(root, from_=0, to=100, orient=”horizontal”, command=show_value)
my_scale.pack(pady=10)
my_label = tk.Label(root, text=””)
my_label.pack()
root.mainloop()
“`
Explanation:
tk.Scale(root, ...)
: Creates aScale
widget.from_=0
: Sets the minimum value of the scale. Note the underscore afterfrom
– this is becausefrom
is a reserved keyword in Python.to=100
: Sets the maximum value of the scale.orient="horizontal"
: Makes the scale horizontal. The default is “vertical”.command=show_value
: Thecommand
option is set to theshow_value
function. Crucially, Tkinter automatically passes the current value of the scale as an argument to thecommand
function. This is whyshow_value
takes avalue
parameter.
11. Menu
The Menu
widget creates menus (like File, Edit, View) that appear at the top of a window.
“`python
import tkinter as tk
from tkinter import messagebox #Import for messagebox
def new_file():
print(“New File”)
messagebox.showinfo(“Info”, “New File created!”)
def open_file():
print(“Open file”)
messagebox.showwarning(“Warning”, “Open File not implemented”)
def exit_app():
if messagebox.askokcancel(“Quit”, “Do you really want to quit?”):
root.destroy() # Close the application
root = tk.Tk()
root.title(“Menu Example”)
root.geometry(“400×300”)
Create a Menu Bar
menubar = tk.Menu(root)
root.config(menu=menubar) # Attach the menu bar to the root window
Create a File Menu
filemenu = tk.Menu(menubar, tearoff=0) # tearoff=0 prevents the menu from being “torn off”
menubar.add_cascade(label=”File”, menu=filemenu) # Add the File menu to the menu bar
Add commands to the File Menu
filemenu.add_command(label=”New”, command=new_file)
filemenu.add_command(label=”Open”, command=open_file)
filemenu.add_separator() # Add a separator line
filemenu.add_command(label=”Exit”, command=exit_app)
Create an Edit menu (for demonstration)
editmenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label=”Edit”, menu=editmenu)
editmenu.add_command(label=”Cut”, command=lambda: print(“Cut”))
editmenu.add_command(label=”Copy”, command=lambda: print(“Copy”))
editmenu.add_command(label=”Paste”, command=lambda: print(“Paste”))
root.mainloop()
“`
Explanation:
menubar = tk.Menu(root)
: Creates aMenu
object to serve as the menu bar.root.config(menu=menubar)
: This is essential. It attaches the menu bar to the root window. Without this, the menu bar won’t be visible.filemenu = tk.Menu(menubar, tearoff=0)
: Creates a submenu (the “File” menu) within the menu bar.tearoff=0
prevents the user from detaching the menu into a separate window.menubar.add_cascade(label="File", menu=filemenu)
: Adds the “File” menu to the menu bar.add_cascade
is used to add submenus.filemenu.add_command(label="New", command=new_file)
: Adds a command (“New”) to the “File” menu. When this command is selected, thenew_file
function will be called.filemenu.add_separator()
: Adds a horizontal separator line to the menu.messagebox
: Thetkinter.messagebox
module provides functions for displaying standard dialog boxes (info, warning, error, question, etc.).messagebox.showinfo()
: Displays an informational message.messagebox.showwarning()
: Displays a warning message.messagebox.askokcancel()
: Asks a yes/no question (OK/Cancel). ReturnsTrue
if OK is clicked,False
otherwise.
root.destroy()
: Closes the Tkinter application.- Lambda functions:
lambda: print("Cut")
creates a small, anonymous function. This is useful for simple commands where defining a separate named function would be overkill.
12. Canvas
The Canvas widget is a versatile widget for drawing graphics, shapes, images, and text. It’s suitable for creating custom widgets or more complex visual elements.
“`python
import tkinter as tk
root = tk.Tk()
root.title(“Canvas Example”)
root.geometry(“400×300”)
Create a Canvas
canvas = tk.Canvas(root, width=300, height=200, bg=”white”)
canvas.pack(pady=20)
Draw a line
canvas.create_line(50, 50, 250, 100, fill=”blue”, width=3)
Draw a rectangle
canvas.create_rectangle(100, 120, 200, 180, fill=”red”, outline=”black”)
Draw an oval (circle)
canvas.create_oval(20, 20, 80, 80, fill=”green”)
Draw text
canvas.create_text(150, 30, text=”Hello, Canvas!”, font=(“Arial”, 14))
root.mainloop()
“`
Explanation:
tk.Canvas(root, ...)
: Creates a Canvas widget.canvas.create_line(...)
: Draws a line. The arguments are the x and y coordinates of the starting and ending points.canvas.create_rectangle(...)
: Draws a rectangle. The arguments are the x and y coordinates of the top-left and bottom-right corners.canvas.create_oval(...)
: Draws an oval (or a circle if the bounding rectangle is a square).canvas.create_text(...)
: Draws text.
Layout Managers: Organizing Your Widgets
We’ve already touched on layout managers, but let’s delve deeper into each one:
1. pack()
The pack()
manager is the simplest. It arranges widgets in blocks, either vertically (top-to-bottom) or horizontally (side-by-side).
Key pack()
Options:
side
: Specifies the side to pack the widget on:"top"
(default),"bottom"
,"left"
, or"right"
.fill
: Controls whether the widget expands to fill the available space:"none"
(default),"x"
(horizontal),"y"
(vertical), or"both"
.expand
: If set toTrue
(or 1), the widget will expand to fill any extra space allocated to its parent container.padx
: Adds external horizontal padding (in pixels).pady
: Adds external vertical padding (in pixels).ipadx
: Adds internal horizontal padding (within the widget’s borders).ipady
: Adds internal vertical padding.
“`python
import tkinter as tk
root = tk.Tk()
root.geometry(“300×200”)
label1 = tk.Label(root, text=”Label 1″, bg=”red”)
label1.pack(side=”left”, fill=”y”) # Fill vertically
label2 = tk.Label(root, text=”Label 2″, bg=”green”)
label2.pack(side=”top”, fill=”x”, expand=True) # Fill horizontally and expand
label3 = tk.Label(root, text=”Label 3″, bg=”blue”)
label3.pack(side=”bottom”, padx=10, pady=5) # Add external padding
root.mainloop()
“`
2. grid()
The grid()
manager arranges widgets in a table-like grid of rows and columns.
Key grid()
Options:
row
: The row number (starting from 0).column
: The column number (starting from 0).rowspan
: The number of rows the widget should span.columnspan
: The number of columns the widget should span.sticky
: Controls how the widget is aligned within its grid cell if the cell is larger than the widget. Values can be a combination of “n” (north), “s” (south), “e” (east), “w” (west), using string concatenation (e.g., “nsew” to stretch the widget to fill the cell).padx
: External horizontal padding.pady
: External vertical padding.ipadx
: Internal horizontal padding.ipady
: Internal vertical padding.
“`python
import tkinter as tk
root = tk.Tk()
root.geometry(“300×200”)
label1 = tk.Label(root, text=”Label 1″, bg=”red”)
label1.grid(row=0, column=0, sticky=”nsew”) # Stretch to fill the cell
label2 = tk.Label(root, text=”Label 2″, bg=”green”)
label2.grid(row=0, column=1, padx=10, pady=5) # Add padding
label3 = tk.Label(root, text=”Label 3″, bg=”blue”)
label3.grid(row=1, column=0, columnspan=2, sticky=”ew”) # Span two columns, stretch horizontally
button1 = tk.Button(root, text=”Button 1″)
button1.grid(row=2, column=0, sticky=”w”) # Align to the west (left)
root.mainloop()
“`
3. place()
The place()
manager gives you the most precise control over widget positioning. You specify the exact x and y coordinates (in pixels) of the widget’s top-left corner. However, it’s generally less flexible than pack()
and grid()
for handling window resizing.
Key place()
Options:
x
: The x-coordinate.y
: The y-coordinate.width
: The width of the widget.height
: The height of the widget.relx
: Relative x-coordinate (0.0 to 1.0), representing a fraction of the parent’s width.rely
: Relative y-coordinate (0.0 to 1.0).relwidth
: Relative width (0.0 to 1.0).relheight
: Relative height (0.0 to 1.0).anchor
: Specifies which point of the widget is placed at the given coordinates. Can be one of “nw” (northwest, default), “n”, “ne”, “w”, “center”, “e”, “sw”, “s”, “se”.
“`python
import tkinter as tk
root = tk.Tk()
root.geometry(“300×200”)
label1 = tk.Label(root, text=”Label 1