有没有办法在 Python 的 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 是一个列表,而不是一个字典,这就是为什么你不通过 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')],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”来标记。

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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...