Gtk小部件显示延迟 [英] Gtk widget shows up with delay
问题描述
使用python3和gi.repository,我想要一个带有Gtk.Button的Gtk.HeaderBar,只要点击它就可以被Gtk.Spinner取代。在计算之后,按钮应该再次出现。
Using python3 and gi.repository, I want to have a Gtk.HeaderBar with a Gtk.Button that is replaced by a Gtk.Spinner as soon as you click on it. After a calculation the button should appear again.
这是一个我认为应该如何运作的例子,但是Gtk.Spinner仅在之后显示在很短的时间内计算(在这个例子中是睡眠)。我怎样才能达到微调显示整个计算(或睡眠)?
Here is an example of how I think it should work but the Gtk.Spinner only shows up after the calculation (in this example sleep) for a very short time. How can I achieve that the spinner shows up for the whole calculation (or sleep)?
from gi.repository import Gtk
import time
class window:
def __init__(self):
self.w = Gtk.Window()
self.button = Gtk.Button('x')
self.button.connect('clicked', self.on_button_clicked)
self.spinner = Gtk.Spinner()
self.hb = Gtk.HeaderBar()
self.hb.props.show_close_button = True
self.hb.pack_start(self.button)
self.w.set_titlebar(self.hb)
self.w.connect('delete-event', Gtk.main_quit)
self.w.show_all()
def on_button_clicked(self, widget):
self.button.hide()
self.hb.pack_start(self.spinner)
self.spinner.show()
self.spinner.start()
time.sleep(5)
self.spinner.stop()
self.hb.remove(self.spinner)
self.button.show()
if __name__ == '__main__':
w = window()
Gtk.main()
推荐答案
GTK +是一个事件驱动的系统,其中主循环应该可以自由更新UI和需要时间的一切就像从文件中读取数据,建立网络连接,长时间计算)应该是异步的。
GTK+ is an event driven system where the mainloop should be left free to update the UI and everything that takes time (like reading from a file, making a network connection, long calculations) should happen asynchronously.
在你的情况下,这看起来像这样:
In your case this would look something like this:
def on_button_clicked(self, widget):
self.button.hide()
self.spinner.show()
self.spinner.start()
GLib.timeout_add_seconds (5, self.processing_finished)
def processing_finished(self):
self.spinner.stop()
self.spinner.hide()
self.button.show()
请注意,我删除了包并删除了调用:在 __ init __()
中执行。你也可以在这里使用gi.repository import GLib 来获得。
Note that I removed the pack and remove calls: do those in __init__()
. You'll want from gi.repository import GLib
in there as well.
这样主循环是免费的根据需要随时更新UI。如果你真的想使用像sleep()那样的阻塞调用,那么你需要在另一个线程中这样做,但我的建议是使用类似于 timeout_add_seconds()
电话。
This way the main loop is free to update the UI as often as it wants. If you really want to use a blocking call like sleep(), then you'll need to do that in another thread, but my suggestion is to use libraries that are asychronous like that timeout_add_seconds()
call.
这篇关于Gtk小部件显示延迟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!