Simple animation using tkinter

I have simple code to visualize some data using tkinter. A button click is bound to a function that redraws the next “frame” of data. However, I would like to be able to automatically redraw at a certain frequency. I am very green when it comes to GUI programming (I don’t need to do much for this code), so most of my tkinter knowledge comes from the following and modifying examples. I think I can use root.after to achieve this, but I'm not quite sure that I understand how from other codes. The basic structure of my program is as follows:

# class for simulation data
# --------------------------------

def Visualisation:

   def __init__(self, args):
       # sets up the object


   def update_canvas(self, Event):
       # draws the next frame

       canvas.delete(ALL)

       # draw some stuff
       canvas.create_........


# gui section
# ---------------------------------------

# initialise the visualisation object
vis = Visualisation(s, canvasWidth, canvasHeight)

# Tkinter initialisation
root = Tk()
canvas = Canvas(root, width = canvasWidth, height = canvasHeight)

# set mouse click to advance the simulation
canvas.grid(column=0, row=0, sticky=(N, W, E, S))
canvas.bind('<Button-1>', vis.update_canvas)

# run the main loop
root.mainloop()

Apologies for asking the question, which I am sure has an obvious and simple answer. Many thanks.

+4
2

Tkinter - , . - , :

def animate(self):
    self.draw_one_frame()
    self.after(100, self.animate)

, - 100 . , , . :

def animate(self):
    if not self.should_stop:
        self.draw_one_frame()
        self.after(100, self.animate)

, self.should_stop False

+12

. .

- self.after_cancel() .

...

def animate(self):
    self.draw_one_frame()
    self.stop_id = self.after(100, self.animate)

def cancel(self):
    self.after_cancel(self.stop_id)
+1

All Articles