3

Code:

import PySimpleGUI as sg

layout = [
    [sg.Input(s=(26, 1), background_color='red', k='Input')],
    [sg.Button('White', s=(10, 1)), sg.Button('Black', s=(10, 1))],
]

window = sg.Window('test', layout=layout, margins=(1, 1))

while True:
    event, values = window.read()
    window.read()
    if event == 'White':
        window['Input'].update(background_color='white')
    if event == 'Black':
        window['Input'].update(background_color='black')

I made it so when you press a button the input field will change it's colour.

But why do I have to press the button twice to actually change it?

Eskimo868
  • 238
  • 1
  • 12
  • I always have a `print(event, values)` after every call to `window.read()`. It makes finding dual reads possible, gives me events that I may not know are happening, etc. It's a really effective debugging technique for these PSG programs. – Mike from PSG Sep 25 '21 at 17:39

1 Answers1

3

Your event loop reads the event twice:

while True:
    event, values = window.read()
    window.read()

You only need it once.

Plus you should add an exit event.

Updated code:

layout = [
    [sg.Input(s=(26, 1), background_color='red', k='Input')],
    [sg.Button('White', s=(10, 1)), sg.Button('Black', s=(10, 1))],
]

window = sg.Window('test', layout=layout, margins=(1, 1))

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break

    if event == 'White':
        window['Input'].update(background_color='white')

    if event == 'Black':
        window['Input'].update(background_color='black')
quamrana
  • 37,849
  • 12
  • 53
  • 71