1

I have a issue where I want a Gtk.Switch to start and stop a function. This function should work as long as the switch is active. For example it could just print "Function is on" as long as switch is active.

But unless I thread this function it will freeze GUI and it won't be possible to stop it.

### 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 ###

As far as I know there is no good way to stop a thread in python, my question is if there is another way of implementing this without using python threads.

  • Your sleep on the callback will freeze the mainloop and as a consequence the ui freezes. If your "function" isnt a time consuming task maybe u can get along with idle_add or timeout_add otherwise you will need threads. – José Fonte Aug 27 '17 at 12:35

1 Answers1

2

Try this code:

#!/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())
theGtknerd
  • 3,647
  • 1
  • 13
  • 34