Computer >> Computer tutorials >  >> Programming >> Python

Changing the color a Tkinter rectangle on clicking


The Canvas widget in Tkinter is one of the versatile widgets in Tkinter which is used for developing dynamic GUI interface of the application such as shapes, logo, arcs, animating objects, and many more. With the help of the create_rectangle(top, left, bottom, right, **options) constructor, we can create a rectangular shape in our canvas widget. All the Canvas items support multiple features such as shapes property, size, color, outline, etc.

Let us suppose that we want to change the color of the drawn rectangle with the help of a button event. Defining a callback function that extends the property such as fill= color would change the color of the rectangle.

Example

# Import the required libraries
from tkinter import *

# Create an instance of Tkinter Frame
win = Tk()

# Set the geometry of Tkinter Frame
win.geometry("700x250")

# Define a function to change the color of the rectangle
def change_color(*args):
   canvas.itemconfig(shape, fill='blue')

# Add a canvas inside the frame
canvas = Canvas(win, width=500, height=250)
canvas.pack()

# Add a rectangle inside the canvas widget
shape = canvas.create_rectangle(500, 100, 50, 50, fill='red')

# Add a button to change the color of the rectangle
button = Button(win, text="Change Color", font=('Helvectica 11'),
command = lambda: change_color(canvas))
button.place(relx=.5, rely=.5, anchor=CENTER)
win.mainloop()

Output

If we run the above code, it will display a window with a rectangle and a button widget.

Changing the color a Tkinter rectangle on clicking

On clicking the "Change Color" button, it will change the color of the rectangle to blue.

Changing the color a Tkinter rectangle on clicking