同じ方法に対応する10個のボタンがあります。対応するメソッドでどのボタンがクリックされたかを確認するにはどうすればよいですか? 次のコードでリスト内の特定のボタンのボタン押下を確認しようとしましたが、セグメンテーション違反エラーが発生しました:
for i in range(0,10):
if button_list[i].clicked():
break
break
#operation with respect to the button clicked
ボタンのラベルを使用してイベントをトリガーしたボタンを知るサンプル コードを次に示します。
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()
したがって、ラベルが何であるかを確認し、それに応じて行動することができます.
すべてのボタンを同じコールバックに接続したら、コールバックに次の署名があると思います。callback(button)
ここで、はシグナルbutton
を発したボタンです。clicked
そのコールバック内では、次のようなものを使用して、どのボタンがクリックされたかを簡単に確認できるはずです。
button_list.index(button)
これにより、リスト内のボタンのインデックスが返されます。