narutoreplicate
narutoreplicate

Reputation: 13

How can I get TK button commands to take in a parameter with a variable (Python)

This has stumped me for over a week. As the title asks, how can I get TK button commands to take in a parameter with a variable?

Here is the exact code I'm using:

i=0

# Make a Staff list button
staffButton = Button(masterFrame,
                        text='Staff List',
                        width=20,
                        justify=LEFT,
                        #command=lambda:self.openTabHere(isLeft,STAFF_LIST_TAB))
                        command=lambda:self.openTabHere(isLeft,i))
staffButton.grid(column=0, row=1)

# Make a course list button
courseButton = Button(masterFrame,
                        text='Course List',
                        width=20,
                        justify=LEFT,
                        #command=lambda:self.openTabHere(isLeft,COURSE_LIST_TAB))
                        command=lambda:self.openTabHere(isLeft,i))
courseButton.grid(column=0, row=0)

i=1

Note that if I use the commented (hardcoded) command, it works as intended. However, if I use the code not commented, with the variable i, both buttons end up with the command for i=1.

Is it that the command gets the variable i at runtime? If so, or for some other reason, what can I do to accomplish what I'm trying to do?

This is because I do something similar for every staff member; a for loop intending to have buttons that open up a tab with a staff ID that is in the parameter as a variable that can't be hardcoded.

Thanks ahead of time.

Upvotes: 1

Views: 203

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385830

You need to bind the value of i at the time you create the widget:

staffButton = Button(..., command=lambda btn=i:self.openTabHere(isLeft,btn))

You probably need to do the same thing for isLeft, unless that's a static value.

Upvotes: 1

Related Questions