pysimplegui之元素简单介绍(元素值得获取修改,key的规范及特殊用法)(A brief introduction to the elements of pysimplegui (the elements are worth obtaining and modifying, the specification and special usage of key))

重点

1获取元素的值

Input(key=’mykey’)

values[‘mykey’]

2通过key查找元素 对象window[‘key’]

3更新元素的值

window[‘key’](要更新的值)

window[‘key’]。update()

4

假设您有一个带有输入元素网格的窗口。您可以使用它们的行和列位置作为键(元组)

key=(row, col)

然后,当您读取从调用返回给您的变量时,变量中的键将是您用于创建元素的任何内容。在这种情况下,您会将值读取为: 

values
Window.read()
values
values[(row, col)]

5key的规范

大多数时候,它们是简单的文本字符串。在演示程序中,键按以下约定编写:( 下划线开头和结尾全部大写字母)或最近的约定是在开头和结尾使用破折号(例如)。您不必遵守约定,但遵守约定也不错,因为其他用户已经习惯了这种格式,并且在使用元素键时很容易发现。

_KEY_NAME_
'-KEY_NAME-'

正文

您将在文档的“调用参考”选项卡中找到有关元素和所有其他类和函数的信息。

“元素”是用于创建窗口的构建块。一些 GUI API 使用术语“Widget”来描述这些图形元素。因此,当引用 PySimpleGUI元素与底层 GUI 框架的Widget时,就很清楚了。PySimpleGUI 元素映射到 GUI 框架小部件,通常以一对一的方式。例如,文本元素是在 tkinter 中使用标签小部件实现的。

Tkinter 端口中的元素表

PySimpleGUI 的每个端口都有一组核心元素以及特定于端口的元素。一些特定于端口的元素包括 Qt 端口中的 Dial 元素和 tkinter 端口中的 Pane 元素。

元素名称 别名 tkinter 小部件 描述
文本 T,文本 tk.标签 一行或多行文本
输入 我,在,输入文本 tk.Entry 单行文本输入
组合 DD, Drop, DropDown, InputCombo    
选项菜单 输入选项菜单    
多行 ML, 多线    
输出      
收音机 R,拉德    
复选框 CB、CBox、检查    
旋转 Sp    
按钮 B, Btn    
图片 我是    
帆布      
柱子 科尔    
框架 神父    
标签      
选项卡组      
窗格      
图形 G    
滑块 SL    
列表框 LB, LBox    
菜单 菜单栏,菜单栏    
菜单栏自定义      
按钮菜单 BM, B菜单    
标题栏      
进度条 PBar, Prog, 进展    
桌子      
     
垂直分隔符 VSep, VSeparator    
水平分隔符 HSep,HS分离器    
状态栏 酒吧    
尺寸握把 SGrip    
P,拉伸    
副推 副总裁,VStretch    
尺寸测量仪      

布局辅助函数

您的窗口布局由元素列表组成。除了元素之外,这些布局帮助功能也可能出现在布局定义中

布局助手 描述
别针 将元素“固定”到布局中的某个位置。如果元素从不可见过渡到可见,则 pin 确保元素位于正确的位置
顶部 将元素或元素行垂直对齐到行的顶部
底部 将元素或元素行垂直对齐到行的底部
中心 将元素或元素行垂直对齐到行的中心
  • 文本
  • 单线输入
  • 包括以下类型的按钮:

    文件浏览
    文件夹浏览
    日历选择器
    日期选择器
    阅读窗口
    关闭窗口(“按钮”和所有快捷按钮)
    即时的

  • 文件浏览
  • 文件夹浏览
  • 日历选择器
  • 日期选择器
  • 阅读窗口
  • 关闭窗口(“按钮”和所有快捷按钮)
  • 即时的

钥匙

在 PySimpleGUI 中,键是一个非常重要的概念。

如果你打算用你的 GUI 做任何超出基本东西的事情,那么你需要了解键。

您可以将“键”视为元素的“名称”。或“标识符”。这是您使用 PySimpleGUI 库识别和讨论元素的一种方式。它与字典键完全相同。它们对于窗口必须是唯一的。

使用参数创建元素时指定键。

key

键的使用方式如下: * 创建元素时指定 * 作为事件返回。如果一个元素导致一个事件,它的键将被使用 * 在从返回的字典中 * 进行更新(更改),到窗口中的元素

values
window.read()

在您将键放入元素的定义中后,从中返回的值将使用该键告诉您该值。例如,如果您的布局中有一个输入元素:

window.read

Input(key='mykey')

你的阅读看起来像这样: 

event, values = Read()

然后要从读取中获取输入值,它将是: 

values['mykey']

如果要对元素调用 Update,也可以使用相同的键。请参阅更新元素部分以了解该用法。要在给定元素键的情况下查找元素对象,可以调用 window 方法(也写为 , ),也可以使用更常见的查找机制:

find_element
FindElement
element
window['key']

虽然您经常会在本文档的示例中看到以字符串形式编写的键,但要知道键可以是ANYTHING

假设您有一个带有输入元素网格的窗口。您可以使用它们的行和列位置作为键(元组)

key=(row, col)

然后,当您读取从调用返回给您的变量时,变量中的键将是您用于创建元素的任何内容。在这种情况下,您会将值读取为: 

values
Window.read()
values
values[(row, col)]

大多数时候,它们是简单的文本字符串。在演示程序中,键按以下约定编写:( 下划线开头和结尾全部大写字母)或最近的约定是在开头和结尾使用破折号(例如)。您不必遵守约定,但遵守约定也不错,因为其他用户已经习惯了这种格式,并且在使用元素键时很容易发现。

_KEY_NAME_
'-KEY_NAME-'

如果您有一个元素对象,要找到它的键,请访问该元素的成员变量。这假设您已经在变量中获得了元素。

.Key
text_elem = sg.Text('', key='-TEXT-')

the_key = text_elem.Key

默认键

如果您未能在元素上放置键,则会自动为您创建一个键。

对于,按钮上的文本是该按钮的键。元素将默认为文本的字符串(当启用事件并单击文本时)

Buttons
Text

如果元素是输入元素之一(将导致在返回值字典中生成条目)并且您未能指定一个,则将为其分配一个以数字 0 开头的数字。效果将如下如果即使使用字典,值也表示为列表。

菜单键

菜单项也可以有与之关联的键。有关这些特殊键的更多信息,请参阅菜单部分。它们与元素键不同。像所有元素一样,菜单元素具有这些元素键之一。各个菜单项键不同。

WRITE_ONLY_KEY 修饰符

WRITE_ONLY_KEY

有时您有用作输出的输入元素(例如 )。这些元素的内容可能会变得很长。您不需要“读取”这些元素,这样做可能会不必要地返回大量数据。

Multiline

要告诉 PySimpleGUI 您不希望元素在被调用时返回值,请将字符串添加到您的键名中。

Window.read
WRITE_ONLY_KEY

如果您的元素最初是这样定义的:

Multiline
sg.Multiline(size=(40,8), key='-MLINE-')

然后要关闭该元素的返回值,该元素将这样编写:

Multiline
sg.Multiline(size=(40,8), key='-MLINE-' + sg.WRITE_ONLY_KEY)

Key Errors – 关键错误恢复算法

在 PySimpleGUI 的主要 (tkinter) 端口中,从版本 4.27.0 开始(尚未在 PyPI 上……但在 GitHub 上作为 4.26.0.14+ 可用)

现在有 3 种对关键错误处理的控制和一个全新的关键报告时代。

SUPPRESS_ERROR_POPUPS = False
SUPPRESS_RAISE_KEY_ERRORS = False
SUPPRESS_KEY_GUESSING = False

您可以通过调用来修改这些值。

set_options
    sg.set_options(suppress_raise_key_errors=False, suppress_error_popups=False, suppress_key_guessing=False)

它们的基本定义是: – 禁止在 PySimpleGUI 本身中生成的错误弹出窗口不显示 – 如果未找到密钥或紧密匹配,则禁止引发密钥错误 – 如果您有密钥错误,则禁止密钥猜测算法

suppress_error_popups
suppress_raise_key_errors
suppress_key_guessing

保留定义的默认值(全部),这是关键错误的工作方式。

False

这是本例中使用的程序:

import PySimpleGUI as sg

def main():
    sg.set_options(suppress_raise_key_errors=False, suppress_error_popups=False, suppress_key_guessing=False)

    layout = [  [sg.Text('My Window')],
                [sg.Input(k='-IN-'), sg.Text(size=(12,1), key='-OUT-')],
                [sg.Button('Go'), sg.Button('Exit')]  ]

    window = sg.Window('Window Title', layout, finalize=True)

    while True:             # Event Loop
        event, values = window.read()
        print(event, values)
        if event == sg.WIN_CLOSED or event == 'Exit':
            break
        window['-O U T'].update(values['-IN-'])
    window.close()

def func():

    main()

func()

有几点需要注意:

  • 调用了多个级别的函数,而不仅仅是一个平面程序
  • 明确定义了 2 个键,此时两者都是文本(我们稍后会更改它们)
  • 有 2 个查找发生,一个与window另一个values

此键错误恢复算法仅适用于用于在窗口内查找键的元素键。键查找是一个普通的字典,因此该查找没有做任何花哨的事情。

values
————————

a key

1 get the value of the element

Input(key=’mykey’)

values[‘mykey’]

2. Find the element object window [‘key ‘] through the key

3 update the value of the element

Window [‘key ‘] (value to be updated)

window[‘key’]。update()

four

Suppose you have a window with a grid of input elements. You can use their row and column positions as keys (tuples)

key=(row, col)

Then, when you read the variable returned to you from the call, the key in the variable will be anything you use to create the element. In this case, you read the value as:

values
Window.read()
values
values[(row, col)]

Specification of 5key

Most of the time, they are simple text strings. In the demo program, the key is written according to the following Convention: (all uppercase letters at the beginning and end of the underscore) or the recent convention is to use dashes at the beginning and end (for example). You don’t have to follow the Convention, but it’s good to follow the Convention, because other users are used to this format and can easily find it when using element keys.

_KEY_NAME_
'-KEY_NAME-'

text

You will find information about the element and all other classes and functions in the call reference tab of the document.

An element is a building block for creating a window. Some GUI APIs use the term “widget” to describe these graphical elements. Therefore, it is clear when referring to the pysimplegui element and the widget of the underlying GUI framework. Pysimplegui elements map to GUI framework widgets, usually in a one-to-one manner. For example, a text element is implemented in Tkinter using a label widget.

Element table in Tkinter port

Each port of the pysimplegui has a set of core elements and port specific elements. Some port specific elements include the dial element in the QT port and the pane element in the Tkinter port.

元素名称 别名 tkinter 小部件 描述
文本 T,文本 tk.标签 一行或多行文本
输入 我,在,输入文本 tk.Entry 单行文本输入
组合 DD, Drop, DropDown, InputCombo    
选项菜单 输入选项菜单    
多行 ML, 多线    
输出      
收音机 R,拉德    
复选框 CB、CBox、检查    
旋转 Sp    
按钮 B, Btn    
图片 我是    
帆布      
柱子 科尔    
框架 神父    
标签      
选项卡组      
窗格      
图形 G    
滑块 SL    
列表框 LB, LBox    
菜单 菜单栏,菜单栏    
菜单栏自定义      
按钮菜单 BM, B菜单    
标题栏      
进度条 PBar, Prog, 进展    
桌子      
     
垂直分隔符 VSep, VSeparator    
水平分隔符 HSep,HS分离器    
状态栏 酒吧    
尺寸握把 SGrip    
P,拉伸    
副推 副总裁,VStretch    
尺寸测量仪      

Layout auxiliary function

Your window layout consists of a list of elements. In addition to elements, these layout help functions may also appear in layout definitions

布局助手 描述
别针 将元素“固定”到布局中的某个位置。如果元素从不可见过渡到可见,则 pin 确保元素位于正确的位置
顶部 将元素或元素行垂直对齐到行的顶部
底部 将元素或元素行垂直对齐到行的底部
中心 将元素或元素行垂直对齐到行的中心
  • text
  • Single line input
  • Includes the following types of buttons:
    File browsing
    Folder browsing
    Calendar selector
    Date Pickers
    read window
    Close the window (buttons and all shortcut buttons)
    Immediate
  • File browsing
  • Folder browsing
  • Calendar selector
  • Date Pickers
  • read window
  • Close the window (buttons and all shortcut buttons)
  • Immediate

key

< strong > in pysimplegui, key is a very important concept

If you’re going to do anything beyond the basics with your GUI, you need to know the keys.

You can think of a key as the name of an element. Or “identifier”. This is a way for you to identify and discuss elements using the pysimplegui library. It is exactly the same as the dictionary key. They must be unique to the window.

Specify a key when creating an element with parameters.

key

Keys are used as follows: * specify * to return as an event when creating an element. If an element causes an event, its key will be updated (changed) using * in the dictionary returned from * to the element in the window

values
window.read()

After you put the key into the definition of the element, the value returned from it will use the key to tell you the value. For example, if you have an input element in your layout:

window.read

Input(key='mykey')

Your reading looks like this:

event, values = Read()

Then to get the input value from the read, it will be:

values['mykey']

If you want to call update on an element, you can also use the same key. See the update element section for this usage. To find an element object with a given element key, you can call the window method (also written as,) or use a more common search mechanism:

find_element
FindElement
element
window['key']

Although you will often see keys written as strings in the examples in this document, you should know that keys can be < strong > analyzing < / strong >.

Suppose you have a window with a grid of input elements. You can use their row and column positions as keys (tuples)

key=(row, col)

Then, when you read the variable returned to you from the call, the key in the variable will be anything you use to create the element. In this case, you read the value as:

values
Window.read()
values
values[(row, col)]

Most of the time, they are simple text strings. In the demo program, the key is written according to the following Convention: (all uppercase letters at the beginning and end of the underscore) or the recent convention is to use dashes at the beginning and end (for example). You don’t have to follow the Convention, but it’s good to follow the Convention, because other users are used to this format and can easily find it when using element keys.

_KEY_NAME_
'-KEY_NAME-'

If you have an element object, to find its key, access the element’s member variables. This assumes that you have obtained the element in the variable.

.Key
text_elem = sg.Text('', key='-TEXT-')

the_key = text_elem.Key

Default key

If you fail to place a key on the element, a key is automatically created for you.

For, the text on the button is the key of the button. The element defaults to the string of text (when the event is enabled and the text is clicked)

Buttons
Text

If the element is one of the input elements (which will cause an entry to be generated in the return value Dictionary) and you cannot specify one, it is assigned a number starting with the number 0. The effect will be as follows. If you use a dictionary, the value is represented as a list.

Menu key

Menu items can also have keys associated with them. For more information about these special keys, see the menu section. They are different from element keys. Like all elements, a menu element has one of these element keys. Each menu item key is different.

WRITE_ONLY_KEY 修饰符

WRITE_ONLY_KEY

Sometimes you use input elements as output (for example). The contents of these elements may become very long. You do not need to “read” these elements, which may unnecessarily return a large amount of data.

Multiline

To tell pysimplegui that you do not want the element to return a value when called, add a string to your key name.

Window.read
WRITE_ONLY_KEY

If your element was originally defined like this:

Multiline
sg.Multiline(size=(40,8), key='-MLINE-')

Then, to turn off the return value of the element, the element will be written as follows:

Multiline
sg.Multiline(size=(40,8), key='-MLINE-' + sg.WRITE_ONLY_KEY)

Key errors – key error recovery algorithm

In the main (Tkinter) port of pysimplegui, starting from version 4.27.0 (not yet on pypi… But available as 4.26.0.14 + on GitHub)

There are now three controls for critical error handling and a new era of critical reporting.

SUPPRESS_ERROR_POPUPS = False
SUPPRESS_RAISE_KEY_ERRORS = False
SUPPRESS_KEY_GUESSING = False

You can modify these values by calling.

set_options
    sg.set_options(suppress_raise_key_errors=False, suppress_error_popups=False, suppress_key_guessing=False)

Their basic definitions are: – prohibit the error pop-up window generated in pysimplegui itself from displaying – prohibit the key error from being raised if the key is not found or a close match – prohibit the key guessing algorithm if you have a key error

suppress_error_popups
suppress_raise_key_errors
suppress_key_guessing

Keep the defined default values (all), which is how critical errors work.

False

This is the program used in this example:

import PySimpleGUI as sg

def main():
    sg.set_options(suppress_raise_key_errors=False, suppress_error_popups=False, suppress_key_guessing=False)

    layout = [  [sg.Text('My Window')],
                [sg.Input(k='-IN-'), sg.Text(size=(12,1), key='-OUT-')],
                [sg.Button('Go'), sg.Button('Exit')]  ]

    window = sg.Window('Window Title', layout, finalize=True)

    while True:             # Event Loop
        event, values = window.read()
        print(event, values)
        if event == sg.WIN_CLOSED or event == 'Exit':
            break
        window['-O U T'].update(values['-IN-'])
    window.close()

def func():

    main()

func()

There are several points to note:

  • Functions at multiple levels are called, not just a flat program
  • Two keys are explicitly defined, both of which are text (we’ll change them later)
  • There are two lookups, one with window and the other with values

This key error recovery algorithm applies only to element keys used to find keys in the window. Key lookup is an ordinary dictionary, so it doesn’t do anything fancy.

values