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

2024-05-16 13:05:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我弟弟刚刚开始编程,为了他的科学展览项目,他正在模拟天空中的一群鸟。他已经编写了大部分代码,而且运行得很好,但是鸟儿需要随时移动。

然而,Tkinter占用了自己事件循环的时间,所以他的代码不会运行。执行root.mainloop()运行、运行并保持运行,它运行的唯一东西是事件处理程序。

有没有办法让他的代码与主循环一起运行(没有多线程,这很混乱,应该保持简单),如果有,是什么?

现在,他想出了一个难看的方法,将他的move()函数绑定到<b1-motion>,这样只要他按住按钮并晃动鼠标,它就可以工作。但一定有更好的办法。


Tags: 项目方法代码处理程序tkinter编程时间事件
3条回答

在编写您自己的循环时,就像在模拟中一样(我假设),您需要调用update函数来执行mainloop所做的操作:用您的更改更新窗口,但您是在循环中执行的。

def task():
   # do something
   root.update()

while 1:
   task()  

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

solution posted by Bjorn在我的计算机上导致“RuntimeError:Calling Tcl from different appartment”消息(RedHat Enterprise 5,python 2.6.1)。Bjorn可能没有收到此消息,因为根据one place I checked,使用Tkinter错误处理线程是不可预测的,并且依赖于平台。

问题似乎是app.start()算作对Tk的引用,因为app包含Tk元素。我通过在__init__内部用self.start()替换app.start()来解决这个问题。我还使所有的Tk引用要么在调用mainloop()函数中,要么在调用mainloop()的函数调用的函数中(这显然对于避免“不同单元”错误非常重要)。

最后,我添加了一个带有回调的协议处理程序,因为如果没有回调,当用户关闭Tk窗口时,程序将以错误退出。

修订后的准则如下:

# Run tkinter code in another thread

import tkinter as tk
import threading

class App(threading.Thread):

    def __init__(self):
        threading.Thread.__init__(self)
        self.start()

    def callback(self):
        self.root.quit()

    def run(self):
        self.root = tk.Tk()
        self.root.protocol("WM_DELETE_WINDOW", self.callback)

        label = tk.Label(self.root, text="Hello World")
        label.pack()

        self.root.mainloop()


app = App()
print('Now we can continue running code while mainloop runs!')

for i in range(100000):
    print(i)

相关问题 更多 >