小编典典

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

python

对于他的Science Fair项目,他正在模拟天空中一群鸟。他得到了大部分他写的代码,它工作得很好,但鸟儿需要移动的每一刻。

然而,Tkinter浪费了自己的事件循环的时间,因此他的代码无法运行。这样root.mainloop()运行,运行,并保持运行,并且它运行的唯一事情是事件处理程序。

有没有一种方法可以让他的代码与mainloop一起运行(没有多线程,这很令人困惑,应该保持简单),如果这样,那是什么?

现在,他想出了一个丑陋的方法,将其move()功能绑定到<b1-motion>,这样,只要按住按钮并摇动鼠标,它就可以工作。但是必须有一个更好的方法。


阅读 1357

收藏
2020-02-09

共1个答案

小编典典

afterTk对象上使用方法:

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."""
2020-02-09