gpt4 book ai didi

python - 你如何在 Tkinter 的事件循环中运行你自己的代码?

转载 作者:IT老高 更新时间:2023-10-28 21:06:26 28 4
gpt4 key购买 nike

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

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

有没有办法让他的代码在主循环旁边运行(没有多线程,这很困惑,应该保持简单),如果有,它是什么?

现在,他想出了一个丑陋的技巧,将他的 move()函数到 <b1-motion> ,所以只要他按住按钮并摆动鼠标,它就可以工作。但一定有更好的方法。

最佳答案

Tk 对象上使用 after 方法:

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 方法的声明和文档:

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."""

关于python - 你如何在 Tkinter 的事件循环中运行你自己的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/459083/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com