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

查看:36
本文介绍了使用 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天全站免登陆