Calling a sequence of commands with a sequence of Tkinter buttons
Harald Rosemann
rosemann at imkt.uni-hannover.de
Wed Feb 21 03:39:40 EST 2001
Martyn Quick wrote:
>
> I'm trying to create a number of buttons each of which has a similar sort
> of command attached to it. Obviously the following doesn't work since I'm
> attaching a called function to the button rather than the function to
> call. Can anyone tell me the correct way to do it? (Equally obviously, I
> could create a different function for each button, but this seems lengthy
> for a large number of buttons).
>
> Thanks
> Martyn
>
> MY ATTEMPT:
>
> from Tkinter import *
>
> def f(i): # Typically I'll have a more complicated function
> print i # but this is just for illustration
>
> root = Tk()
>
> buttons = [] # initialize list to contain the button widgets
>
> for i in range(20):
> buttons.append(Button(root,text="Button "+`i`,command=f(i)))
> buttons[i].pack()
> # This doesn't work - it just prints 1,2,..,20 down the screen
> # immediately, since f(i) is called at the creation of the button.
>
>
> --------------------------------------------------------
> Dr. Martyn Quick (Research Fellow in Pure Mathematics)
> University of Birmingham, Edgbaston, Birmingham, UK.
> http://www.mat.bham.ac.uk/M.R.Quick
You may use a "lambda expression".
Something like the following will work.
def show_ind(i, event=None):
print i
...
my_tst[i] = Tkinter.Frame(zzz, ....)
my_tst[i].pack()
....
my_but[i] = Tkinter.Button(my_tst[i], text = ".....", state = status)
my_but[i].pack(side = Tkinter.LEFT)
my_but[i].bind("<Button-1>", (lambda event, ind=i: show_ind(ind,
event)))
With best regards,
Harald Rosemann
--
Prof.Dr.-Ing. Harald Rosemann
am Institut fuer Maschinenelemente,
Konstruktionstechnik und Tribologie
Universitaet Hannover
More information about the Python-list
mailing list