如何在PyGTK中向button.connect添加额外参数?
我想把两个下拉框(ComboBox)传递给一个方法,然后在这个方法里使用它们(比如,打印出它们当前选中的内容)。我有类似下面的代码:
class GUI():
...
def gui(self):
...
combobox1 = gtk.combo_box_new_text()
# code for inserting some values into the combobox
combobox2 = gtk.combo_box_new_text()
# code for inserting some values into the combobox
btn_new = gtk.Button("new")
btn_new.connect("clicked", self.comboprint)
def comboprint(self):
# do something with the comboboxes - print what is selected, etc.
我该怎么把combobox1和combobox2传给名为“comboprint”的方法,这样我就可以在里面使用它们?把它们变成类的字段(self.combobox1, self.combobox2)是唯一的办法吗?
2 个回答
1
我会用另一种方法来解决这个问题,把 combobox1 和 combobox2 设为类的变量,像这样:
class GUI():
...
def gui(self):
...
self.combobox1 = gtk.combo_box_new_text()
# code for inserting some values into the combobox
self.combobox2 = gtk.combo_box_new_text()
# code for inserting some values into the combobox
btn_new = gtk.Button("new")
btn_new.connect("clicked", self.comboprint)
def comboprint(self):
# do something with the comboboxes - print what is selected, etc.
self.combobox1.do_something
这样做的好处是,当其他函数需要使用这些下拉框时,它们可以直接使用,不需要你每次都把下拉框作为参数传递给每个函数。
11
可以这样做:
btn_new.connect("clicked", self.comboprint, combobox1, combobox2)
然后在你的回调函数 comboprint
中,应该像这样:
def comboprint(self, widget, *data):
# Widget = btn_new
# data = [clicked_event, combobox1, combobox2]
...