How it works...

During application initialization, we create the canvas and define the current field to store a reference to the current highlighted item. We also handle the "<Motion>" events on the canvas with the mouse_motion() method:

        self.current = None
self.canvas = tk.Canvas(self, bg="white")
self.canvas.bind("<Motion>", self.mouse_motion)
self.canvas.pack()

Then, we create four items with a specific arrangement so that we can easily visualize the item that is closest to the mouse pointer:

        self.update()
w = self.canvas.winfo_width()
h = self.canvas.winfo_height()
positions = [(60, 60), (w-60, 60), (60, h-60), (w-60, h-60)]
for x, y in positions:
self.canvas.create_rectangle(x-10, y-10, x+10, y+10,
fill="blue")

The mouse_motion() handler sets the color of the current item back to blue and saves the item identifier of the new one, which is closer to the event coordinates. Finally, the fill color of this item is set to yellow:

    def mouse_motion(self, event):
self.canvas.itemconfig(self.current, fill="blue")
self.current = self.canvas.find_closest(event.x, event.y)
self.canvas.itemconfig(self.current, fill="yellow")

Initially, there are no errors when mouse_motion() is called for the first time and the current field is still None, since it is also a valid input parameter to itemconfig(); it just does not perform any action on the canvas.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset