好的,这里有一个例子,使用一个类来执行我认为你所要求的。在
您希望在命令中使用lambda并将text的值赋给变量。然后将该变量传递给getTest(self, text)方法,以便能够打印按钮。在
从你的评论中Whole code is not need i just need way to get buttons text nothing else
我创建了一些代码来说明您想要什么。在
编辑:我已经添加了代码,允许您更改按钮的配置。在import tkinter as tk
# created this variable in order to test your code.
seznamTextu = ["1st Button", "2nd Button", "3rd Button", "4th Button", "5th Button"]
class MyButton(tk.Frame):
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.parent = parent
self.obsahOkna()
def obsahOkna(self):
radek = 0
bunka = 0
for i in range(5):
btn = tk.Button(self.parent, text=seznamTextu[i])
btn.config(command= lambda t=seznamTextu[i], btn = btn: self.getText(t, btn))
# in order for this to work you need to add the command in the config after the button is created.
# in the lambda you need to create the variables to be passed then pass them to the function you want.
btn.grid(row=radek, column=bunka)
bunka += 1
if bunka == 2 : # changed this variable to make it easier to test code.
bunka = 0
radek +=1
def getText(self, text, btn):
btn.configure(background = 'black', foreground = "white")
print("successfully called getText")
print(text)
if __name__ == "__main__":
root = tk.Tk()
myApp = MyButton(root)
root.mainloop()
这是运行程序并按下几个按钮的结果。在