0

I wrote a for loop to create buttons according to the number of sheets in an excel workbook. However, I'm having a hard time binding functions that print the data on each sheet. Can anyone help? Thanks. Here's what I have done

wb = xlrd.open_workbook('file_path.xlsx')
        sheetnames = wb.sheet_names()
        num_sheets = len(sheetnames)

        def load_sheet():
        for d in range(0, num_sheets):
            print(sheetnames[d])

        for i in range(0, num_sheets):
            an_sheet = ttk.Button(self, text = "%s" % sheetnames[i], 
                                  command= lambda : load_data)
            an_sheet.grid(row = 1, column = i+1, sticky='w', pady = 10, padx = 10)
3
  • What's the function that you want to bind? Commented Mar 21, 2017 at 17:18
  • sorry forgot to paste that piece of the code .. editing question asap Commented Mar 21, 2017 at 17:22
  • the question has been updated Commented Mar 21, 2017 at 17:26

1 Answer 1

1

It's a common beginner's issue if you are using lambda in a for loop because beginners don't realize that lambda is late-binding. In other words it always uses the last value of "i", not the value of "i" when the command argument was set. In this case you need to use functools.partial instead:

from functools import partial
# ...
for i in range(0, num_sheets):
    an_sheet = ttk.Button(self, text = "%s" % sheetnames[i], command=partial(function, i))
    an_sheet.grid(row = 1, column = i+1, sticky='w', pady = 10, padx = 10)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much, does functools come with python or i have to install it.
It's part of the default install.

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.