pythonstringfor-loopenumeratecustomtkinter

Why is my index in my enumerate() function not functioning properly?


So when I'm trying to make buttons for my sidebar, I make a button for every class by using a for loop.

for index, course in enumerate(api.pull_courses('insert_my_api_key_which_works')):
            course_button = customtkinter.CTkButton(self, text=course,
                            command=lambda: controller.show_frame('ClassPage' + str(index)))
            print(index)
            course_button.place(relx=0.5, rely=((index + 1) * ((0.6)/9))+0.2, anchor=customtkinter.CENTER)

The print(index) function gives the output

0
1
2
3
4
5
6
7

but the command=lambda: controller.show_frame('ClassPage' + str(index)) keeps trying to class ClassPage7 instead of Classpage0, ClassPage1, etc. Does anybody know why or have a fix for future reference?


Solution

  • To fix it create the lambda this way:

    command=lambda index=index: controller.show_frame("ClassPage" + str(index))