[pygtk] Button connect() execution
Radomir Dopieralski
pygtk at sheep.art.pl
Wed Oct 25 06:57:15 WST 2006
Dnia Tue, Oct 24, 2006 at 06:30:36PM -0400, napisale(a)s:
> Hi Everyone,
>
> Let's say I have the following code:
>
> OkButton.connect("clicked", self.ButtonFunction,ComboBox.get_active_text
> ())
> **
> I assumed the function ComboBox.get_active_text() is determined after the
> button was clicked. Instead the function get_active_text() seems to be
> executed at run-time. The value of get_active_text() determined at run-time
> is used for the connect variable even if the active text in the ComboBox has
> changed.
>
> So let's say the ComboBox has the following Values:
>
> AAAAA
> BBBBB
>
> Initially, AAAAA is selected. If the user selects BBBBB and then presses
> the OkButtton, the function ButtonFunction is sent the value AAAAA and not
> BBBBB.
>
> Anyone interested in clarification of this behavior?
>
> Thanks for your help!
It's perfectly correct, let me explain on this little snippet of code:
def on_button_clicked(self, button, data):
print "click! (%s)" % data
def get_data():
return "bonk!"
button = gtk.Button()
button.connect("clicked", on_button_clicked, get_data() )
gtk.main()
When the control reaches the 'button.connect' line, there
are three object references defined:
on_button_clicked -- a function
get_data -- a function
button -- a button object
Now, in order to execute the 'clicked' method, Python needs
to compute the parameters for it. The fisrst parameter is
a string, no need to compute it. The second one is a function
reference, also no need to define it. But the third one is
a command to execute a function and use its return value.
So, naturally, Python calls that function, gets the return
value, and puts it in place of the call:
button.connect("clicked", on_button_clicked, "bonk!" )
To get the behavior you probably want, you'd need to
execute that function inside the on_button_clicked function
instead:
def on_button_clicked(self, button):
print "click! (%s)" % get_data()
--
Radomir `The Sheep' Dopieralski
"When in doubt, use brute force." [Ken Thompson]
More information about the pygtk
mailing list