How to do it...

Our App class will be responsible for creating an empty canvas and handling mouse click events.

The information on the line options will be retrieved from the LineForm class. The approach of separating this component into a different class helps us to abstract its implementation details and focus on how to work with the Canvas widget.

For the sake of brevity, we omit the implementation of the LineForm class in the following snippet:

import tkinter as tk

class LineForm(tk.LabelFrame):
# ...

class App(tk.Tk):
def __init__(self):
super().__init__()
self.title("Basic canvas")

self.line_start = None
self.form = LineForm(self)
self.canvas = tk.Canvas(self, bg="white")
self.canvas.bind("<Button-1>", self.draw)

self.form.pack(side=tk.LEFT, padx=10, pady=10)
self.canvas.pack(side=tk.LEFT)

def draw(self, event):
x, y = event.x, event.y
if not self.line_start:
self.line_start = (x, y)
else:
x_origin, y_origin = self.line_start
self.line_start = None
line = (x_origin, y_origin, x, y)
arrow = self.form.get_arrow()
color = self.form.get_color()
width = self.form.get_width()
self.canvas.create_line(*line, arrow=arrow,
fill=color, width=width)

if __name__ == "__main__":
app = App()
app.mainloop()

You can find the complete code sample in the chapter7_02.py file.

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

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