好的,这里是一个例子,使用一个类来执行我认为它是你问的东西。
你想在你的命令中使用lambda并将文本的值赋给一个变量。然后您将该变量传递给getTest(self, text)方法以便能够打印您的按钮。
从您的评论
整个代码是不需要我只是需要的方式来获得按钮文本没有别的
我创建了一个位的代码来说明你想要什么。
编辑:我已经添加了代码,可以让你改变按钮的配置。
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()
这是运行程序并按下几个按钮的结果。