1from gi.repository import Gtk 2import sys 3 4 5class MyWindow(Gtk.ApplicationWindow): 6 # a window 7 8 def __init__(self, app): 9 Gtk.Window.__init__(self, title="Switch Example", application=app) 10 self.set_default_size(300, 100) 11 self.set_border_width(10) 12 13 # a switch 14 switch = Gtk.Switch() 15 # turned on by default 16 switch.set_active(True) 17 # connect the signal notify::active emitted by the switch 18 # to the callback function activate_cb 19 switch.connect("notify::active", self.activate_cb) 20 21 # a label 22 label = Gtk.Label() 23 label.set_text("Title") 24 25 # a grid to allocate the widgets 26 grid = Gtk.Grid() 27 grid.set_column_spacing(10) 28 grid.attach(label, 0, 0, 1, 1) 29 grid.attach(switch, 1, 0, 1, 1) 30 31 # add the grid to the window 32 self.add(grid) 33 34 # Callback function. Since the signal is notify::active 35 # we need the argument 'active' 36 def activate_cb(self, button, active): 37 # if the button (i.e. the switch) is active, set the title 38 # of the window to "Switch Example" 39 if button.get_active(): 40 self.set_title("Switch Example") 41 # else, set it to "" (empty string) 42 else: 43 self.set_title("") 44 45 46class MyApplication(Gtk.Application): 47 48 def __init__(self): 49 Gtk.Application.__init__(self) 50 51 def do_activate(self): 52 win = MyWindow(self) 53 win.show_all() 54 55 def do_startup(self): 56 Gtk.Application.do_startup(self) 57 58app = MyApplication() 59exit_status = app.run(sys.argv) 60sys.exit(exit_status) 61