如何从单独的类配置 Tkinter 小部件?
我正在编写一个需要循环的 Tkinter 程序。我无法从 Tkinter 所在的同一个类中运行循环,我对此相当确定。要运行所述循环,我相信我必须使用单独的线程,因此是单独的类,以防止 Tkinter 冻结。我已经让 Tkinter 运行,同时线程中的循环打印数字。但是,我需要让它配置驻留在另一个类中的 Tkinter 窗口。我该怎么办呢?
I am writing a Tkinter program that requires a loop. I can't run the loop from the same class that Tkinter is in, I'm fairly certain of that much. To run said loop, I believe that I have to use a separate thread, therefore a separate class, to keep Tkinter from freezing. I have gotten Tkinter to run while a loop in the thread prints numbers. However, I need to have it configure a Tkinter window that resides in another class. How would I go about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不一定需要另一个线程,因为您不一定需要创建循环(请参阅 我对您有关使用嵌套循环的其他问题的回答)。
但是,要回答您的具体问题,您必须实现一个队列。工作线程会将某种类型的消息放入队列中,主线程通过事件循环轮询队列并响应消息。这是必要的,因为工作线程不能直接修改 tk 小部件。
有关通过 Tkinter 使用线程和队列的示例,请参阅 effbot 上的 Tkinter 和线程。球体。请密切注意它如何使用
after
每 100 毫秒轮询一次队列。You don't necessarily need another thread, because you don't necessarily need to create a loop (see my answer to your other question about using a nested loop).
However, to answer your specific question, you have to implement a queue. The worker thread will place messages of some sort on the queue, and the main thread polls the queue via the event loop and responds to the message. This is necessary because a worker thread can't directly modify tk widgets.
For an example of using threads and queues with Tkinter, see Tkinter and Threads on effbot.orb. Pay close attention to how it uses
after
to poll the queue every 100 ms.