有没有办法使用 Python 的 PySimpleGUI 中的键获取输入?

Is there a way to get inputs using their keys in Python's PySimpleGUI?

我想知道如何使用它的键获取值(文本输入框),但我真的不知道如何。

我想你可以使用 values['key_name_here'],但我不确定。我试过了,但似乎没有用。 (至少我在文本标签上试过了)

我还需要从标签中获取文本,但到目前为止我还不知道该怎么做。

如果你回到 PySimpleGUI 的基本介绍(Jumpstart),这里告诉你如何获取文本输入框的值。

import PySimpleGUI as sg

sg.theme('DarkAmber')   # Add a touch of color
# All the stuff inside your window.
layout = [  [sg.Text('Some text on Row 1')],
            [sg.Text('Enter something on Row 2'), sg.InputText()],
            [sg.Button('Ok'), sg.Button('Cancel')] ]

# Create the Window
window = sg.Window('Window Title', layout)
# Event Loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
        break
    print('You entered ', values[0])

window.close()

你可以从初始化中看到 window = sg.Window('Window Title', layout) 行将列表(布局)传递给变量“window”。

在事件循环中,文本输入框的状态由event, values = window.read()处理,将文本传递给“值”。 Values 是一个列表,而不是字典,这就是为什么您不通过 values['Inp1'] 访问它的原因;您可以通过列表索引 values[0] 访问它(大概如果有多个 InputBox,下一个将是 values[1])。

或者,事件循环启动后,您可以直接使用.get()获取InputBox值:print(f'Label 1 is {layout[1][1].get()}')

获取标签的文本有点难懂。答案是使用.DisplayTextprint(f'Label 1 is {layout[0][0].DisplayText}')

使用直接访问的示例:

import PySimpleGUI as sg

sg.theme('DarkAmber')   # Add a touch of color
# All the stuff inside your window.
layout = [  [sg.Text('Some text on Row 1')],
            [sg.Text('Enter something on Row 2'), sg.InputText()],
            [sg.Button('Ok'), sg.Button('Cancel')] ]

# Create the Window
window = sg.Window('Window Title', layout)
# Event Loop to process "events" and get the "values" of the inputs
while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED or event == 'Cancel': # if user closes window or clicks cancel
        break
    print('You entered ', values[0])
    # This is a directly accessed Label
    print(f'Label 1 is {layout[0][0].DisplayText}')
    # This is directly accessed InputBox
    print(f'Label 1 is {layout[1][1].get()}')
    # Note that layout is a list of lists

window.close()

Python 中有不同的方法来构建动态字符串。 f-strings (Formatted String Literals) 是最新的,通常也是我个人的选择。这些通过在字符串 f'Label 1 is {layout[1][1].get()}'.

前面放置 'f' 来标记

小部件的顺序由布局定义。每行是一个小部件列表,然后将所有列表添加到布局容器中。这意味着第一行小部件是布局[0]。第一行的第一个小部件是 layout[0][0].