Step 1: Import the tkinter Library
First, we need to import tkinter. You can import the entire library or just the components you need. In this example, we will import tkinter as tk to simplify the code.
import tkinter as tk
Step 2: Create the Main Window
To start, we will create a main window where we will add elements for our graphical interface.
Create the main window
window = tk.Tk()
# Set the window title
window.title("My First Interface with Tkinter")
# Set the window size
window.geometry("400x300")
Step 3: Run the Main Application Loop
Finally, we need to run the main application loop to keep the window open and responsive to user actions.
# Run the main window loop
window.mainloop()
Add a Label Widget
A Label is a text widget that allows us to display text on the window.
# Create a label and add it to the window
label = tk.Label(window, text="Hello, welcome to my application!")
label.pack() # Use pack to place the widget in the window
Add a Text Entry Widget (Entry)
The Entry widget allows the user to enter text in a text field.
# Create a text entry field
entry = tk.Entry(window)
entry.pack()
Add a Button
Now, we will add a button that, when clicked, will execute an action. We will define a function to be executed when the button is pressed.
# Define a function to be executed when the button is clicked
def show_text():
text = entry.get() # Get text from the entry field
label.config(text="Hello, " + text) # Update label text
# Create the button and add it to the window
button = tk.Button(window, text="Show text", command=show_text)
button.pack()
Add a Dropdown List with Options
First, let’s define the options we want to appear in the dropdown list. Then, we’ll use a StringVar to store the selected option, and finally, we’ll create the OptionMenu.
# Create a label
label = tk.Label(window, text="Select an option from the list!")
label.pack()
# Define the list options
options = ["Option 1", "Option 2", "Option 3", "Option 4"]
# Create a variable to store the selected option
selected_option = tk.StringVar()
selected_option.set(options[0]) # Set initial option
# Create the dropdown menu (OptionMenu)
menu_options = tk.OptionMenu(window, selected_option, *options)
menu_options.pack()
Show the Selected Option
To show the selected option, we can add a button that displays a message with the current selection when pressed. This is done with a function that executes when the button is pressed.
# Define a function to show the selected option
def show_selection():
selection = selected_option.get()
label.config(text="You selected: " + selection)
# Create a button to call the show_selection function
button = tk.Button(window, text="Show selection", command=show_selection)
button.pack()
Methods for Aligning Objects
-
Method 1: pack()
The pack() method places widgets either vertically (one below another) or horizontally (side-by-side) depending on configuration. With pack(), you can specify the options side, fill, and pad.
- side: Specifies which side of the window the widget is placed on (top, bottom, left, right).
- fill: Allows the widget to occupy more space in the horizontal (x), vertical (y), or both (both) directions.
- padx and pady: Add padding around the widget (in pixels).
Example with pack()
import tkinter as tk
window = tk.Tk()
window.title("Alignment with pack()")
window.geometry("300x200")
# Example widget
label1 = tk.Label(window, text="Top", bg="lightblue")
label1.pack(side="top", fill="x", padx=10, pady=5)
label2 = tk.Label(window, text="Bottom", bg="lightgreen")
label2.pack(side="bottom", fill="x", padx=10, pady=5)
label3 = tk.Label(window, text="Left", bg="lightcoral")
label3.pack(side="left", fill="y", padx=5, pady=10)
label4 = tk.Label(window, text="Right", bg="lightpink")
label4.pack(side="right", fill="y", padx=5, pady=10)
window.mainloop()
In this example:
- label1 is placed at the top and occupies the entire width (fill=“x”).
- label2 is placed at the bottom and also occupies the full width.
- label3 and label4 are placed on the left and right sides respectively, occupying the full height (fill=“y”).
Method 2: place()
The place() method allows precise positioning of widgets within the main window by specifying x and y coordinates.
- x and y: Specify the pixel coordinates where the widget is placed.
- relx and rely: Position the widget in relative coordinates (values between 0 and 1, where 0.5 would be the center).
- anchor: Controls the widget’s reference point (e.g., center to center the widget at the specified position).
Example with place()
import tkinter as tk
window = tk.Tk()
window.title("Alignment with place()")
window.geometry("300x200")
# Widgets in specific positions
label1 = tk.Label(window, text="Top-left corner", bg="lightblue")
label1.place(x=10, y=10)
label2 = tk.Label(window, text="Center", bg="lightgreen")
label2.place(relx=0.5, rely=0.5, anchor="center") # Center of the window
label3 = tk.Label(window, text="Bottom-right corner", bg="lightcoral")
label3.place(relx=1.0, rely=1.0, anchor="se", x=-10, y=-10) # Offset from corner
window.mainloop()
In this example:
- label1 is placed at the top-left corner, 10 pixels from the edges.
- label2 is placed in the center of the window using relative coordinates (relx=0.5, rely=0.5).
- label3 is placed in the bottom-right corner using relx=1.0, rely=1.0 and adjusts its position with x=-10 and y=-10.