python - 如何让 TK 按钮命令接受带有变量的参数(Python)

标签 python tkinter tk-toolkit

这已经困扰了我一个多星期了。正如标题所问,如何让 TK 按钮命令接受带有变量的参数?

这是我正在使用的确切代码:

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

请注意,如果我使用注释(硬编码)命令,它会按预期工作。但是,如果我使用注释的代码以及变量 i,两个按钮都会以 i=1 的命令结束。

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

这是因为我为每个员工做了类似的事情;一个 for 循环,旨在使用按钮打开一个带有员工 ID 的选项卡,该员工 ID 作为无法硬编码的变量存在于参数中。

提前致谢。

最佳答案

您需要在创建小部件时绑定(bind) i 的值:

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

您可能需要对 isLeft 执行相同的操作,除非它是静态值。

关于python - 如何让 TK 按钮命令接受带有变量的参数(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13113780/

相关文章:

python - Pandas 根据其他列上的复合条件添加一列

python - 如何在python3中的EOF之前提前读取stdin缓冲区?

python - 带有 tk 的窗口以获取文本

python-3.x - Python + matplotlib 中的自动补全导致 'RuntimeError: main thread not in main loop'

python - 来自更大列表的对象实例的排序/唯一列表?

python - Apache Airflow : Pass variable in jinja include

python - Tkinter 文本滚动条走得太远

python - 类型错误 : cannot pickle 'weakref' object

用于替换标签的 Python Tkinter 按钮

python - 编辑组合框时拦截事件