How to get text from dynamically created buttons?

走远了吗. 提交于 2021-02-15 07:51:34

问题


I want my buttons when i click on them to return the text attribute of them.

I've used a for loop to dynamically create the buttons but when i do this the btn variable gets stuck on the last created button meaning every button returns the same text value.

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

This code produces 4 buttons: Image of buttons

However no matter what button i press btn['text'] will always return Bike. I want the output to be that of the button itself for example when i click car i want btn['text'] to return car.


回答1:


You can use lambda in command= to assign function with argument - word - and function has to get this argument - 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()

Instead of word you can send btn to function so you can get text from button but also change text on button or change its color, etc.

But it need little different method

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()

You can also use bind('<Button-1>', callback) to assing click to Button or other Windget and it will run function with argument event which gives access to clicked widget - 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()


来源:https://stackoverflow.com/questions/55598418/how-to-get-text-from-dynamically-created-buttons

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!