使用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()
很抱歉提出一个问题,我相信这个问题显而易见且简单。非常感谢。
问题答案:
使用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