gpt4 book ai didi

python - 交替开关开/关?

转载 作者:行者123 更新时间:2023-12-01 09:30:15 26 4
gpt4 key购买 nike

所以我想让我的 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()

最佳答案

我会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) 

给你bind switch1switch2"active" 属性以及 binding flags : bidirectional , sync on createinvert boolean

关于python - 交替开关开/关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50032779/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com