I am trying to get the name of a button when pressed. I have looked at several other answers, but I don't understand how to get them to work. This is what I have:
number = 0
location = 0
characters = ['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']
text_list = []
for idx in characters:
text_list.append(Button(window, text=characters[number], command = clear))
text_list[-1].place(x=location, y=0)
location += 18
number += 1
it makes a button for every letter in the alphabet (I am making hang man). The unstyled result looks like this:
I now want a way to get the name of the button, so that I know what letter was pressed. That is what I need help on.
Try using:
import tkinter as tk
import string # string.ascii_lowercase = "abcdefghijklmnopqrstuvwxyz"
def button_pressed(button):
# `button.cget("text")` gets text attribute of the button
print("Button text =", button.cget("text"))
text_list = []
window = tk.Tk()
# Iterate over each letter in the alphabet
for character in string.ascii_lowercase:
# Create the button
button = tk.Button(window, text=character)
# Add the command attribute to the button
button.config(command=lambda button=button: button_pressed(button))
# Show the button on the screen using `.pack` because it's much easier to use
button.pack(side="left")
# Append it to the list of buttons
text_list.append(button)
window.mainloop()
It passes the button
to the function which uses button.cget("text")
to get the text from the button.