PySimpleGui:如何在文本框中输入文本?

4

我正在参考链接1链接2上的教程学习PySimpleGui。

我需要在我的布局中添加按钮来输入一个值,并将该值显示在相邻的文本框中。

到目前为止,我已经成功创建了按钮和文本框。

以下是我的代码:

import PySimpleGUI as sg

layout = [[sg.Text('Enter Value:')],
          [sg.Input(do_not_clear=False), sg.Text('Value selected is:'), sg.Text(sg.InputText(""), key='_USERNAME_')],
          [sg.Button('Enter'), sg.Exit()],
          [sg.Text('List Of Values:')],
          [sg.Listbox(values=('value1', 'value2', 'value3'), size=(30, 2), key='_LISTBOX_')]]

window = sg.Window('My Application', layout)

while True:
    event, values = window.Read()
    print(event, values)
    if event is None or event == 'Exit':
        break
    if event == 'Enter':
        window.Element('_LISTBOX_').Update(values=[event, values, 'new value 3'])
        #window.Element('_USERNAME_').Update(values=[values]) #need to update the text box with value entered
window.Close()

然而,我无法在文本框中显示输入的值。

我已经在代码中添加了一个注释(现在会出现错误),在那里我需要更新文本框以显示输入的值。

请帮忙!

编辑:我能够在弹出窗口中显示该值,但我需要在文本框中显示。

2个回答

4
你可以通过在window对象上引用它们的键来直接更新元素:
例如根据你的更新
window['_LISTBOX_'].Update(values=[event, values, 'new value 3'])
window['_USERNAME_'].Update(values[0])

2

我想通了,

以下代码满足我的需求:

import PySimpleGUI as sg

layout = [[sg.Text('Enter Value:')],
          [sg.Input(do_not_clear=False), sg.T('Not Selected ', size=(52,1), justification='left',text_color='red', background_color='white', key='_USERNAME_')],
          [sg.Button('Enter'), sg.Exit()],
          [sg.Text('List Of Values:')],
          [sg.Listbox(values=('value1', 'value2', 'value3'), size=(30, 2), key='_LISTBOX_')]]

window = sg.Window('My Application', layout)

while True:
    event, values = window.Read()
    print(event, values)
    if event is None or event == 'Exit':
        break
    if event == 'Enter':
        window.Element('_LISTBOX_').Update(values=[event, values, 'new value 3'])
        window.FindElement('_USERNAME_').Update(values[0])
window.Close()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接