How do you run your own code alongside Tkinter#39;s event loop?(你如何在 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."""
这篇关于你如何在 Tkinter 的事件循环中运行你自己的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:你如何在 Tkinter 的事件循环中运行你自己的代码?


基础教程推荐
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01