Python 使用 Gtk Switch 启动和停止连续功能

Python Start & stop a continous function with Gtk Switch

我有一个问题,我想要一个 Gtk.Switch 来启动和停止一个功能。只要开关处于活动状态,此功能就应该起作用。例如,只要开关处于活动状态,它就可以打印 "Function is on"。

但是,除非我将此函数线程化,否则它将冻结 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 线程的实现方式。

试试这个代码:

#!/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())