# L-32 MCS 260 Fri 9 Nov 2007 : movedot.py # # GUI for a random walk. from Tkinter import * import random class MovingDot(): """ GUI to illustrate an animation. """ def __init__(self,wdw): "determines the layout of the GUI" wdw.title('a moving dot') self.d = 400 self.c = Canvas(wdw,width=self.d,\ height=self.d,bg ='white') self.c.grid(row=0,column=0,columnspan=2) self.T = Label(wdw,text="sleep time") self.T.grid(row=1,column=0,columnspan=2) self.x = self.d/2 self.y = self.d/2 self.go = False self.sleep = IntVar() self.step = IntVar() self.s = Scale(wdw,\ orient='horizontal',from_=0,to=300,\ tickinterval=50,resolution=1,\ length=300,variable=self.sleep) self.s.grid(row=2,column=0,columnspan=2,\ sticky=W+E+N+S) self.s.set(100) self.h = Scale(wdw,\ orient='vertical',from_=0,to=100,\ tickinterval=10,resolution=1,\ length=400,variable=self.step) self.h.grid(row=0,column=2) self.h.set(10) self.b0 = Button(wdw,text="start",\ command = self.start) self.b0.grid(row=3,column=0,sticky=W+E) self.b1 = Button(wdw,text="stop",\ command = self.stop) self.b1.grid(row=3,column=1,sticky=W+E) def animate(self): "performs the animation" vx = self.x vy = self.y while self.go: self.c.delete("dot") self.c.create_oval(vx-6,vy-6,vx+6,vy+6,width=1,\ outline='black',fill='SkyBlue2',tags="dot") n = self.step.get() vx = vx + random.randint(-n,n); vy = vy + random.randint(-n,n) if vx >= self.d: vx = vx - self.d if vy >= self.d: vy = vy - self.d if vx < 0: vx = vx + self.d if vy < 0: vy = vy + self.d self.c.after(self.sleep.get()) self.c.update() def start(self): "starts the animation" self.go = True self.animate() def stop(self): "stops the animation" self.go = False def main(): top = Tk() show = MovingDot(top) top.mainloop() if __name__ == "__main__": main()