PyGtk3,切换按钮,"toggled-or-untoggled" 事件

PyGtk3, ToggleButton, "toggled-or-untoggled" event

我知道 "toggled-or-untoggled" 事件不存在,但我需要使用这样的事件。当按钮为 "toggled" 和 "untoggled" 时,是否有事件要执行任务。我不想使用 "clicked" 事件,因为无需单击即可切换或取消切换 ToggleButton 谢谢

例子

def foo(obj):
    if obj.get_active():
        print("toggled")
    else:
        print("untoggled")

mybtn = gtk.ToggleButton()
mybtn.connect("toggled-or-untoggled", foo)

根据the docs-

When the state of the button is changed, the “toggled” signal is emitted.

因此,理想情况下,mybtn.connect("toggled", foo) 应该可行。

这是一个简短的 GTK2+ / PyGTK 演示;如有必要,适应 GTK3 应该很容易。

GUI 包含一个 ToggleButton 和一个普通按钮。 ToggleButton 的回调仅在按钮被切换时打印按钮的状态,无论是通过用户单击它还是通过其他代码调用其 set_active 方法。单击普通按钮时会打印一条消息,它还会切换 ToggleButton。

#!/usr/bin/env python2

from __future__ import print_function
import pygtk
pygtk.require('2.0')
import gtk

class Test(object):
    def __init__(self):
        win = gtk.Window(gtk.WINDOW_TOPLEVEL)
        win.connect("destroy", lambda w: gtk.main_quit())

        box = gtk.HBox()
        box.show()
        win.add(box)

        self.togglebutton = button = gtk.ToggleButton('toggle')
        button.connect("toggled", self.togglebutton_cb)
        box.pack_start(button, expand=True, fill=False)
        button.show()

        button = gtk.Button('plain')
        button.connect("clicked", self.button_cb)
        box.pack_start(button, expand=True, fill=True)
        button.show()

        win.show()
        gtk.main()

    def button_cb(self, widget):
        s = "%s button pressed" % widget.get_label()
        print(s)
        print('Toggling...')
        tb = self.togglebutton
        state = tb.get_active()
        tb.set_active(not state)

    def togglebutton_cb(self, widget):
        state = widget.get_active()
        s = "%s button toggled to %s" % (widget.get_label(), ("off", "on")[state])
        print(s)

Test()

典型输出

toggle button toggled to on
toggle button toggled to off
plain button pressed
Toggling...
toggle button toggled to on
plain button pressed
Toggling...
toggle button toggled to off
plain button pressed
Toggling...
toggle button toggled to on
toggle button toggled to off