0

Tkinter allows you to assign a function to a button like this:

but = Button(master,text="Press Here",command=press_B1).pack()

where press_B1 is a defined function.

I have to take an array with n elements and create a button for each one element and if you press for example the first button it print the first element of array. It simple if I have a defined number of elements but with undefined elements I don't know how to do that.

If I have not explained well what I want to do:

arr = ["a","b","c"] #random number of elements
for i in range(len(array)):
    but = Button(master,text="Press Here",command=?).pack()        

At the end I should have 3 buttons and if I press the first one, python should print "a"

Ermans
  • 3
  • 1

1 Answers1

0

Given your example, you might be able to use function definitions within the loop if you need print statements (Python 2.x);

arr = ["a","b","c"] #random number of elements
for i in range(len(arr)):
    def f(val=arr[i]):
        print val
    but = Button(None,text="Press Here",command=f).pack()  

or else you could use a lambda instead:

import sys
arr = ["a","b","c"] #random number of elements
for i in range(len(arr)):
    lam = lambda val=arr[i]: sys.stdout.write("%s\n"%val)
    but = Button(None,text="Press Here",command=lam).pack()
jmetz
  • 12,144
  • 3
  • 30
  • 41
  • Both solutions do not work, they just print the last element of the array. I'm using Python 2.7 – Ermans Mar 01 '14 at 14:54
  • @Ermans - you're right I forgot the need to use a default value, updated should work now – jmetz Mar 01 '14 at 16:47