2017-04-16 68 views
1

我知道“切换或非切换”事件不存在,但我需要使用这样的事件。当按钮被“切换”和“不动摇”时,是否有任务要做?我不想使用“点击”事件,因为切换按钮可以在不点击 感谢PyGtk3,ToggleButton,“切换或非切换”事件

例如

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

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

你的问题应该提到你正在使用的GTK版本。 –

回答

1

这是一个简短的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 
+0

非常感谢您的帮助。 – PyGtk3

2

根据the docs进行切换或untoggled -

当按钮的状态发生改变,“切换”信号为 。

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

+0

我已经知道这一点。我不是故意的 – PyGtk3

+1

噢好吧,然后请详细说明确切的要求。 –

+0

“切换”事件仅在小部件切换时运行,但在小部件未被切断时不运行。我想在窗口小部件切换并且不动时运行 – PyGtk3