PyGtk3,切换按钮,“切换”偶数

2024-09-30 22:13:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道“切换或未切换”事件不存在,但我需要使用这样的事件。当按钮处于“切换”和“未切换”状态时,是否存在要执行任务的事件。我不想使用“clicked”事件,因为ToggleButton可以在没有单击的情况下被切换或不被切换 谢谢

示例

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

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

Tags: obj示例iffoo状态def事件情况
2条回答

下面是一个简短的GTK2+/PyGTK演示;如果需要,它应该很容易适应GTK3。在

GUI包含一个切换按钮和一个普通按钮。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()

典型输出

^{pr2}$

根据the docs-

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

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

相关问题 更多 >