How it works...

To dynamically select the type of item drawn by clicking on the canvas, we will create a button for each one of the shapes by iterating over the shapes tuple.

We define each callback command using the partial function from the functools module. Thanks to this, we can freeze the Button instance and the current shape of the loop as arguments to the callback of each button:

        for shape in self.shapes:
btn = tk.Button(frame, text=shape.capitalize())
btn.config(command=partial(self.set_selection, btn, shape))
btn.pack(side=tk.LEFT, expand=True, fill=tk.BOTH)

The set_selection() callback marks the clicked button with the SUNKEN relief and stores the selection in the shape field.

The other widget siblings are configured with the standard relief (RAISED) by navigating to the parent, available in the master field of the current widget, and then retrieving all the children widgets with the winfo_children() method:

    def set_selection(self, widget, shape):
for w in widget.master.winfo_children():
w.config(relief=tk.RAISED)
widget.config(relief=tk.SUNKEN)
self.shape = shape

The draw_item() handler stores the coordinates of the first click of each pair of events to draw the item when the canvas is clicked again—exactly like we previously did in the Drawing lines and arrows recipe.

Depending on the value of the shape field, one of the following methods is invoked to display the corresponding item type:

  • canvas.create_rectangle(x0, y0, x1, y1, **options): Draws a rectangle whose upper-left corner is placed at (x0, y0) and lower-right corner at (x1, y1):
  • canvas.create_oval(x0, y0, x1, y1, **options): Draws an ellipse that fits into the rectangle from (x0, y0) to (x1, y1):
  • canvas.create_arc(x0, y0, x1, y1, **options): Draws a quarter of the ellipse that would fit into the rectangle from (x0, y0) to (x1, y1):
..................Content has been hidden....................

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