[Tutor] tkinter events: <B1-Motion>
zslevi at sch.bme.hu
Sat Aug 26 08:03:35 CEST 2006
So, in the following line
the event-handler will call handler(event, 'release') when the
mousebutton is released, but the 'self' reference is automatically
passed over, so the result will be the handler(self,event, 'release') call.
Correct me, if I'm wrong.
># This program implements <B1-motion>. it was originally written by
>#Zsiros Levente. all rights of this modified version go to him :)
>from Tkinter import *
> def __init__(self):
> #our self.mousedown variable is what we'll use to check the state
> #of the button, since we're going to be passing a copy of 'self'
> #around, we don't have to deal with scoping of the variables.
> #I.E. self.mousedown is global to functions in the class
> #that accept a 'self' argument.
> self.mousedown = 0
> #we make the window normally. note all these are 'self' variables
> #so we can change them easily elsewhere in the class.
> self.root = Tk()
> self.label = Label(self.root, text=str(self.mousedown))
> self.can = Canvas(self.root, width='500', height='400', bg='white')
> #lambda is a way we can add extra arguments to a function.
> #since the callback of bound events is only a single argument,
> #we use 'lambda x' to get the 'event' instance, and pass it
> #along with another string identifying which event it came from.
> #this may or may not be necessary, but it's cool and it
> #makes the handler function make more sense.
> #also, we only need one handler function this way.
> self.can.bind("<Motion>",lambda x:self.handler(x,'motion'))
> self.can.bind("<Button-1>",lambda x:self.handler(x,'press'))
> self.can.bind("<ButtonRelease-1>",lambda x:self.handler(x,'release'))
> def handler(self,event,x):
> #the first two clauses of the if-elif branch implement your
> #'press' and 'release' functions.
> if x == 'press':
> self.mousedown = 1
> elif x == 'release':
> self.mousedown = 0
> elif x == 'motion':
> if self.mousedown:
> #you could do something really cool here, like store the time
> #that the button was last pressed, and increase the radius of the circle
> #depending on how long it's been since then.
> r = 5
> self.can.create_oval(event.x-r, event.y-r, event.x+r, event.y+r, fill="orange")
>#we create an instance of the class which automatically
>#calls the '__init__' method.
>x = ButtonHandler()
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Tutor