Simple mouse input

We now develop code that helps to draw complicated shapes by capturing mouse clicks on electronic graph paper rather than with a pencil, eraser, and sheets of paper made from dead trees. We break this complex task into simple steps covered by the next three recipes.

# mouseclick_1.py
#>>>>>>>>>>>>>>>
from Tkinter import *
root = Tk()
frame = Frame(root, width=100, height=100)
def callback(event):
print "clicked at", event.x, event.y
frame.bind("<Button-1>", callback)
frame.grid()
root.mainloop()
root.destroy()

How it works...

Clicking a mouse button is referred to as an event. If we want our program to perform some actions within our program, then we need to write a callback function that is called whenever the event occurs. Older terminology for callback was "interrupt service routine".

The line frame.bind("<Button-1>", callback) says in effect:

"Make a connection (bind()) between the event, which is the click of the left button on the mouse (<Button-1>), and the function called callback". You could name this function anything you like, but the word callback makes the code easier to understand.

The final point to note is that the variables event.x and event.y are reserved for recording the x-y coordinates of the mouse. In this specific callback function we print out the position, in a frame called "frame", of the mouse when clicked.

There's more...

We build on the use of mouse-triggered callback functions in the next two recipes with the objective of producing a shape-tracing tool.

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

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