程序的主循环可以移出GUI吗?
如果重要的话,我正在使用 python 3 / tkinter 。
在查看代码示例时,我注意到主循环通常位于代码的 GUI 部分,其余代码提供回调供 GUI 在需要时调用。
但我的模拟运行独立于用户交互; UI 可以时不时地提供模拟中发生的情况的视图,但它不能控制模拟中发生的情况。所以我希望主循环关注模拟而不是 UI。我该怎么做呢?
I'm using python 3 / tkinter if that matters.
In looking at code samples I noticed that the main loop is typically in the GUI part of the code, and the rest of the code provides callbacks for GUI to call when needed.
But my simulation runs independently of the user interaction; the UI is there to provide a view, from time to time, into what's going on in the simulation, but it doesn't control what goes on in the simulation. So I would like the main loop to be concerned with the simulation rather than UI. How would I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
为什么不把你的逻辑和表达分开呢?编写你的 sim 后端来响应基于单个文本的协议来接收命令并发送回结果,然后只需通过你的 gui 程序通过 unix 套接字与它对话。
Why not seperate your logic and presentation. Write your sim backend to respond to a single text based protcol to receive cmds and send back results, and then just talk to it from your gui program over e.g. unix sockets.
编写您自己的主循环来调用检查和处理 GUI 事件的函数。
Write your own main loop that calls the functions that check for and process GUI events.
在这种情况下,您应该在单独的线程中执行处理,然后让 GUI 线程向该线程发送和接收消息。
但是,不要尝试直接从处理线程更新 GUI。相反,您可以使用消息队列向 GUI 发送消息,类似于 effbot 的示例 。重要的是
queue.get_nowait()
:如果队列中没有任何内容,您可以在 GUI 中定期运行它,而不会阻塞其他线程。In this case, you should perform your processing in a separate thread, and then have the GUI thread send and receive messages to that thread.
However, do not try to directly update the GUI from the processing thread. Instead, you can send a message to the GUI using a message queue, similar to effbot's example. The important thing is
queue.get_nowait()
: you can just periodically run this in your GUI without blocking other threads if there is nothing in the queue.