你如何在 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?
现在,他想出了一个丑陋的 hack,将他的 move()
函数绑定到 <b1-motion>
,这样只要他持有按下按钮并摆动鼠标,它可以工作.但一定有更好的方法.
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."""
相关文章