使用tkinter的简单动画

use*_*634 4 python user-interface animation tkinter

我有一个简单的代码来使用tkinter可视化一些数据.按钮单击绑定到重绘下一个"数据帧"的函数.但是,我想选择以特定频率自动重绘.在GUI编程方面我非常环保(我不需要为这段代码做很多事情),因此我的大多数tkinter知识来自跟随和修改示例.我想我可以使用root.after来实现这一点,但我不太清楚我是否理解其他代码.我的程序的基本结构如下:

# 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()
Run Code Online (Sandbox Code Playgroud)

对于提出一个我肯定有一个明显而简单的答案的问题的道歉.非常感谢.

Bry*_*ley 12

使用Tkinter进行动画或周期性任务的基本模式是编写绘制单个帧或执行单个任务的函数.然后,使用类似的东西定期调用它:

def animate(self):
    self.draw_one_frame()
    self.after(100, self.animate)
Run Code Online (Sandbox Code Playgroud)

一旦调用此函数,它将继续以每秒十次的速度绘制帧 - 每100毫秒一次.如果您希望能够在动画启动后停止动画,则可以修改代码以检查标志.例如:

def animate(self):
    if not self.should_stop:
        self.draw_one_frame()
        self.after(100, self.animate)
Run Code Online (Sandbox Code Playgroud)

然后,您将有一个按钮,单击该按钮时将设置self.should_stopFalse

  • @rahultyagi:不,超出最大递归深度是不可能的,因为它不是递归函数.至少,不是字面意义上的.该函数不会调用自身,它只是安排自己在将来再次运行.堆栈深度永远不会超过1. (2认同)