简体   繁体   中英

How do I add additional arguments to button.connect in PyGTK?

I want to pass 2 ComboBox instances to aa method and use them there (eg, print their active selection). I have something similar to the following:

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.

How can I pass combobox1 and combobox2 to the method "comboprint", so that I can use them there? Is making them class fields (self.combobox1, self.combobox2) the only way to do this?

do something like this:

btn_new.connect("clicked", self.comboprint, combobox1, combobox2)

and in your callback comboprint it should be something like this:

def comboprint(self, widget, *data):
    # Widget = btn_new
    # data = [clicked_event, combobox1, combobox2]
    ...  

I would solve this another way, by making combobox1 and combobox2 class variables, like this:

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

This has the advantage that when another function needs to do something with those comboboxes, that they can do that, without you having to pass the comboboxes as parameters to every function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM