Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 9 - GUI Programming using Tkinter - Section 9.5 - Canvas - Check Point - MyProgrammingLab - Page 283: 9.20

Answer

In Tkinter, you can make a shape change color when the mouse is moved over it by binding a callback function to the event of the shape. This event is triggered when the mouse enters the bounding box of the shape.

Work Step by Step

Here's an example of how you can change the color of a rectangle when the mouse is moved over it: import tkinter as tk root = tk.Tk() canvas = tk.Canvas(root, bg="white", height=200, width=200) canvas.pack() x1, y1 = 10, 10 x2, y2 = 50, 50 rect = canvas.create_rectangle(x1, y1, x2, y2, fill="red") def change_color(event): canvas.itemconfig(rect, fill="blue") def change_back(event): canvas.itemconfig(rect, fill="red") canvas.tag_bind(rect, "", change_color) canvas.tag_bind(rect, "", change_back) root.mainloop() we defined two callback functions: change_color and change_back. The change_color function is triggered when the mouse enters the bounding box of the rectangle and changes its color to blue. The change_back function is triggered when the mouse leaves the bounding box of the rectangle and changes its color back to red. Finally, we use the tag_bind method of the canvas to bind the change_color function to the event of the rectangle, and the change_back function to the event of the rectangle. This will cause the color of the rectangle to change when the mouse is moved over it.
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.