2017-08-26 72 views
1

我有一个问题,我想让Gtk.Switch启动和停止一个功能。只要开关处于活动状态,此功能就会工作。例如,只要开关处于活动状态,就可以打印“功能处于打开状态”。Python使用Gtk开关启动和停止连续功能

但是,除非我线程这个功能它会冻结GUI,它不可能停止它。

### Gtk Gui ### 
self.sw = Gtk.Switch() 

self.sw.connect("notify::active", 
       self.on_sw_activated) 
### Gtk Gui ### 

### Function ### 
def on_sw_activated(self, switch, gparam): 

    if switch.get_active(): 
     state = "on" 
    else: 
     state = "off" 

    ### This needs to be "threaded" as to not freeze GUI 
    while state == "on": 
     print("Function is on") 
     time.sleep(2) 
    else: 
     print("Function is off") 

### Function ### 

据我知道有没有好办法阻止Python中的线程,我的问题是,如果没有实施这一不使用python线程的另一种方式。

+0

你的回调睡眠将冻结主循环和作为结果的UI冻结。如果你的“函数”不是一个耗时的任务,也许你可以与idle_add或timeout_add相处,否则你将需要线程。 –

回答

3

试试这个代码:

#!/usr/bin/env python 

import gi 
gi.require_version ('Gtk', '3.0') 
from gi.repository import Gtk, GdkPixbuf, Gdk, GLib 
import os, sys, time 

class GUI: 
    def __init__(self): 

     window = Gtk.Window() 
     self.switch = Gtk.Switch() 
     window.add(self.switch) 
     window.show_all() 

     self.switch.connect('state-set', self.switch_activate) 
     window.connect('destroy', self.on_window_destroy) 

    def on_window_destroy(self, window): 
     Gtk.main_quit() 

    def switch_activate (self, switch, boolean): 
     if switch.get_active() == True: 
      GLib.timeout_add(200, self.switch_loop) 

    def switch_loop(self): 
     print time.time() 
     return self.switch.get_active() #return True to loop; False to stop 

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

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