Python 如何在回调函数中更改tkinter中按钮的文本

Python 如何在回调函数中更改tkinter中按钮的文本,python,python-3.x,tkinter,Python,Python 3.x,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.c

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

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()
您必须将小部件引用传递到回调函数中,您可以这样做:

   import tkinter as tk

   main = tk.Tk()
   def getPressed(button):
            tk.Button.config(button, text="this has been pressed", state = tk.DISABLED)

   button1 = tk.Button(main, text="1", command=lambda widget='button1': getPressed(button1))
   button2 = tk.Button(main, text="2", command=lambda widget = 'button2': getPressed(button2))
   button1.grid(row=0, column=0)
   button2.grid(row=0, column=1)
   main.mainloop()

我要做的是使用lambda将值传递到函数中,以便您可以对按下的按钮进行编码。这是如果在按钮中使用lambda时的外观

self.Button1 = Button(self, text="1", command=lambda: getPressed(1))
如果你这样做。您可以定义一个将接受该参数并将其转换为字符串的方法。如果该值等于“1”:对此进行处理。否则,若该值等于“2”:对该按钮执行操作

如果我把这些知识应用到你的工作中。它看起来像这样

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, number):
    if(number == "1"):
      button1.config(self, text="this button has been pressed", state=DISABLED)
    elif(number == "2"):
      button2.config(self, text="Button 2 has been pressed" state=DISABLED)
我希望你明白我在说什么。如果你这样做了,请回复我对你的解释

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, number):
    if(number == "1"):
      button1.config(self, text="this button has been pressed", state=DISABLED)
    elif(number == "2"):
      button2.config(self, text="Button 2 has been pressed" state=DISABLED)