0

我有 10 个按钮,对应于相同的方法。我将如何检查在相应方法中单击了哪个按钮?我试图通过以下代码检查列表中特定按钮的按钮按下,但出现分段错误错误:

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

2 回答 2

3

下面是一个示例代码,说明了通过使用按钮的标签知道是哪个按钮触发了事件:

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()

所以你可以检查标签是什么并采取相应的行动。

于 2012-11-06T23:07:54.903 回答
0

将所有按钮连接到同一个回调后,我假设回调将具有以下签名:发出信号的按钮callback(button)在哪里。buttonclicked

在该回调内部应该很容易使用以下内容检查单击了哪个按钮:

button_list.index(button)

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

于 2012-01-10T19:32:35.013 回答