1

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

1 Answer 1

2

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!)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! Haven't quite figured out how to make it work yet, but now I know where to start. Much appreciated.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.