Tkinter question

Fredrik Lundh fredrik at pythonware.com
Wed Jun 15 08:04:46 EDT 2005


Nicholas.Vaidyanathan at aps.com wrote:

> I'm sure there must be a way to do this, but I can't figure it out for
> the life of me... I'm writing a program where I would like to use a
> button's text field as part of an if statement. I set up my button like
> this:
>
>  i = [ "7", "8","9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+"]
>  t = 0   #iterator through the sequence
>
> for x in range(4):
>             for y in range(4):
>                 self.buttonx = Button(self, text = "%s" %i[t], width=10, command = self.pressed)
>                 self.buttonx.grid( row=x+1, column = y, sticky = W+E+S)
>                 t+=1
>
> What I would like to do is is check which buttons' text values are
< digits, and if the text is, I would like to append the number to a
> label. But:
>
> if(self.buttonx.title.isdigit):
>
> Doesn't work. How do I access the button's text field?

note that you're assigning all buttons to the same instance variable, so
even if the above did work, it would always return a plus.

since the command callback doesn't know what widget it was called
from, you need to create a separate callback for each widget.  here's
one way to do that:

    for x in range(4):
        for y in range(4):
            text = i[t] # label text
            def callback():
                self.pressed(text)
            buttonx = Button(self, text=text, width=10, command=callback)
            buttonx.grid( row=x+1, column = y, sticky = W+E+S)

the "def callback" statement creates a small dispatcher which calls your
original key handler with the widget's text as the argument.

    def pressed(self, text):
        print "PRESSED", text

</F> 






More information about the Python-list mailing list