2017-06-18 47 views
0

我希望這個腳本不起作用:GTK3和Python:爲什麼set_property延遲?

import gi 
import time 
gi.require_version('Gtk', '3.0') 
from gi.repository import Gtk 

class GridWindow(Gtk.Window): 

    def __init__(self): 
     Gtk.Window.__init__(self, title="hi") 

     def fnButton1(self): 
      button1.set_property("label", "TEST") 
      print("hello") 
      time.sleep(3) 
      print("you") 

     grid = Gtk.Grid() 

     button1 = Gtk.Button(label="Button 1") 
     button1.connect("clicked", fnButton1) 
     button2 = Gtk.Button(label="Button 2") 

     grid.add(button1) 
     grid.attach(button2, 1, 0, 1, 1) 
     self.add(grid) 

win = GridWindow() 
win.connect("delete-event", Gtk.main_quit) 
win.show_all() 
Gtk.main() 

當點擊按鈕1,它的標籤沒有改變,但「你好」被打印出來。這隻發生在3秒鐘之後:標籤變成「TEST」並且「你」被打印。當函數fnButton1()完成時,似乎屬性發生了變化,而不是在那之前。爲什麼?而且如何解決這個問題?

我只是想在一些函數的開始處更改一些小部件屬性,它以按鈕單擊開始。編程時這會很正常,不是嗎?爲什麼GTK3(使用Python)的行爲有所不同?

+0

可能重複的[Gtk小部件顯示與延遲](https://stackoverflow.com/questions/24272293/gtk-widget-shows-up-with-delay) –

回答

1
def fnButton1(self): 
     button1.set_property("label", "TEST") 
     print("hello") 
     time.sleep(3) 
     print("you") 

set_property創建繪製這些排隊進入後臺進程的命令,當基於GTK的事件循環「有時間」做它的迭代將被執行。 sleep命令有效地阻止事件循環執行3秒。然而,打印命令會立即執行。您可以看到,在此期間將另一個窗口移至現有窗口時,窗口內容可能不會更新。

如果你真的需要sleep你應該尋找的幾種方法不會阻塞事件循環延遲一個(像從GLib的add_timeout,例如)

通常,使用sleep或塊的任何功能事件循環在諸如大多數圖形窗口系統的事件驅動系統中是一個壞主意。