猿问

如何从动态创建的按钮中获取文本?

我想要我的按钮,当我点击它们时返回它们的文本属性。


我使用了 for 循环来动态创建按钮,但是当我这样做时, btn 变量卡在最后创建的按钮上,这意味着每个按钮都返回相同的文本值。


listWords = ("Car","Train","Bus","Bike")

var = 0

def getdef():

    print(btn['text'])

for word in listWords:

    btn = Button(window, text=word,command=getdef)

    btn.grid(column=var, row=0)

    var = var + 1

此代码生成 4 个按钮:按钮 图像

但是,无论我按什么按钮 btn['text'] 都会返回 Bike。我希望输出是按钮本身的输出,例如当我单击汽车时,我希望 btn['text'] 返回汽车。


凤凰求蛊
浏览 252回答 1
1回答

交互式爱情

您可以使用lambdaincommand=用参数分配函数 - word- 并且函数必须获取此参数 -def get_text(text)import tkinter as tkdef get_text(text):&nbsp; &nbsp; print(text)list_words = ("Car","Train","Bus","Bike")var = 0root = tk.Tk()for word in list_words:&nbsp; &nbsp; btn = tk.Button(root, text=word, command=lambda txt=word:get_text(txt))&nbsp; &nbsp; btn.grid(column=var, row=0)&nbsp; &nbsp; var += 1root.mainloop()而不是word您可以发送btn到功能,以便您可以从按钮获取文本,但也可以更改按钮上的文本或更改其颜色等。但它需要一点不同的方法import tkinter as tkdef get_widget(widget):&nbsp; &nbsp; print(widget["text"])&nbsp; &nbsp; widget["text"] = "DONE"&nbsp; &nbsp; widget["bg"] = "green"list_words = ("Car","Train","Bus","Bike")var = 0root = tk.Tk()for word in list_words:&nbsp; &nbsp; btn = tk.Button(root, text=word)&nbsp; &nbsp; btn["command"] = lambda widget=btn:get_widget(widget)&nbsp; &nbsp; btn.grid(column=var, row=0)&nbsp; &nbsp; var += 1root.mainloop()您还可以使用bind('<Button-1>', callback)assing click to Button 或其他 Windget,它将运行带有参数的函数,该参数event可以访问单击的小部件 -event.widgetimport tkinter as tkdef get_event(event):&nbsp; &nbsp; print(event.widget["text"])&nbsp; &nbsp; event.widget["text"] = "DONE"&nbsp; &nbsp; event.widget["bg"] = "green"list_words = ("Car","Train","Bus","Bike")var = 0root = tk.Tk()for word in list_words:&nbsp; &nbsp; btn = tk.Button(root, text=word)&nbsp; &nbsp; btn.bind('<Button-1>', get_event)&nbsp; &nbsp; btn.grid(column=var, row=0)&nbsp; &nbsp; var += 1root.mainloop()
随时随地看视频慕课网APP

相关分类

Python
我要回答