[Tutor] commands with multiple things to do?

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Mar 29 10:18:53 CEST 2005

```On Tue, 29 Mar 2005, Diana Hawksworth wrote:

> Is it possible for me to make a command do multiple things instead of 1?
> For instance, I have a button that allows me to "submit" some user input
> (that is, show it in a window), but I also want it to count the number
> of times that submit button has been pressed.
>
> I have tried this code:
>
>    self.submit_bttn = Button(self, text = "Tries: 0", command =
> self.reveal, self.update_count)

Hi Diana,

Yes.  The easiest thing to do here is write an "internal function"
definition.

We already know how to define functions:

######
def square(x):
return x * x

def sqrt(x):
return x**0.5

def hypotenuse(a, b):
return sqrt(square(a) + square(b))
######

Here, we're writing square and sqrt just as helpers to hypotenuse, to make

Anyway, a neat thing is that we can do this function definition pretty
much anywhere, even within other functions:

######
def hypotenuse(a, b):
def square(x):
return x * x
def sqrt(x):
return x**0.5

return sqrt(square(a) + square(b))
######

And now it's very clear that square() and sqrt() are intended for internal
use by the hypotenuse function.  They are "local" internal defintions.

In the problem brought up above, we can write an internal definition:

######
# ... some earlier code, right before the call to the Button
# construction
def my_command():
self.reveal()
self.update_count()
######

Once we have this function, we can then use it as the callback we pass to
submit_bttn:

######
def my_command():
self.reveal()
self.update_count()
self.submit_bttn = Button(self, text = "Tries: 0",
command = my_command)
######

This is a nice feature of Python.  But if you're familiar with more static
languages like C, this might look a little weird.  *grin*

If you can tell us what other programming languages you've had experience
with, perhaps we can give you analogies in those languages.  Please feel
free to ask more questions on this.

Best of wishes!

```