Yngve
Yngve

Reputation: 783

Python: Assign commnds to buttons using a for loop when using Tkinter

I'm using Tkinter, and I'm wondering if there is a way to define one callback function for a bunch of button commands, where the commands have names like 'callback1', callback2', etc.

I'm creating the buttons like this (it's part of a calendar):

buttonlist = ['c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7']
daylist = ['mo', 'tu', 'we', 'th', 'fr', 'sa', 'su']
counter = 0
daycount = -1

for item in buttonlist:
    counter = counter + 1
    daycount = daycount + 1
    item = Tkinter.Button(label1, width=5, bg = 'white', 
                                text = daylist[daycount])
    item.grid(row=0, column = counter, padx=5, pady=5)

I could manually add one command to each button, and define a function for each, but I would prefer to only have to define one function, and give the commands unique names in the for-loop, because I also have a button for each day in the month.

Is there a way of doing this? I'm using Python 2.7.2

Thanks

Upvotes: 1

Views: 1264

Answers (1)

Jon Clements
Jon Clements

Reputation: 142106

A long time since I've used Tkinter

Firstly, you can modify your loop to be something like (adjust as necessary):

for idx, (bl, dl) in enumerate(zip(buttonlist, daylist)):
    TKinter.Button(text=dl, command=lambda: button_pressed(bl))

and then have in an appropriate place:

def button_pressed(which):
    print 'I am button {}'.format(b1)

The lambda function creates an anonymous functions whose job is to call the button_pressed function with the button that was pressed (if that makes sense!)

Upvotes: 2

Related Questions