这是一个简短的GTK2 +/PyGTK演示;如果有必要,应该很容易适应GTK3。
GUI包含一个ToggleButton和一个普通的Button。 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
你的问题应该提到你正在使用的GTK版本。 –