为什么我必须双击才能真正做某事?

Why do I have to double click to actually do something?

代码:

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')

我做到了,当您按下按钮时,输入字段会改变它的颜色。

但为什么我必须按两次按钮才能真正改变它?

您的事件循环读取事件两次:

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

你只需要一次。

另外你应该添加一个退出事件。

更新代码:

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')