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

拟墨画扇 提交于 2021-02-19 08:01:27

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/13113780/how-can-i-get-tk-button-commands-to-take-in-a-parameter-with-a-variable-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!