python - 如何在回调函数中更改 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 模块)
解决方案
您可以使用 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()
推荐阅读
- python - 使用 OpenCV 将 BGR 转换为 RGB 时出现断言错误
- c++ - OpenGL 投影矩阵显示正交
- c# - InsertOneModel 与 InsertOneAsyn 之间的区别
- html - 当用户单击箭头更改推荐时,我怎样才能让它转到下一条评论?
- ios - 每当我添加 FlutterFire 包时,Firebase 就会停止工作
- fortran - 如果使用不是直接从 MPI_COMM_WORLD 创建的组,则在 fortran MPI_COMM_CREATE_GROUP 中出现段错误
- java - 在 JLabel 中打开文件
- conda - 由于 python.app 错误,conda 更新后无法启动 Spyder
- javascript - 范围滑块 - 向下箭头跟随拇指
- ios - 无法在 iOS NativeScript Sidekick 中使用 openUrl 打开应用程序