2

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: enter image description here

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Wow! Thanks so much for spending your time to solve my problem. It is much appreciated
0

just pass the name you want to get from callback

from tkinter import *
for idx in characters:
    button = Button(name=characters[idx], command=lambda name=characters[idx]:print(name))
    # pack, grid, place

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.