-
Notifications
You must be signed in to change notification settings - Fork 1
/
eventBasedAnimationClass.py
58 lines (50 loc) · 2.07 KB
/
eventBasedAnimationClass.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# eventBasedAnimationClass.py
# CITATION: This is taken from course notes.
from Tkinter import *
class EventBasedAnimationClass(object):
def onMousePressed(self, event): pass
def onKeyPressed(self, event): pass
def onTimerFired(self): pass
def redrawAll(self): pass
def initAnimation(self): pass
def __init__(self, width=300, height=300):
self.width = width
self.height = height
self.timerDelay = 250 # in milliseconds (set to None to turn off timer)
def onMousePressedWrapper(self, event):
self.onMousePressed(event)
self.redrawAll()
def onKeyPressedWrapper(self, event):
self.onKeyPressed(event)
self.redrawAll()
def onTimerFiredWrapper(self):
if (self.timerDelay == None):
return # turns off timer
self.onTimerFired()
self.redrawAll()
self.canvas.after(self.timerDelay, self.onTimerFiredWrapper)
def onMouseMovedWrapper(self, event):
self.canvas = event.widget.canvas
ctrl = ((event.state & 0x0004) != 0)
shift = ((event.state & 0x0001) != 0)
self.canvas.data["info"] = eventInfo("mouseMotion", event.x, event.y, ctrl, shift)
self.canvas.data["motionPosn"] = (event.x, event.y)
redrawAll(canvas)
def run(self):
# create the root and the canvas
self.root = Tk()
self.canvas = Canvas(self.root, width=self.width, height=self.height)
self.canvas.pack()
self.initAnimation()
# set up events
# DK: You can use a local function with a closure
# to store the canvas binding, like this:
def f(event): self.onMousePressedWrapper(event)
self.root.bind("<Button-1>", f)
# DK: Or you can just use an anonymous lamdba function, like this:
self.root.bind("<Key>", lambda event: self.onKeyPressedWrapper(event))
self.onTimerFiredWrapper()
# and launch the app (This call BLOCKS, so your program waits
# until you close the window!)
self.root.mainloop()
# EventBasedAnimationClass(300,300).run()