使用python检查按下哪个按钮gtk3

时间:2012-01-10 19:29:14

标签: python gtk3

我有10个按钮,对应相同的方法。我该怎么检查相应方法中点击了哪个按钮?我试图通过以下代码检查列表中特定按钮的按钮按下,但是我得到了分段错误错误:

for i in range(0,10):
    if button_list[i].clicked():
        break
 break
#operation with respect to the button clicked

2 个答案:

答案 0 :(得分:3)

Here's a sample code通过使用按钮标签说明知道哪个按钮触发了事件:

from gi.repository import Gtk

class ButtonWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Button Demo")
        self.set_border_width(10)

        hbox = Gtk.Box(spacing=6)
        self.add(hbox)

        #Lets create 10 buttons for this demo
        #You could create and set the label for 
        #each of the buttons one by one
        #but in this case we just create 10 
        #and call them Button0 to Button9
        for i in range(10):

            name = "Button{}".format(i)
            button = Gtk.Button(name)
            button.connect("clicked", self.on_button_clicked)
            hbox.pack_start(button, True, True, 0)


    def on_button_clicked(self, button):
        print button.get_label()

    def on_close_clicked(self, button):
        print "Closing application"
        Gtk.main_quit()

win = ButtonWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

因此,您只需检查标签是什么,并采取相应的行动。

答案 1 :(得分:0)

将所有按钮连接到同一个回调后,我认为回调将具有此签名:callback(button)其中button是发出clicked信号的按钮。

在回调内部应该很容易检查点击了哪个按钮:

button_list.index(button)

这将返回列表中按钮的索引。