你如何在 Tkinter 的事件循环旁边运行你自己的代码? [英] How do you run your own code alongside Tkinter's event loop?

查看:27
本文介绍了你如何在 Tkinter 的事件循环旁边运行你自己的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的弟弟刚刚开始​​编程,在他的 Science Fair 项目中,他正在模拟天空中的一群鸟.他已经编写了大部分代码,并且运行良好,但是小鸟需要每时每刻移动.

My little brother is just getting into programming, and for his Science Fair project, he's doing a simulation of a flock of birds in the sky. He's gotten most of his code written, and it works nicely, but the birds need to move every moment.

然而,Tkinter 会为自己的事件循环占用时间,因此他的代码无法运行.做 root.mainloop() 运行,运行,一直运行,它运行的唯一的东西就是事件处理程序.

Tkinter, however, hogs the time for its own event loop, and so his code won't run. Doing root.mainloop() runs, runs, and keeps running, and the only thing it runs is the event handlers.

有没有办法让他的代码与主循环一起运行(没有多线程,这很混乱,这应该保持简单),如果是,那是什么?

Is there a way to have his code run alongside the mainloop (without multithreading, it's confusing and this should be kept simple), and if so, what is it?

现在,他想出了一个丑陋的黑客,将他的 move() 函数绑定到 ,这样只要他持有按下按钮并摆动鼠标,它起作用了.但一定有更好的方法.

Right now, he came up with an ugly hack, tying his move() function to <b1-motion>, so that as long as he holds the button down and wiggles the mouse, it works. But there's got to be a better way.

推荐答案

Tk 对象上使用 after 方法:

Use the after method on the Tk object:

from tkinter import *

root = Tk()

def task():
    print("hello")
    root.after(2000, task)  # reschedule event in 2 seconds

root.after(2000, task)
root.mainloop()

以下是 after 方法的声明和文档:

Here's the declaration and documentation for the after method:

def after(self, ms, func=None, *args):
    """Call function once after given time.

    MS specifies the time in milliseconds. FUNC gives the
    function which shall be called. Additional parameters
    are given as parameters to the function call.  Return
    identifier to cancel scheduling with after_cancel."""

这篇关于你如何在 Tkinter 的事件循环旁边运行你自己的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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