Brad Fortner
Brad Fortner

Reputation: 144

PySimpleGui - Get Button Text

I'm developing an app using PySimpleGui that will assign button text from a list. The text on the button(s) will change by users as they search. I want to be able to read, print and assign the button text when the button is pushed. How do I do that? Here's the code. I've tried several things to no avail. Two print statements at the end of the code are remnants.

import PySimpleGUI as sg

selection_button_text_data = ['Like a Rolling Stone','Bob Dylan','The Sound of Silence','Simon & Garfunkel','Respect','Aretha Franklin','A Day In The Life','The Beatles']

layout =[
    [
        [sg.Button(selection_button_text_data[0])],
        [sg.Button(selection_button_text_data[1])],
        [sg.Button(selection_button_text_data[2])],
        [sg.Button(selection_button_text_data[3])]
    ]
        ]
window = sg.Window('Window Title', layout)
event, values = window.read()
window.close()
print(values)
print(sg.Button.GetText())

Upvotes: 2

Views: 5709

Answers (1)

Jason Yang
Jason Yang

Reputation: 13061

In your case, it's better give each key for each button, then you will get event same as the key of clicked button. By window[key], you can get the element and apply method get_text() to get text of button.

import PySimpleGUI as sg

selection_button_text_data = [
    'Like a Rolling Stone',
    'Bob Dylan',
    'The Sound of Silence',
    'Simon & Garfunkel',
    'Respect',
    'Aretha Franklin',
    'A Day In The Life','The Beatles',
]

layout =[
    [sg.Button(selection_button_text_data[i], key=f'BTN{i}')] for i in range(4)
]
window = sg.Window('Window Title', layout)
event, values = window.read()
if event != sg.WINDOW_CLOSED:
    print(window[event].get_text())
window.close()
The Sound of Silence

Upvotes: 3

Related Questions