【发布时间】:2021-02-12 10:32:05
【问题描述】:
我想知道如何使用它的键获取值(文本输入框),但我真的不知道如何。
我认为您可以使用values['key_name_here'],但我不确定。我已经尝试过了,但它似乎没有用。 (至少我在文本标签上试过)
我还需要从标签中获取文本,但到目前为止我不知道该怎么做。
【问题讨论】:
标签: python python-3.x pysimplegui
我想知道如何使用它的键获取值(文本输入框),但我真的不知道如何。
我认为您可以使用values['key_name_here'],但我不确定。我已经尝试过了,但它似乎没有用。 (至少我在文本标签上试过)
我还需要从标签中获取文本,但到目前为止我不知道该怎么做。
【问题讨论】:
标签: python python-3.x pysimplegui
如果你回到 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) 行将列表(布局)传递给变量“窗口”。
在事件循环中,文本输入框的状态由event, values = window.read()处理,将文本传递给“值”。 Values 是一个列表,而不是字典,这就是为什么您不通过values['Inp1'] 访问它的原因;您可以通过列表索引values[0] 访问它(假设如果有多个InputBox,则下一个将是values[1])。
或者,一旦事件循环启动,你可以直接使用.get()获取InputBox值:print(f'Label 1 is {layout[1][1].get()}')
获取标签的文本有点晦涩难懂。答案是使用.DisplayText:print(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”来标记的。
小部件的顺序由布局定义。每行是一个小部件列表,然后将所有列表添加到布局容器中。这意味着第一行小部件是 layout[0]。第一行的第一个小部件是 layout[0][0]。
【讨论】:
f 做了什么print(f'Text')