首页 > 解决方案 > 如何在回调函数中更改 tkinter 中按钮的文本

问题描述

是否可以在按下按钮时更改按钮上的文本,即使有很多按钮使用相同的回调命令?

button1 = Button(self, text="1", command=self.getPressed)
button2 = Button(self, text="2", command=self.getPressed)

button1.grid(row=0, column=0)
button2.grid(row=0, column=1)

def getPressed(self):
    button.config(self, text="this has been pressed", state=DISABLED)

我知道这段代码不起作用,因为 button 不是变量,但这是我为回调考虑的那种事情。(我在 python 3.7 中使用 tkinter 模块)

标签: pythonpython-3.xtkinter

解决方案


您可以使用 lambda 将按钮的编号作为参数传递给回调函数:

command=lambda:self.getPressed(1)

然后使用 if 来确定按下了哪个按钮。或者您可以将按钮存储在列表中,然后将索引传递给回调函数。

不使用类符号的示例:

from tkinter import *

root = Tk()

def getPressed(no):
    button_list[no].config(text="this has been pressed", state=DISABLED)

button_list = []
button_list.append(Button(text="1", command=lambda:getPressed(0)))
button_list.append(Button(text="2", command=lambda:getPressed(1)))

button_list[0].grid(row=0, column=0)
button_list[1].grid(row=0, column=1)

root.mainloop()

推荐阅读