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

发布于 2021-02-02 23:23:04

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

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

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

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

关注者
0
被浏览
188
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看