4. tkinter options
4.1. Setting Options for tk widgets
Options control things like the color and border width of a widget.
Options can be set in three ways:
4.2. At object creation time
At object creation time, using keyword arguments
button_1 = tk.Button(root, text="Button 1", fg="blue", bg="red")
4.3. After object creation
After object creation, treating the option name like a dictionary index
button_1["fg"] = "red"
button_1["bg"] = "blue"
Use the config() method to update multiple attributes subsequent to object creation
button_2.config(fg="green", bg="yellow", font=("Arial", 24))
4.4. Example code
The code below uses the config method to change the appearance of the button.
import tkinter as tk
root = tk.Tk()
root.title("pack side")
root.geometry("250x150")
button_1 = tk.Button(root, text="Button 1", fg="blue", bg="red")
button_1.pack()
button_2 = tk.Button(root, text="Button 2")
button_2.pack()
# Function to change the button's appearance
def change_button():
button_2.config(fg="green", bg="yellow", font=("Arial", 24))
# Schedule the change_button function to run after 3000 milliseconds (3 seconds)
root.after(3000, change_button)
root.mainloop()
This code users root.after function to make changes after a specified time after the window is opened.
- root.after(delay_ms, callback)
Schedule a callback function to be called after a given time.
- Parameters:
delay_ms (int) -- The delay in milliseconds before the callback is called.
callback (function) -- The function to be called after the delay.