使用tkinter的简单动画 [英] simple animation using tkinter

查看:232
本文介绍了使用tkinter的简单动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的代码,可以使用tkinter可视化某些数据。单击按钮绑定到重新绘制下一个帧数据的功能。但是,我想选择以一定的频率自动重绘。关于GUI编程,我非常环保(我不需要为此代码做很多事情),因此我的tkinter知识大部分来自于跟踪和修改示例。我想我可以使用root.after来实现这一点,但是我不确定我是否能从其他代码中了解到。我程序的基本结构如下:

I have a simple code to visualise some data using tkinter. A button click is bound to the function that redraws the next "frame" of data. However, I'd like to have the option to redraw automatically with a certain frequency. I'm very green when it comes to GUI programming (I don't have to do a lot for this code), so most of my tkinter knowledge comes from following and modifying examples. I guess I can use root.after to achieve this, but I'm not quite sure 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 a question which I'm sure has an obvious and simple answer. Many thanks.

推荐答案

使用Tkinter进行动画或定期任务的基本模式是编写一个绘制单个帧或执行一个任务。然后,定期使用这样的名称进行调用:

The basic pattern for doing animation or periodic tasks with Tkinter is to write a function that draws a single frame or performs a single task. Then, use something like this to call it at regular intervals:

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

调用此函数一次,它将继续以每秒10个的速度绘制帧-每100毫秒一次。如果希望动画一旦开始就可以停止,则可以修改代码以检查标志。例如:

Once you call this function once, it will continue to draw frames at a rate of ten per second -- once every 100 milliseconds. You can modify the code to check for a flag if you want to be able to stop the animation once it has started. For example:

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

然后您将有一个按钮,单击后将 self.should_stop 设置为 False

You would then have a button that, when clicked, sets self.should_stop to False

这篇关于使用tkinter的简单动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆