2017-07-05 30 views
0

我有一個運行循環並相應地更新窗口的按鈕。我想要另一個「暫停」按鈕來暫停這個循環,但似乎並不像循環運行時那樣。也許線程是解決方案(我嘗試了GLib.timeout_add_seconds而沒有成功) - 使這項工作最簡單的方法是什麼? 我重視我的錯誤代碼:如何用PyGObject中的按鈕暫停循環?

import sys 
from time import sleep 
import gi 
gi.require_version("Gtk", "3.0") 
from gi.repository import Gtk 

class LoopButton(Gtk.Box): 

    def __init__(self, GUI): 
     Gtk.Box.__init__(self) 

     self.GUI = GUI 
     self.set_border_width(10) 
     self.message = "1" 

     button = Gtk.Button.new_with_label("Run") 
     button.connect("clicked", self.on_click) 
     self.pack_start(button, True, True, 0) 

    def on_click(self, widget): 
     msg = int(self.message) 
     while self.GUI.is_paused == False: 
      self.GUI.restart_window(str(msg)) 
      msg += 1 
      while Gtk.events_pending(): 
       Gtk.main_iteration() 
      sleep(1) 
     self.GUI.is_paused = True 

class PauseButton(Gtk.Box): 
    def __init__(self, GUI): 
     Gtk.Box.__init__(self) 

     self.GUI = GUI 
     self.set_border_width(10) 

     button = Gtk.Button.new_with_label("Pause") 
     button.connect("clicked", self.on_click) 
     self.pack_start(button, True, True, 0) 

    def on_click(self, widget): 
     self.GUI.is_paused = True 


class GUI: 

    def __init__(self): 
     self.is_paused = False 
     self.win = Gtk.Window() 
     self.window_grid = Gtk.Grid() 
     self.box = Gtk.Box(spacing=10) 
     self.label = Gtk.Label("Default label") 
     self.win.connect("delete-event", Gtk.main_quit) 
     self.start_window() 

    def start_window(self): 
     self.box.pack_start(LoopButton(self), True, True, 0) 
     self.box.pack_start(PauseButton(self), True, True, 0) 
     self.window_grid.add(self.box) 
     self.window_grid.add(self.label) 
     self.win.add(self.window_grid) 
     self.win.show_all() 

    def restart_window(self, label="Default label"): 
     self.window_grid.destroy() 
     self.window_grid = Gtk.Grid() 
     self.box = Gtk.Box(spacing=10) 
     self.label = Gtk.Label(label) 
     self.start_window() 

def main(): 
    app = GUI() 
    Gtk.main() 

if __name__ == "__main__": 
    sys.exit(main()) 
+0

這是因爲https://stackoverflow.com/questions/44916094/why-cant-i-have-a-loop-in-the-onclick-function-in-pygobject同樣的問題? – jku

+1

你的實際代碼將在循環中做什麼?答案依賴於此。 – andlabs

+0

@ jku不,它不是。這是非常相似的,我修改了代碼,但我問了如何暫停循環,其他問題沒有做的事情 –

回答

0

取決於你真正做循環可能會有更多必要的細節,但下面是如何循環中的GLib/GTK通常避免的例子。這種方法的注意事項是:A)一次迭代必須足夠快以至於不會影響UI更新(最多幾毫秒)。 B)時間不準確:超時功能在上次呼叫後2秒鐘可能不會被稱爲正好

import gi 
from gi.repository import GLib 

class GUI: 
    def __init__(self): 
     # initialize the UI here... 

     # setup updates every two seconds 
     GLib.timeout_add_seconds(2, self.timeout_update) 

    def timeout_update(self): 
     # update your widgets here 
     print ("Updating UI now...") 

     # yes, we want to be called again 
     return True 
+0

完美 - 現在起作用。我也想在使用之前使用timeout_add_seconds,但是我沒有返回True,這導致它無法正常運行。 –