交替开关是ON / OFF?

时间:2018-04-25 23:41:24

标签: python python-3.x pygtk gtk3

所以我希望我的小型Python Gtk窗口有2个开关。当一个开关打开时,另一个开关关闭,反之亦然。我不太确定如何控制两个开关。如果有人能引导我朝着正确的方向前进,那就非常感激。

#!/usr/bin/python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk

class SwitcherWindow(Gtk.Window):

def __init__(self):
    Gtk.Window.__init__(self, title="Alt Switch Demo")
    self.set_border_width(10)

    hbox = Gtk.Box(spacing=10)
    self.add(hbox)

    switch1 = Gtk.Switch()
    switch1.connect("notify::active", self.on_switch_activated)
    switch1.set_active(True)
    hbox.pack_start(switch1, True, True, 0)

    switch2 = Gtk.Switch()
    switch2.connect("notify::active", self.on_switch_activated)
    switch2.set_active(False)
    hbox.pack_start(switch2, True, True, 0)

    if switch1.get_active():
        switch2.set_active(False)
    else:
        switch2.set_active(True)

def on_switch_activated(self, switch, gparam):
    builder = Gtk.Builder()
    sw1 = builder.get_object("switch1")
    sw2 = builder.get_object("switch2")
    if switch.get_active():
        state = "on"
        sw2.set_active(False)
    else:
        state = "off"
        print("Switch was turned", state)

win = SwitcherWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

3 个答案:

答案 0 :(得分:1)

我会bind the properties两个开关,在创建时反转和同步:

#!/usr/bin/python3

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject 

class SwitcherWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Alt Switch Demo")
        self.set_border_width(10)

        hbox = Gtk.Box(spacing=10)
        self.add(hbox)

        switch1 = Gtk.Switch()
        switch1.set_active(True)
        hbox.pack_start(switch1, True, True, 0)

        switch2 = Gtk.Switch()
        switch2.set_active(False)
        hbox.pack_start(switch2, True, True, 0)

        switch1.bind_property("active", switch2, "active", GObject.BindingFlags.BIDIRECTIONAL | GObject.BindingFlags.SYNC_CREATE |  GObject.BindingFlags.INVERT_BOOLEAN)   


win = SwitcherWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()

解决方案位于以下代码行中:

switch1.bind_property("active", switch2, "active", GObject.BindingFlags.BIDIRECTIONAL | GObject.BindingFlags.SYNC_CREATE |  GObject.BindingFlags.INVERT_BOOLEAN) 

"active" switch1 switch2 -- ProjectA |-- code |__ module1.py |__ __init__.py | |-- dags |__ crawler.py # Contains the bash operator to run a python module |__ __init__.py | |-- jobs |__ python_module.py # Contains a function that makes call to module1.py (contains the code to crawl websites) present inside Code package |__ __init__.py | |-- logs | |-- __init__.py and other Airflow files 属性from datetime import datetime, timedelta from airflow import DAG from airflow.operators.bash_operator import BashOperator default_args = { 'owner': 'Sam', 'depends_on_past': False, 'start_date': datetime(2018, 4, 26), 'email': ['airflow@airflow.com'], 'email_on_failure': False, 'email_on_retry': False, 'retries': 1, 'retry_delay': timedelta(minutes=2) } dag = DAG('dump_aerial_image', default_args=default_args) t1 = BashOperator( task_id='AerialDUMP', bash_command='python /Users/sam/App/ProjectA/jobs/python_module.py', dag=dag ) ImportError: No module named 'code.module1'; 'code' is not a package [2018-04-25 18:45:07,699] {base_task_runner.py:98} INFO - Subtask: [2018-04-25 18:45:07,698] {bash_operator.py:105} INFO - Command exited with return code 1 [2018-04-25 18:45:07,707] {models.py:1595} ERROR - Bash command failed Traceback (most recent call last): File "/Users/sam/App-Setup/anaconda/envs/anaconda35/lib/python3.5/site- packages/airflow/models.py", line 1493, in _run_raw_task result = task_copy.execute(context=context) File "/Users/sam/App-Setup/anaconda/envs/anaconda35/lib/python3.5/site-packages/airflow/operators/bash_operator.py", line 109, in execute raise AirflowException("Bash command failed") airflow.exceptions.AirflowException: Bash command failed bind binding flagsbidirectionalsync on create { {3}}

答案 1 :(得分:0)

你可以实现与我写的类似的逻辑:

#!/usr/bin/env python


class Switch:
    _State = False

    def __init__(self, StartingPosition=False):
        self._State = StartingPosition

    def SwitchON(self):
        self._State = True

    def SwitchOFF(self):
        self._State = False

    def Switch(self):
        self._State = not self._State

    def GetInfo(self):
        print(self._State)


class Switcher:
    def __init__(self, switchDependencyList=[]):
        self.SwitchDependencyList = switchDependencyList
        if len(self.SwitchDependencyList) == 0:
            return None
        if not len(self.SwitchDependencyList) % 2:
            return None

    def SwitchByIndex(self, Index):
        for i, switch in enumerate(self.SwitchDependencyList):
            if i == Index:
                switch.SwitchON()
            else:
                switch.SwitchOFF()

    def GetInfo(self):
        for switch in self.SwitchDependencyList:
            switch.GetInfo()


sw1 = Switch()
sw2 = Switch()
SwitcherModule = Switcher([sw1, sw2])
SwitcherModule.SwitchByIndex(1)
SwitcherModule.GetInfo()

答案 2 :(得分:0)

不需要像预先列出的答案那样复杂的东西。 gtk已经有了一个radiobutton小部件,可以为你完成所有工作。唯一的事情是,当它被初始化时你没有设置按钮,所以你必须选择一个来设置。