如何让 TK 按钮命令接收带有变量的参数(Python) [英] How can I get TK button commands to take in a parameter with a variable (Python)

查看:44
本文介绍了如何让 TK 按钮命令接收带有变量的参数(Python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这让我难住了一个多星期.正如标题所问,如何让 TK 按钮命令接收带有变量的参数?

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

请注意,如果我使用注释(硬编码)命令,它会按预期工作.但是,如果我使用 not 注释的代码,使用变量 i,两个按钮都以 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.

是不是命令在运行时获取了变量i?如果是这样,或者出于其他原因,我该怎么做才能完成我想要做的事情?

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?

这是因为我对每个员工都做了类似的事情;一个 for 循环,旨在让按钮打开一个选项卡,其中员工 ID 位于参数中,作为无法硬编码的变量.

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.

提前致谢.

推荐答案

需要在创建widget时绑定i的值:

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

您可能需要为 isLeft 做同样的事情,除非它是一个静态值.

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

这篇关于如何让 TK 按钮命令接收带有变量的参数(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆