Drawing lines using a mouse on Tkinter Canvas
The Tkinter Canvas widget provides an area to create and draw objects on. The following script demonstrates how to use mouse events to interact with Tkinter. By detecting the mouse clicks, we can use Tkinter to draw a line that follows the movement of the mouse:
Getting ready
As before, we need to have Tkinter installed and either the Raspbian desktop running (startx
from the command line) or an SSH session with X11 Forwarding and an X server running (see Chapter 1, Getting Started with a Raspberry Pi Computer). We will also need a mouse connected.
How to do it…
Create the following script, painting.py
:
#!/usr/bin/python3 #painting.py import tkinter as TK #Set defaults btn1pressed = False newline = True def main(): root = TK.Tk() the_canvas = TK.Canvas(root) the_canvas.pack() the_canvas.bind("<Motion>", mousemove) the_canvas.bind("<ButtonPress-1>", mouse1press...