python - Tkinter canvas animation flicker -
i wrote python program tkinter makes ball bounce around screen. works great, except 1 problem: outermost edges of ball flicker ball moves.
i understand tkinter automatically double buffering, thought shouldn't having problems tearing. i'm not sure error coming from. ideas on how can rid of it?
code below. here's gist of it: class ball extends tk , gets created when program run. sets game, encapsulating in gmodel. gmodel runs game run() , loops on , over, calling update().
import threading time import sleep, clock tkinter import * tkinter import ttk speed = 150 # pixels per second width = 400 height = 500 rad = 25 pause = 0 # time added between frames. slows things down if necessary class gmodel: # contains game data. def __init__(self, can): # can canvas draw on self.can = can self.circ = can.create_oval(0,0, 2*rad, 2*rad) # position , velocity of ball self.x, self.y = rad, rad self.dx, self.dy = speed, speed # ball moving? self.is_running = true def update(self, elapsed_time): # updates dynamic game variables. elapsed_time in seconds. change_x = self.dx * elapsed_time change_y = self.dy * elapsed_time self.can.move(self.circ, change_x, change_y) self.x += change_x self.y += change_y self.resolve_collisions() def resolve_collisions(self): # if ball goes off edge, put , reverse velocity if self.x - rad < 0: self.x = rad self.dx = speed elif self.x + rad > width: self.x = width - rad self.dx = -speed if self.y - rad < 0: self.y = rad self.dy = speed elif self.y + rad > height: self.y = height - rad self.dy = -speed def end_game(self): self.is_running = false def run(self): last_time = 0.0 while self.is_running: # number of seconds since last iteration of loop this_time = clock() elapsed_time = this_time - last_time last_time = this_time try: # use here in case window gets x'd while t still runs self.update(elapsed_time) except: self.is_running = false if (pause > 0): sleep(pause) # slow things down if necessary class ball(tk): def __init__(self): tk.__init__(self) self.can = canvas(self, width=width, height=height) self.can.grid(row=0, column=0, sticky=(n, w, e, s)) self.gm = gmodel(self.can) def mainloop(self): t = threading.thread(target=self.gm.run, daemon=true) t.start() tk.mainloop(self) def main(): ball().mainloop() if __name__ == "__main__": main()
Comments
Post a Comment