Tkinter
Fredrik Lundh
fredrik at pythonware.com
Sun Apr 16 11:10:43 EDT 2006
"Jay" wrote:
> I wold like to be able to generate buttons from a list in a file.
> How would I go about making each button have a different command,
> Lets say make the button print its label instead of print "."
>
> The problem I have is I don't know what the list is going to be until
> it is opened or how big so I carnet make a def for each.
def is an executable statement, and creates a new function object
everytime it's executed. if you want a new function for each pass
through a loop, just put the def inside the loop:
> from Tkinter import *
>
> class App:
> def __init__(self, root):
>
> self.DisplayAreaListsFrame = Frame(root)
> self.DisplayAreaListsFrame.pack()
>
> Lists = ["A1","B2","C3","D4"]
>
> for i in Lists:
def callback(text=i):
print text
> self.DisplayAreaListButton = Button(
> self.DisplayAreaListsFrame,
> text=i,
> command=callback)
> self.DisplayAreaListButton.pack(side=LEFT,padx=10)
>
> root = Tk()
> app = App(root)
> root.mainloop()
the only think that's a little bit tricky is scoping: you can access all
variables from the __init__ method's scope from inside the callbacks,
but the callbacks will be called after the loop is finished, so the "i"
variable will be set to the *last* list item for all callbacks.
to work around this, you have to explicitly pass the *value* of "i" to
to the callback; the "text=i" part in the above example uses Python's
default argument handling to do exactly that.
</F>
More information about the Python-list
mailing list