I am making a vector of buttons.
interfaceLectorNotas = Toplevel()
interfaceLectorNotas.title("Enciclopedia")
interfaceLectorNotas.geometry("800x600")
lienzo = Canvas(interfaceLectorNotas, width=800, height=600)
lienzo.place(x=0, y=0)
btnsText = ["#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M","N", "Ñ", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
btns = []
contador = 0
for i in btnsText:
btns.append(Button(lienzo, text=i, command=lambda : print("Akas")))
btns[contador].place(x=(22*contador)+4, y=2)
contador = contador + 1
I need to know how to refer to itself... that is, if I press the A button, it prints A??? how can I do it????
Look at the following example:
In this example, clicking any button will print "D" , since at the end of the for loop ,
i == "D"
(the last item in the list). However, the text of each button is the expected one ("A"
,"B"
,"C"
and"D"
respectively), regardless of the final value ofi
, since the button text is not a value by reference , but a copy of the current value ofi
.Instead of using
command
you can handle the event'<Button-1>'
. For example:The event
'<Button-1>'
fires when the mouse is left clicked . The event handler is the functionshow_me
, which must receive an argument that refers to the event itself (e
).Inside the handler
show_me
you can access the widget that the event was fired on usinge.widget
, and since you assigned the text you want to display to the button's own text, you can print it usinge.widget.cget('text')
.NOTE: Trying to use it wo
btn = Button(root, text=i, command=lambda:print(btn.cget('text')))
n't work, since at the end of the for loop , the variablebtn
refers to the last button (it would always print "D" ).You can use lambda functions if you prefer:
All the best!