Calling a sequence of commands with a sequence of Tkinter buttons

Martyn Quick mrq at for.mat.bham.ac.uk
Tue Feb 20 06:36:01 EST 2001


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




More information about the Python-list mailing list