销毁按钮的旧回调并安装新的回调

时间:2015-08-28 00:37:37

标签: python button callback gtk pygobject

我为完成按钮上的点击信号安装了两个回调。有没有办法取出(不执行)其中一个,例如

import threading
import time
from gi.repository import Gtk, GLib

class Test():
    def __init__(self):

        win = Gtk.Window()
        win.set_title("XYZ")

        win.set_border_width(10)

        box = Gtk.VBox(spacing=10)
        win.add(box)
        done_button = Gtk.Button(label="DONE")
        done_button.connect("clicked", self.callback1)

        #remove callback ??? callback1 should not be called when button is clicked.

        done_button.connect("clicked", self.callback2)

        box.pack_end(done_button, False, False, 0)

        win.show_all()
        win.maximize()
        win.connect("delete-event", Gtk.main_quit)

    def callback1(self, widget):
        print "callback1"

    def callback2(self, widget):
        print "callback2"


if __name__ == '__main__':
    test = Test()
    Gtk.main()

如何删除callback1。

2 个答案:

答案 0 :(得分:2)

您需要获取信号的ID才能断开连接,因此请将连接更改为:

b_id = done_button.connect("clicked", self.callback1)

然后使用GObject模块的disconnect函数:

GObject.signal_handler_disconnect(done_button, b_id)

或者elya5建议(所以你甚至不必导入GObject):

done_button.disconnect(b_id)

请记住首先导入GObject模块(不是GLib)

from gi.repository import Gtk, GObject

答案 1 :(得分:0)

请参阅python-gtk-3-tutorial.readthedocs.io

如果由于某种原因丢失了“ handler_id”(例如,使用Gtk.Builder.connect_signals()安装了处理程序),您仍然可以使用函数connect_by_func()断开特定的回调:

widget.disconnect_by_func(callback)