Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to change the color of a Tkinter rectangle on clicking?
The Canvas widget is one of the most versatile widgets in the Tkinter Library. It is used for creating shapes of different types and sizes, animating objects, visualizing graphics, and many more. To change the property of a particular item in Tkinter, we can use the itemconfig(**options) method. It takes options such as background color, outline color, and other useful properties of the items defined in a canvas.
Example
In this example, we will create a rectangle such that the color inside the rectangle would change after clicking a Button ?
# Import the required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of Tkinter Frame
win = Tk()
# Set the geometry
win.geometry("700x300")
# Define a function to change the state of the Widget
def change_color():
canvas.itemconfig(rectangle, fill='green')
# Define a Canvas Widget
canvas = Canvas(win, width=500, height=240)
canvas.pack()
# Create a rectangle in Canvas
rectangle = canvas.create_rectangle(100, 100, 400, 200, fill='blue')
# Create a Button to change the rectangle color
ttk.Button(win, text="Change Color", command=change_color).pack()
win.mainloop()
How It Works
The canvas.create_rectangle() method creates a rectangle and returns its ID. We store this ID in the rectangle variable. When the button is clicked, the change_color() function uses itemconfig() to modify the rectangle's fill color from blue to green.
Multiple Color Changes
You can also cycle through multiple colors by tracking the current color state ?
from tkinter import *
from tkinter import ttk
win = Tk()
win.geometry("700x300")
# List of colors to cycle through
colors = ['blue', 'green', 'red', 'yellow', 'purple']
current_color = 0
def change_color():
global current_color
current_color = (current_color + 1) % len(colors)
canvas.itemconfig(rectangle, fill=colors[current_color])
canvas = Canvas(win, width=500, height=240)
canvas.pack()
rectangle = canvas.create_rectangle(100, 100, 400, 200, fill=colors[0])
ttk.Button(win, text="Change Color", command=change_color).pack()
win.mainloop()
Key Methods
| Method | Purpose | Example |
|---|---|---|
create_rectangle() |
Creates a rectangle shape | canvas.create_rectangle(x1, y1, x2, y2) |
itemconfig() |
Modifies canvas item properties | canvas.itemconfig(item_id, fill='red') |
Conclusion
Use itemconfig() to dynamically change canvas item properties like color. Store the item ID returned by create_rectangle() to reference the shape later for modifications.
