当回调时间过长时,如何使 PyGTK 小部件快速响应?

发布于 2024-11-17 11:06:25 字数 288 浏览 1 评论 0原文

我在_init回调函数中做了一个耗时的处理。因此,在 GUI 上,当我激活复选按钮时,程序会冻结,而处理运行完成,然后出现复选标记并正常恢复执行。

self.init = gtk.CheckButton("Init", False)
self.init.connect("toggled", self._init)

def _init(self, w):
....

如何在处理过程中使 GUI 的响应速度更快?

有没有办法让 GUI 在开始时改变复选框的状态,然后进入重循环?

I do a time-consuming processing in the _init callback function. Therefore, at the GUI, when I activate the check-button, the program freezes, while the processing runs to completion, and then the check mark appears and execution resumes normally.

self.init = gtk.CheckButton("Init", False)
self.init.connect("toggled", self._init)

def _init(self, w):
....

How do I make the GUI more responsive while the processing takes place ?

And is there a way I can make the GUI change the state of the check-box right in the beginning and then enter the heavy loop ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

面犯桃花 2024-11-24 11:06:25

您有几种解决方案:

  1. 在工作线程中进行计算,这会将结果发送到主线程。但不要在工作线程中更改 GUI 项目。与大多数工具包一样,GTK 不是线程安全的。我不太喜欢那个,因为我不太喜欢线程,因为它们往往会使调试变得更加困难......
  2. 将处理拆分为空闲句柄。当我说拆分时,我真正的意思是将其拆分为几个步骤,从而减少计算时间。您应该使用具有多个状态的自动机,每个状态花费的时间要少得多。将大量微积分放入空闲处理程序中就像在该处理程序中调用 sleep(5) 一样:GUI 消息泵将被阻塞 5 秒,无法处理重绘事件...这是一个 延迟加载数据示例使用这种技术。
  3. 使用 gtk_main_iteration 强制定期调用消息泵

我给你的例子是C语言的,但Python的精神是一样的。

You have several solutions:

  1. Make the computation in a worker thread, which will send the result to the main thread. But don't change GUI items in the worker thread. Like most toolkits, GTK is not thread safe. I don't really like that one, as I don't really like threads, as they tend to make debugging harder...
  2. Split the processing in an idle handle. When I say split, I really mean to split it in several steps that take much less time to compute. You should use an automaton with several states taking each much less time. Putting a big fat calculus in an idle handler is like calling sleep(5) in that handler: the GUI message pump would be blocked for 5 seconds, with no way to handle redrawing events... Here's an example of lazy loading data using this technique.
  3. Force a call to the message pump on a regular basis using gtk_main_iteration.

The examples I gave you are in C, but the spirit is the same in python.

朮生 2024-11-24 11:06:25

在处理程序中,将 init 的其余部分注册为空闲处理程序并返回。 gtk.idle_add IIRC。这样它将在处理 gui 事件后运行。检查文档以了解需要返回哪个值,以便该函数不会再次启动。

In the handler, register the rest of the init as idle-handler and return. gtk.idle_add IIRC. That way it will run after the gui events are handled. Check documentation to see which value you need to return so the function is not started again.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文