1 回答
TA贡献1712条经验 获得超3个赞
您可以使用lambdaincommand=用参数分配函数 - word- 并且函数必须获取此参数 -def get_text(text)
import tkinter as tk
def get_text(text):
print(text)
list_words = ("Car","Train","Bus","Bike")
var = 0
root = tk.Tk()
for word in list_words:
btn = tk.Button(root, text=word, command=lambda txt=word:get_text(txt))
btn.grid(column=var, row=0)
var += 1
root.mainloop()
而不是word您可以发送btn到功能,以便您可以从按钮获取文本,但也可以更改按钮上的文本或更改其颜色等。
但它需要一点不同的方法
import tkinter as tk
def get_widget(widget):
print(widget["text"])
widget["text"] = "DONE"
widget["bg"] = "green"
list_words = ("Car","Train","Bus","Bike")
var = 0
root = tk.Tk()
for word in list_words:
btn = tk.Button(root, text=word)
btn["command"] = lambda widget=btn:get_widget(widget)
btn.grid(column=var, row=0)
var += 1
root.mainloop()
您还可以使用bind('<Button-1>', callback)assing click to Button 或其他 Windget,它将运行带有参数的函数,该参数event可以访问单击的小部件 -event.widget
import tkinter as tk
def get_event(event):
print(event.widget["text"])
event.widget["text"] = "DONE"
event.widget["bg"] = "green"
list_words = ("Car","Train","Bus","Bike")
var = 0
root = tk.Tk()
for word in list_words:
btn = tk.Button(root, text=word)
btn.bind('<Button-1>', get_event)
btn.grid(column=var, row=0)
var += 1
root.mainloop()
添加回答
举报