导图社区 PySimpleGUI
这是一篇关于PySimpleGUI的思维导图,主要内容包括:Known Issues,Fun Stuff,Creating a Mac App File,Creating a Windows .EXE File,Elements,Common Element Parameters通用元素参数,Layouts版面,Window Object,Multithea
编辑于2024-08-06 11:11:57PySimpleGUI
Elements
Text
T == Txt == Text
基本元素。它显示文本。 layout = [[sg.Text('This is what a Text Element looks like')],]
Text(text, size=(None, None), auto_size_text=None, click_submits=False, enable_events=False, relief=None, font=None, text_color=None, background_color=None, justification=None, pad=None, key=None, right_click_menu=None, tooltip=None, visible=True)
Text - The text that's displayed size - Element's size click_submits - if clicked will cause a read call to return the key value of the button enable_events - same as click_submits relief - relief to use around the text auto_size_text - Bool. Change width to match size of text font - Font name and size to use text_color - text color background_color - background color justification - Justification for the text. String - 'left', 'right', 'center' pad - (x,y) amount of padding in pixels to use around element when packing key - used to identify element. This value will return as button if click_submits True right_click_menu - menu definition to display if right clicked tooltip - string representing tooltip
PySimpleGUI中的颜色采用两种格式之一-颜色名称或RGB值。 可以使用tkinter中定义的颜色名称或这种格式的RGB字符串指定各个颜色: "#RRGGBB" or "darkblue"
auto_size_text 当True值auto_size_text放置在“文本元素”上时,表示该元素的宽度应缩小为文本的宽度。默认设置为True。
enable_events 如果设置了参数,enable_events或者click_submits如果用户单击“文本”,则将得到一个事件。
如果要在创建元素后更改文本,字体或颜色,请使用Update方法。 Update(value = None, background_color=None, text_color=None, font=None, visible=None) value- 将文本元素设置为 background_color的新值 -new background color text_color-显示 字体的文本颜色 -用于显示可见字体的字体-可见性
Buttons
Save & Open Buttons
FilesBrowse
要一次打开多个文件,它将创建一个用“;”分隔的文件列表。
FileBrowse
文件浏览-与文件夹浏览相同,只是选择一个文件而不是选择一个文件夹。
FolderBrowse
文件夹浏览-单击后,将打开一个文件夹浏览对话框。文件夹浏览对话框的结果将写入窗口的输入字段之一。
SaveAs
保存文件
按钮所有补平值到位于窗口上的另一个元件。目标可以是Text元素或InputText元素或按钮本身。元素的位置由target函数调用中的变量指定;有两种形式。1. Key ;2. (row, column),使用键指定的目标将通过使用目标的键值找到其目标元素。这是“首选”方法。
如果使用(row, column)指定了目标,则它将利用网格系统。GUI中的行从0开始编号。目标可以指定为硬编码网格项,也可以相对于按钮指定。 (row, column)定位只能定位相同“容器”中的元素。容器是窗口,列和框架元素。列内的“文件浏览”按钮无法定位该列外的元素。 其缺省值target是(ThisRow, -1)。 ThisRow是一个特殊值,它告诉GUI使用与按钮相同的行。Y值-1表示按钮左侧的字段一。对于“文件或文件夹浏览”按钮,大多数情况下,其填充的字段通常位于按钮的左侧。(ThisRow,-1)表示同一行上按钮左侧的Element。
该InputText元件位于(1,0)...行1,列0的Browse按钮位于位置(2,0)。该按钮的目标可以是以下任何值: Target = (1,0) Target = (-1,0)
整个窗口的代码可能是: layout = [[sg.T('Source Folder')], [sg.In()], [sg.FolderBrowse(target=(-1, 0)), sg.OK()]] 或者,如果使用键,则代码为: layout = [[sg.T('Source Folder')], [sg.In(key='input')], [sg.FolderBrowse(target='input'), sg.OK()]]
File Types
FileBrowse和SaveAs按钮有一个名为额外的设置file_types。此变量用于过滤文件对话框中显示的文件。此设置的默认值为 FileTypes=(("ALL Files", "*.*"),) 这段代码产生一个窗口,其中“浏览”按钮仅显示.TXT类型的文件 layout = [[sg.In() ,sg.FileBrowse(file_types=(("Text Files", "*.txt"),))]]
Normal button that returns event
Closewindow
关闭窗口-常规按钮,例如“提交”,“取消”,“是”,“否”,关闭窗口,您需要使用CloseButton / CButton。
Realtime Buttons
通常,在向下单击按钮后放开鼠标按钮时,按钮被视为“已单击”。何时需要读取原始的上/下按钮值呢?一个典型的例子是机器人遥控器。使用GUI构建遥控器非常容易。每个方向的一个按钮是一个开始。也许是这样的:
该窗口有2种按钮类型。有正常的“读取按钮”(退出)和4个“实时按钮”。 这是从此窗口制作,显示和获取结果的代码: import PySimpleGUI as sg gui_rows = [[sg.Text('Robotics Remote Control')], [sg.T(' ' * 10), sg.RealtimeButton('Forward')], [sg.RealtimeButton('Left'), sg.T(' ' * 15), sg.RealtimeButton('Right')], [sg.T(' ' * 10), sg.RealtimeButton('Reverse')], [sg.T('')], [sg.Quit(button_color=('black', 'orange'))] ] window = sg.Window('Robotics Remote Control', auto_size_text=True).Layout(gui_rows) # # Some place later in your code... # You need to perform a Read or Refresh call on your window every now and then or # else it will apprear as if the program has locked up. # # your program's main loop while (True): # This is the code that reads and updates your window event, values = window.Read(timeout=0) if event is not None: print(event) if event == 'Quit' or values is None: break window.Close() # Don't forget to close your window! 此循环将读取按钮值并进行打印。单击“实时”按钮之一后,window.Read将返回与按下按钮上的名称或如果已为该按钮分配了按键的按键相匹配的按键名称。只要按钮保持按下状态,它将继续返回值。释放后,读取将返回超时事件,直到再次单击按钮。
Calendar chooser
打开图形日历以选择日期。
将弹出日历选择器窗口。所选日期将作为字符串返回。
Colorchooser
打开颜色选择器对话框
弹出一个标准的颜色选择器窗口。结果以元组形式返回。返回的值之一是RGB十六进制表示形式。
Button targets
FileBrowse,FolderBrowse,FileSaveAs,FilesSaveAs,CalendarButton,ColorChooserButton按钮所有填充值到位于窗口上的另一个元件。目标可以是Text元素或InputText元素。元素的位置由target函数调用中的变量指定。 目标有两种形式。 1.键 2.(行,列) 使用键指定的目标将通过使用目标的键值找到其目标元素。这是“首选”方法。 如果使用(行,列)指定了目标,则它将利用网格系统。GUI中的行从0开始编号。目标可以指定为硬编码网格项,也可以相对于按钮指定。 (行,列)定位只能定位相同“容器”中的元素。容器是窗口,列和框架元素。列内的“文件浏览”按钮无法定位该列外的元素。 其缺省值target是(ThisRow, -1)。 ThisRow是一个特殊值,它告诉GUI使用与按钮相同的行。Y值-1表示按钮左侧的字段一。对于“文件或文件夹浏览”按钮,大多数情况下,其填充的字段通常位于按钮的左侧。(ThisRow,-1)表示同一行上按钮左侧的Element。 如果(None, None)为目标选择了值,则按钮本身将保存信息。之后,可以使用按钮的键查询按钮的值。
以这个窗口为例: 该InputText元件位于(1,0)...行1,列0的Browse按钮位于位置(2,0)。该按钮的目标可以是以下任何值: Target = (1,0) Target = (-1,0) 整个窗口的代码可能是: layout = [[sg.T('Source Folder')], [sg.In()], [sg.FolderBrowse(target=(-1, 0)), sg.OK()]] 或者,如果使用键,则代码为: layout = [[sg.T('Source Folder')], [sg.In(key='input')], [sg.FolderBrowse(target='input'), sg.OK()]]
Read window
读取窗口-这是一个窗口按钮,将读取所有输入字段的快照,但是在单击窗口后不会关闭该窗口。
Custom Buttons
并非所有按钮均创建相同。关闭窗口的按钮与从窗口返回而不关闭窗口的按钮不同。如果要定义自己的按钮,通常将使用Button元素来执行此操作,Button单击该按钮时会关闭窗口。 layout = [[sg.Button('My Button')]]
通过更改button_text按钮调用中的参数,可以更改所有按钮的文本。读取窗口时将返回此文本。该文本将告诉您单击了哪个按钮。但是,您也可以在按钮上使用键,这样它们将是唯一的。如果仅使用文本,则您将永远无法在同一窗口中使用相同文本的两个按钮。 layout = [[sg.Button('My Button', key='_BUTTON_KEY_')]] 在这种布局下,Window.Read()单击按钮后从呼叫返回的事件将是“ _BUTTON_KEY_”
大多数程序将组合使用快捷方式按钮调用(提交,取消等),使窗口保持打开状态的普通按钮和单击时关闭窗口的关闭按钮。 有时,同一功能有多个名称。这仅仅是为了使程序员的工作更快,更轻松。或者,它们是不再使用但保留的旧名称,以使现有程序不会中断。
The 4 primary windows of PySimpleGUI buttons and their names
Button= ReadButton = RButton = ReadFormButton CloseButton = CButton RealtimeButton DummyButton
Button Element Shortcuts
OK Ok Submit Cancel Yes No Exit Quit Help Save SaveAs FileBrowse FilesBrowse FileSaveAs FolderBrowse
如果您希望不关闭窗口的Submit()按钮,可以将其写为CloseButton('Submit')or。CButton('Submit')
使用的最基本的Button元素调用是 Button layout = [[sg.Button('Ok'), sg.Button('Cancel')]]
Button Images
借助一些按钮图像来制作漂亮的用户界面。按钮图片必须为PNG或GIF格式。用图像制作按钮时,请将按钮背景设置为与背景相同的颜色。您可以将按钮颜色设置为TRANSPARENT_BUTTON,以使其融合到背景中。请注意,此值当前与Windows上默认系统背景的颜色相同。如果要将按钮背景色设置为当前系统默认值,请使用值COLOR_SYSTEM_DEFAULT作为背景色。
本示例来自Demo Media Player.py示例程序。由于它是一个非阻塞按钮,因此定义为RButton。您还可以使用将图像放置在阻止按钮上Button。 sg.Button('Restart Song', button_color=sg.TRANSPARENT_BUTTON, image_filename=image_restart, image_size=(50, 50), image_subsample=2, border_width=0) 三个参数用于按钮图像。 image_filename-文件名,可以是相对路径; image_size-图像文件的大小(以像素为单位); image_subsample-大小除以的数量, 2表示您的图像将是尺寸的1/2, 3表示1/3。
The ENTER key
ENTER键是Windows数据输入的重要部分。长期以来,使用Enter键来快速提交窗口。PySimpleGUI通过将ENTER键绑定到关闭或读取窗口的第一个按钮来实现此目的。
可以将Enter键“绑定”到特定按钮,以便在按下该键时,它会使窗口返回,就像单击该按钮一样。这是使用bind_return_key按钮调用中的参数完成的。如果窗口上有多个按钮,则使用“关闭”窗口或“读取”窗口类型的“第一”按钮。首先通过从上至下,从左至右扫描窗口来确定。
Button(button_text='' button_type=BUTTON_TYPE_CLOSES_WIN target=(None, None) tooltip=None file_types=(("ALL Files", "*.*"),) initial_folder=None disabled = False image_filename=None image_data=None image_size=(None, None) image_subsample=None border_width=None size=(None, None) auto_size_button=None button_color=None default_value = None font=None bind_return_key=False focus=False pad=None key=None, visible=True):
button_text - Text to be displayed on the button button_type - You should NOT be setting this directly target - key or (row,col) target for the button tooltip - tooltip text for the button file_types - the filetypes that will be used to match files initial_folder - starting path for folders and files disabled = Bool If True button is disabled image_filename - image filename if there is a button image image_data - in-RAM image to be displayed on button image_size - size of button image in pixels image_subsample - amount to reduce the size of the image border_width - width of border around button in pixels size - size in characters auto_size_button - True if button size is determined by button text button_color - (text color, backound color) default_value - initial value for buttons that hold information font - font to use for button text bind_return_key - If True the return key will cause this button to fire focus - if focus should be set to this button pad - (x,y) padding in pixels for packing the button key - key used for finding the element
Button Methods
Update(text=None, button_color=(None, None), disabled=None, image_data=None, image_filename=None, visible=None) GetText() Update - Change the button element text - sets button text button color - (text, background) disabled - if True disables the button image_data - sets button image to in-ram image image_filename - sets button image using a file GetText - Returns the current text shown on a button
ButtonMenu
ButtonMenu元素产生独特的效果。这是一个按钮,单击后会显示一个菜单。这就像单击MenuBar上的顶级菜单项之一。结果,菜单定义采用普通菜单定义中单个菜单项的格式。正常的菜单定义是列表列表。该定义是这些列表之一。 这是一个示例定义: ['Menu', ['&Pause Graph', 'Menu item::optional_key']] 通常,第一个字符串指定菜单栏上显示的内容。在这种情况下,不使用该值。您可以使用另一个参数button_textparm 来设置按钮的文本。
ButtonMenu( button_text, menu_def, tooltip=None, disabled=False, image_filename=None, image_data=None, image_size=(None, None), image_subsample=None, border_width=None, size=(None, None), auto_size_button=None, button_color=None, font=None, pad=None, key=None, visible=True, size_px=(None,None)): 此元素的一种用法是制作一个带有彩色背景的“假菜单栏”。普通菜单栏不能更改其背景颜色。ButtonMenus并非如此。
ButtonMenus的返回值通过返回值字典发送。如果做出选择,则将生成一个事件,该事件将等于ButtonMenu的键值。使用该键值来查找用户选择的值。这与菜单栏元素的机制相同,但与弹出菜单(单击鼠标右键)不同。
Window
Window.FindElement(key) Shortcut Window[key]
Fonts
Color
color name or RGB value
auto_size_text
当True值auto_size_text放置在“文本元素”上时,表示该元素的宽度应缩小为文本的宽度。
Text('', key='_TXTOUT_)将创建一个Text长度为0 的元素。如果您尝试输出5个字符的字符串,则由于空间不足,该字符串将不会显示在窗口中。补救措施是将大小手动设置为您希望输出的大小.Text('', size=(15,1), key='_TXTOUT_)创建一个Text可以容纳15个字符的元素。
Multiline
此元素同时用作输入和输出元素。 layout = [[sg.Multiline('This is what a Multi-line Text Element looks like', size=(45,5))]]
Multiline( default_text='', enter_submits=False, disabled=False, autoscroll=False, size=(None, None), auto_size_text=None, background_color=None, text_color=None, change_submits=False, enable_events=False, do_not_clear=False, key=None, focus=False, font=None, pad=None, tooltip=None right_click_menu=None, visible=True)
default_text - Text to display in the text box change_submits - Bool. If True, pressing Enter key submits window anable_events - Bool. same as change_submits autoscroll - Bool. Causes "cursor" to always be at the end of the text size - Element's size right_click_menu - menu definition to displat if right clicked auto_size_text - Bool. Change width to match size of text
Update( value=None, disabled=None, append=False, font=None, text_color=None, background_color=None) Update(self, value=None, disabled=None, append=False, font=None, text_color=None, background_color=None)value=None, disabled=None, append=False):
Output
输出重新路由Stdout到滚动的文本框。 无论您打印什么,都会在此窗口中显示。 请注意,只有调用window.Read或window.Refresh才能看到打印的内容。如果要立即查看打印的内容,请在打印语句后立即调用window.Refresh()。 layout = [[sg.Output(size=(80,10)]]
Output( size=(None, None), background_color=None, text_color=None, pad=None, font=None, tooltip=None, right_click_menu=None, key=None, visible=True) size-输出元素的大小(宽度,高度),以字符为单位。现在,您应该已经非常熟悉这些参数。如果没有,请阅读其他元素或了解通用参数。
Input
文字输入元素| InputText == Input == In layout = [[sg.InputText('Default text')]]
这些构成了窗口定义的大部分。元素级别的可选变量将覆盖窗口级别的值(例如size,在元素中指定)。所有输入元素都会在返回值列表中创建一个条目。文本输入元素在返回的项目列表中创建一个字符串。 文本输入元素快捷方式(输入,输入) layout = [[sg.InputText('Default text')]]
def InputText(default_text ='', size=(None, None), disabled=False, auto_size_text=None, password_char='', justification=None, background_color=None, text_color=None, font=None, tooltip=None, change_submits=False do_not_clear=False, key=None, focus=False, right_click_menu=None, pad=None, vitible=True):
default_text - Text initially shown in the input box size - (width, height) of element in characters auto_size_text- Bool. True is element should be sized to fit text disabled - Bool If True the input is disabled password_char - Character that will be used to replace each entered character. Setting to a value indicates this field is a password entry field background_color - color to use for the input field background text_color - color to use for the typed text font - font used for the element tooltip - what is shown when hovered over element (doesn't appear to work) change_submits - if True, will cause a Window.Read to return if a button fills in the value do_not_clear - Bool. Normally windows clear when read, turn off clearing with this flag. key = Dictionary key to use for return values focus = Bool. True if this field should capture the focus (moves cursor to this field) pad - amount of room in pixels to leave around the element
可以调用两种方法: Input.Update(new_Value) - sets the input to new_value Input.Get() - returns the current value of the field. 速记功能,这些功能相当于InputText是Input和In do_not_clear 参数 重要提示 -这使很多人绊倒。如果未设置do_not_clear参数,则事件发生时,输入字段将清除。该行为是“窗体”样式窗口的开发。假设您要清除该字段。如果您正在编写聊天程序,那么您会很感激。其余的人,很抱歉。 TextInput方法 Update(value=None, disabled=None): Get() 更新-更改元素 值-新值以显示在 禁用的字段中 -如果为True将禁用元素 Get-返回元素的当前值(您也可以通过调用Read获得)
Combo
组合元素| Combo == InputCombo == DropDown == Drop 也称为下拉列表。仅必需的参数是选项列表。返回值是一个与GUI上可见的字符串匹配的字符串。 layout = [[sg.Combo(['choice 1', 'choice 2'])]]
InputCombo(values, , default_value=None size=(None, None) auto_size_text=None background_color=None text_color=None change_submits=False enable_events=False readonly=True disabled=False key=None pad=None tooltip=None visible=True)
values - Choices to be displayed. List of strings default_value - which value should be initially chosen size - (width, height) of element in characters auto_size_text - Bool. True if size should fit the text length background_color - color to use for the input field background text_color - color to use for the typed text change_submits - Bool. If set causes Read to immediately return if the selected value changes disabled - Bool. If set will disable changes readonly - Bool. If set user cannot change the values to choose from key - Dictionary key to use for return values pad - (x,y) Amount of padding to put around element in pixels tooltip - Text string. If set, hovering over field will popup the text 快捷功能-组合,下拉,拖放
组合方法 Update(value=None, values=None, set_to_index=None, disabled=None, readonly=None) 值-更改哪个值为当前选定的 值-更改选项列表 set_to_index-将选择更改为特定选项 禁用-如果为True将禁用元素 只读-如果为True将使元素只读
Listbox
在大多数GUI中都可以找到类似的标准列表框。请注意,此元素的返回值将是结果列表,而不是单个result。这是因为用户可以从列表中选择多个项目(如果您设置了正确的模式)。 layout = [[sg.Listbox(values=['Listbox 1', 'Listbox 2', 'Listbox 3'], size=(30, 6))]]
列表框可能导致窗口从Read调用返回。如果enable_events设置了该标志,则当用户进行选择时,读取立即返回。
ListBoxes可以导致Reads返回的另一种方法是是否设置了标志bind_return_key。如果为True,则在选择条目时用户按下返回键,则Read返回。同样,如果设置了此标志,则如果用户双击一个条目,它将从读取中返回。
Listbox(values default_values=None select_mode=None change_submits=False bind_return_key=False size=(None, None) disabled = False, auto_size_text=None font=None background_color=None text_color=None key=None pad=None right_click_menu=None tooltip=None, visible=True):
values - Choices to be displayed. List of strings select_mode - Defines how to list is to operate. Choices include constants or strings: Constants version: LISTBOX_SELECT_MODE_BROWSE LISTBOX_SELECT_MODE_EXTENDED LISTBOX_SELECT_MODE_MULTIPLE LISTBOX_SELECT_MODE_SINGLE - the default Strings version: 'browse' 'extended' 'multiple' 'single' change_submits - if True, the window read will return with a button value of '' bind_return_key - if the focus is on the listbox and the user presses return key, or if the user double clicks an item, then the read will return size - (width, height) of element in characters disapled - Bool. If True element is disabled auto_size_text - Bool. True if size should fit the text length background_color - color to use for the input field background font - font to use for items in list text_color - color to use for the typed text key - Dictionary key to use for return values and to find element pad - amount of padding to use when packing tooltip - tooltip text
该select_mode选项可以是字符串或定义为变量的常量值。一般来说,字符串用于这些类型的选项。 列表框可能导致窗口从Read调用返回。如果设置了标志change_submits,则当用户进行选择时,读取立即返回。 ListBoxes可以导致Reads返回的另一种方法是是否设置了标志bind_return_key。如果为True,则在选择条目时用户按下返回键,则Read返回。同样,如果设置了此标志,则如果用户双击一个条目,它将从读取中返回。
列表框方法 Update(values=None, disabled=None) SetValue(values) GetListValues() 更新-更改元素 值- 禁用新的选择列表 -如果为True则禁用元素 SetValue-将选择设置为一个或多个值 GetListValues-返回值列表以供选择
Slider
滑块元素 滑块具有几个特定于滑块的设置以及外观设置。示例包括orientation和range设置。
layout = [[sg.Slider(range=(1,500), default_value=222, size=(20,15), orientation='horizontal', font=('Helvetica', 12))]]
Qt和tkinter滑块之间存在重要区别。在Qt上,滑块值必须是整数,而不是浮点数。如果您希望滑块从0.1变为1.0,则使滑块从1变为10并除以10。
Slider(range=(None,None), default_value=None, resolution=None, orientation=None, border_width=None, relief=None, change_submits=False, disabled=False, size=(None, None), font=None, background_color=None, text_color=None, key=None, pad=None, tooltip=None, visible=True)
range - (min, max) slider's range default_value - default setting (within range) resolution - how much each 'tick' should represent. Default = 1 orientation - 'horizontal' or 'vertical' ('h' or 'v' work) border_width - how deep the widget looks relief - relief style. Values are same as progress meter relief values. Can be a constant or a string: RELIEF_RAISED= 'raised' RELIEF_SUNKEN= 'sunken' RELIEF_FLAT= 'flat' RELIEF_RIDGE= 'ridge' RELIEF_GROOVE= 'groove' RELIEF_SOLID = 'solid' size - (width, height) of element in characters disabled - Bool If True slider is disabled auto_size_text - Bool. True if size should fit the text background_color - color to use for the input field background text_color - color to use for the typed text change_submits - causes window read to immediately return if the checkbox value changes key- Dictionary key to use for return values tooltip - Tooltip to display when hovered over wlement
Qt滑杆 Qt和tkinter滑块之间存在重要区别。在Qt上,滑块值必须是整数,而不是浮点数。如果您希望滑块从0.1变为1.0,则使滑块从1变为10并除以10。这是一件容易的数学事情,没什么大不了的。只是处理它。。。您毕竟是在编写软件。大概您知道如何做这些事情。;-)
滑块方法 Update(self, value=None, range=(None, None), disabled=None, visible=None): 值-将当前选择设置为值 范围- 禁用有效值的范围更改 -如果为True则禁用元素
Radio Button
创建一个分配给一组单选按钮的单选按钮。一次只能选择该组中的一个按钮。 layout = [ [sg.Radio('My first Radio!', "RADIO1", default=True), sg.Radio('My second radio!', "RADIO1")] ]
Radio(text, group_id, default=False, size=(None, None), disabled = False, auto_size_text=None, font=None, background_color = None, text_color = None, key = None, pad = None, tooltip = None, visible=True)
text - Text to display next to button group_id - Groups together multiple Radio Buttons. Can be any value default - Bool. Initial state size - (width, height) size of element in characters auto_size_text - Bool. True if should size width to fit text font - Font type and size for text display background_color - color to use for the background text_color - color to use for the text key - Dictionary key to use for return values pad - padding around element tooltip - tooltip to show when mouse hovered over element
Radio Button Methods Update(value=None, disabled=None, visible=None) value - bool - if True change to selected disabled - if True disables the element
Checkbox
复选框元素| CBox == CB == Check 复选框元素类似于单选按钮元素。它们返回一个布尔值,指示是否已对其进行检查。 layout = [[sg.Checkbox('My first Checkbox!', default=True), sg.Checkbox('My second Checkbox!')]]
Checkbox(text, default=False, size=(None, None), auto_size_text=None, font=None, background_color = None, text_color = None, change_submits = False disabled = False, key = None, pad = None, tooltip = None, visible=True):
text - Text to display next to checkbox default- Bool + None. Initial state. True = Checked, False = unchecked, None = Not available (grayed out) size - (width, height) size of element in characters auto_size_text- Bool. True if should size width to fit text disabled - Bool. If True element is disabled font- Font type and size for text display background_color - color to use for the background text_color - color to use for the typed text change_submits - causes window read to immediately return if the checkbox value changes key = Dictionary key to use for return values pad - Padding around element in window tooltip - text to show when mouse is hovered over element
Checkbox Methods Update(value=None, disabled=None, visible=None) Get() Update - changes the element value - Bool if True checks the checkbox disabled - if True disables the element Get - returns current state
Spin
自旋元素 向上/向下微调器控件。有效值将作为列表传递。 layout = [[sg.Spin([i for i in range(1,11)], initial_value=1), sg.Text('Volume level')]]
Spin(values, intiial_value=None, disabled = False, size=(None, None), change_submits = False, auto_size_text=None, font=None, background_color = None, text_color = None, key = None. pad = None, tooltip = None, visible=True):
values - List of valid values initial_value - String with initial value size - (width, height) size of element in characters auto_size_text - Bool. True if should size width to fit text font - Font type and size for text display disabled - Bool. If True element is disabled background_color - color to use for the background text_color - color to use for the typed text change_submits - causes window read to immediately return if the spinner value changes key = Dictionary key to use for return values pad - padding around element in the window tooltip - text to show when mouse hovered over element
Qt差异- values是一个范围! 请注意,Qt不允许使用任意微调器值。使用PySimpleGUI-tkinter,您可以在列表中包含任何值。在Qt中,它们必须是整数。是的,有点烂。我在做这个工作。 在Qt值上是表示范围的元组。在纯PySimpleGUI上,此值是项目列表。确保在普通版本中,您使用[]将项目指定为列表,而不使用()将其指定为生成器。
Update Method Like other Elements, the Image Element has an Update method. Call Update if you want to change the image. def Update(self, filename=None, data=None, visible=None): Choose either a filename or in-ram data image to use to replace current image
Image
图像元素 图像可以以PNG,GIF,PPM / PGM格式放置在窗口中。无法显示JPG,因为tkinter并不天真支持JPG。如果图像为JPG格式,则可以在调用PySimpleGUI之前使用Python Imaging Library(PIL)包将图像转换为PNG。
layout = [ [sg.Image(r'C:\PySimpleGUI\Logos\PySimpleGUI_Logo_320.png')], ]
您可以将动画GIF指定为图像,并可以通过调用来设置GIF动画UpdateAnimation。激动人心的东西!
您可以在不设置time_between_frames值的情况下调用该方法,该方法将显示一个框架并立即移至下一框架。这使您可以进行帧间计时。
Image(filename=None, data=None, data_base64=None, background_color=None, size=(None,None), pad=None, key=None, tooltip=None, click_submits=False, enable_events=False, visible=True, right_click_menu=None, size_px=(None,None) visible=True)
filename - file name if the image is in a file data - if image is in RAM (PIL format?) data_base64 - image in base64 format background_color - Color of background size - Size (Width, Height) of image in pixels pad - Padding around Element in the window key - Key used to find the element tooltip - text to show when mouse if hovered over image click_submits, enable_events - if True returns event when image is clicked visible - if False will create image as hidden size_px - size of image in pixels
UpdateAnimation 动画GIF的方法
从3.23版开始,您可以将动画GIF指定为图像,并可以通过调用设置GIF动画UpdateAnimation。激动人心的东西! UpdateAnimation(source, time_between_frames=0) source可以是文件名或 base64字节变量(不同于将文件名参数和base64参数分成2个参数的其他调用)。 time_between_frames是可选参数。它将跟踪帧更改之间的时间量,以使您获得平滑的动画。使用此参数,您可以根据需要多次调用该函数,并且仅在经过正确的时间后,该函数才会前进到下一帧。 您可以在不设置time_between_frames值的情况下调用该方法,该方法将显示一个框架并立即移至下一框架。这使您可以进行帧间计时。
VerticalSeparator
元素的用途有限,为完整性起见,比其他任何元素都包含更多。它将在元素之间画一条线。 当放置在跨越多行的列或元素之间时,效果最佳。如果在“普通”行上且元素只有1行高,则它将仅跨越该行。 VerticalSeparator(pad=None)
当放置在跨越多行的列或元素之间时,效果最佳。如果在“普通”行上且元素只有1行高,则它将仅跨越该行。
HorizontalSeparator
在Tyinter端口PySimpleGUI中,没有HorizontalSeparatorElement。一个将被添加为“存根”,以便代码可移植。它可能不会像StretchElement 一样无所作为。
在PySimpleGUI中获得水平线的一种简单方法是使用Text包含下划线的Element sg.Text('_'*30)
ProgressBar
用于构建自定义进度栏窗口。强烈建议您使用OneLineProgressMeter,它为您提供完整的进度表解决方案。进度表不容易使用,因为窗口必须是非阻塞的,并且调试起来很棘手。
将进度表纳入代码的最简单方法是使用OneLineProgressMeterAPI。这由一对函数OneLineProgressMeter和组成OneLineProgressMeterCancel。您可以通过使用当前值=最大值调用进度表来轻松取消它。这将把仪表标记为过期并关闭窗口。您已经在本自述文件的前面看到了OneLineProgressMeter调用。 sg.OneLineProgressMeter('My Meter', i+1, 1000, 'key', 'Optional message')
返回值OneLineProgressMeter是: True如果False用户单击“取消”按钮,关闭窗口或阀门达到最大值,则仪表正确更新 。
将进度表与PySimpleGUI一起使用的另一种方法是使用窗口中的ProgressBarElement 来构建自定义窗口。您需要将您的窗口作为非阻塞窗口运行。准备好更新进度条时,可以调用元素本身的UpdateBar方法ProgressBar。
import PySimpleGUI as sg # layout the window layout = [[sg.Text('A custom progress meter')], [sg.ProgressBar(10000, orientation='h', size=(20, 20), key='progressbar')], [sg.Cancel()]] # create the window` window = sg.Window('Custom Progress Meter', layout) progress_bar = window.FindElement('progressbar') # loop that would normally do something useful for i in range(10000): # check to see if the cancel button was clicked and exit loop if clicked event, values = window.Read(timeout=0) if event == 'Cancel' or event is None: break # update bar with loop value +1 so that bar eventually reaches the maximum progress_bar.UpdateBar(i + 1) # done with loop... need to destroy the window as it's still open window.Close()
Output
输出元素是Stdout的重定向。 如果您正在寻找一种快速添加在窗口内显示滚动文本的功能的方法,那么添加Output元素就变得一样快捷和容易。 任何“已打印”的内容都将显示在此元素中。 这是在窗口中显示滚动文本的“简单”方法。就像将Output Element放到窗口中,然后根据需要调用print一样简单。用户将在其窗口内看到文本的滚动区域。 重要事项 您print必须先致电window.Read或,才能看到自己的名字window.Refresh。如果要立即查看打印的内容,请window.Refresh()在打印语句后立即致电。 Output(size=(80,20))
这是使用Output元素的聊天窗口的完整解决方案。要显示接收到的数据,您只需简单地“打印”它,它就会显示在输出区域中。您会在包括HowDoI应用程序在内的多个演示程序中找到使用此技术的方法。 import PySimpleGUI as sg def ChatBot(): layout = [[(sg.Text('This is where standard out is being routed', size=[40, 1]))], [sg.Output(size=(80, 20))], [sg.Multiline(size=(70, 5), enter_submits=True), sg.Button('SEND', button_color=(sg.YELLOWS[0], sg.BLUES[0])), sg.Button('EXIT', button_color=(sg.YELLOWS[0], sg.GREENS[0]))]] window = sg.Window('Chat Window', layout, default_element_size=(30, 2)) # ---===--- Loop taking in user input and using it to query HowDoI web oracle --- # while True: event, value = window.read() if event == 'SEND': print(value) else: break window.close() ChatBot()
Column
从2.9版开始,您将可以使用Column Element进行更复杂的布局。将列视为窗口中的一个窗口。而且,是的,如果需要,您可以在列中有一个列。 列的指定方式与窗口,列表列表完全相同。 Column( layout, background_color=None, size=(None, None), pad=None, scrollable=False, vertical_scroll_only=False, right_click_menu=None, key=None, visible=True) 当您的元素左侧的高度大于1行,而右侧的单行元素时,则需要使用列。这是这种布局的示例:
这段代码产生了上面的窗口。 import PySimpleGUI as sg # Demo of how columns work # window has on row 1 a vertical slider followed by a COLUMN with 7 rows # Prior to the Column element, this layout was not possible # Columns layouts look identical to window layouts, they are a list of lists of elements. window = sg.Window('Columns') # blank window # Column layout col = [[sg.Text('col Row 1')], [sg.Text('col Row 2'), sg.Input('col input 1')], [sg.Text('col Row 3'), sg.Input('col input 2')], [sg.Text('col Row 4'), sg.Input('col input 3')], [sg.Text('col Row 5'), sg.Input('col input 4')], [sg.Text('col Row 6'), sg.Input('col input 5')], [sg.Text('col Row 7'), sg.Input('col input 6')]] layout = [[sg.Slider(range=(1,100), default_value=10, orientation='v', size=(8,20)), sg.Column(col)], [sg.In('Last input')], [sg.OK()]] # Display the window and get values # If you're willing to not use the "context manager" design pattern, then it's possible # to collapse the window display and read down to a single line of code. event, values = sg.Window('Compact 1-line window with column').Layout(layout).Read() sg.Popup(event, values, line_width=200)
进行更复杂的布局。将列视为窗口中的一个窗口,可以在列中有一个列。像所有“容器元素”一样,以与窗口完全相同的方式将列指定为列表列表。当您要在一行中指定多个元素时,需要使用列。
通过设置元素的行Column的justification、Column的element_justification参数来证明其中的全部内容,使用这些参数,可以创建内容居中的窗口,以前这很难做到,当前仅在主要的PySimpleGUI端口中可用。
SizerElement 是4.3中的新功能。此元素用于帮助创建特定大小的容器。可以将其放置在以下PySimpleGUI项目中:Column、Frame、Tab、Window,实现Sizer非常简单。它返回一个空Column元素,其填充值设置为传递给的值Sizer。因此,它不是一个类,而是一个类似于预定义按钮的“快捷功能”。
列元素具有1个必需参数和1个可选参数(布局和背景色)。设置背景色与设置窗口的背景色具有相同的效果,只不过它会影响列矩形。 Column(layout, background_color=None) 列的默认背景色与默认窗口背景色相同。如果更改窗口的外观,列背景将自动与窗口背景匹配。
Frame (Labelled Frames, Frames with a title)
框架的工作方式与“列”完全相同。您创建布局,然后用于初始化框架。就像Column元素一样,它是一个“容器元素”,其中包含一个或多个元素。
此代码创建一个带有Frame和2个按钮的窗口。 frame_layout = [ [sg.T('Text inside of a frame')], [sg.CB('Check 1'), sg.CB('Check 2')], ] layout = [ [sg.Frame('My Frame Title', frame_layout, font='Any 12', title_color='blue')], [sg.Submit(), sg.Cancel()] ] window = sg.Window('Frame with buttons', font=("Helvetica", 12)).Layout(layout)
子主题
注意“框架”布局看起来与窗口布局完全相同。窗口的工作方式与“列”和“框架”完全相同。它们都是“容器元素”。包含其他元素的元素。 这些容器元素可以嵌套到所需的深度。这是一个非常漂亮的功能,对吗?做了大量的工作,所以要感谢。递归代码并非易事。
Frame( title, layout, title_color=None, background_color=None, title_location=None, relief=DEFAULT_FRAME_RELIEF, size=(None, None), font=None, pad=None, border_width=None, key=None, tooltip=None, right_click_menu=None, visible=True)
def Frame(title - the label / title to put on frame layout - list of rows of elements the frame contains title_color - color of the title text background_color - color of background title_location - locations to put the title relief - type of relief to use size - size of Frame in characters. Do not use if you want frame to autosize font - font to use for title pad - element padding to use when packing border_width - how thick the line going around frame should be key - key used to location the element tooltip - tooltip text
Canvas
tkinter画布小部件是tkinter小部件中功能最强大的。尽管我尽最大努力将用户与与tkinter相关的任何事物完全隔离开来,但Canvas元素是一个例外。它可以与许多其他程序包集成,通常会产生出色的结果。
Canvas(canvas=None, background_color=None, size=(None, None), pad=None, key=None, tooltip=None, right_click_menu=None, visible=True)
Matploplib和Pyplot就是这样一种集成。有一个编写的演示程序,您可以将其用作设计模式,以了解在使用Canvas Widget后如何使用它。 def Canvas(canvas - a tkinter canvasf if you created one. Normally not set background_color - canvas color size - size in pixels pad - element padding for packing key - key used to lookup element tooltip - tooltip text
另一种获得此功能的方法,那就是通过Graph元素,它甚至是功能更强大的元素,因为它使用了Canvas,您可以在需要时直接访问Canvas。Graph元素具有许多Canvas元素不具备的绘制方法。
要从PySimpleGUI获取tkinter画布小部件,请按照以下步骤操作:1、将Canvas元素添加到窗口中;2、布局窗口;3、调用window.Finalize() -这是您不能忘记的关键步骤;4、通过使用键查找来查找Canvas元素;5、您的Canvas小部件对象将是found_element.TKCanvas;6、在画布上绘制到您内心的内容;7、调用 window.Read() -在您调用Read之前,画布上不会显示任何内容。
获取tkinter画布小部件的操作顺序为: figure_x, figure_y, figure_w, figure_h = fig.bbox.bounds # define the window layout layout = [[sg.Text('Plot test')], [sg.Canvas(size=(figure_w, figure_h), key='canvas')], [sg.OK(pad=((figure_w / 2, 0), 3), size=(4, 2))]] # create the window and show it without the plot window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI').Layout(layout).Finalize() # add the plot to the window fig_photo = draw_figure(window.FindElement('canvas').TKCanvas, fig) # show it all again and get buttons event, values = window.Read()
TKCanvas-不是方法而是属性。返回tkinter画布小部件
Graph
如果您曾经对绘制的某个表面上的(0,0)位置感到沮丧,请别担心,您的挫败感就在这里结束。您可以使用所需的任何坐标系进行绘制。将(0,0)放置在所需的任何位置,包括图表上的任何位置。您可以定义一个图,在X轴上所有负数都在-2.1和-3.5之间,在Y轴上所有负数都在-3到-8.2之间。
提供Graph元素需要3个值。他们是: 画布大小(以像素为单位) 坐标系的左下坐标,left (x,y) 坐标系的右上角坐标,right (x,y)
提供这些值之后,您可以通过创建“图形图”在整个图形上进行涂抹。创建图形图形,并通过调用以下方法获取图形,ID: 画圆-DrawCircle 牵引线-DrawLine 牵引点-DrawPoint 绘制矩形-DrawRectangle 绘制椭圆-DrawOval 画图-DrawImage
图方法 DrawLine(self, point_from, point_to, color='black', width=1) DrawPoint(self, point, size=2, color='black') DrawCircle(self, center_location, radius, fill_color=None, line_color='black') DrawOval(self, top_left, bottom_right, fill_color=None, line_color=None) DrawArc(self, top_left, bottom_right, extent, start_angle, style=None, arc_color='black') DrawRectangle(self, top_left, bottom_right, fill_color=None, line_color=None) DrawText(self, text, location, color='black', font=None, angle=0) Erase(background_color) DeleteFigure(figure_id) Update() Move(self, x_direction, y_direction) MoveFigure(self, figure, x_direction, y_direction) TKCanvas 所有的Drawing方法都返回一个“ Figure ”,可用于移动和删除该Figure
您可以通过向图形标识提供要移动的x,y值来在画布上移动图形。 graph.MoveFigure(my_circle, 10, 10)
您还将使用此ID删除绘制的单个图形: graph.DeleteFigure(my_circle)
Mouse Events Inside Graph Elements
如果您的Graph元素具有启用的事件,则可以接收鼠标单击事件。如果您另外 drag_submits 在创建GraphElement时启用,那么当您在窗口内“拖动”时,您还将获得事件。“拖动”定义为向下的鼠标左键,然后移动鼠标。 发生拖动事件时,该事件将成为“图形元素”的键。的 value 中的值返回字典当前鼠标的(X,Y)位置的一个元组。 这意味着您将获得事件的“流”。如果鼠标移动,您将获得至少1个事件,并且可能会超过1个事件。
Mouse Up Event for Drags
“鼠标向上移动”将为您生成一个事件,值: Graph_key + '+UP' 。因此,如果Graph Element的键为 '_GRAPH_' ,则释放鼠标按钮时将收到的事件是: '_GRAPH_+UP',在处理这些类型的字符串值时使用 .startswith 和 .endswith内置函数。
此处是一个例子 events 并且 values dictionary 这是通过点击和图形元素的内部拖动与键==“曲线图”中产生: graph {'graph': (159, 256)} graph {'graph': (157, 256)} graph {'graph': (157, 256)} graph {'graph': (157, 254)} graph {'graph': (157, 254)} graph {'graph': (154, 254)} graph {'graph': (154, 254)} graph+UP {'graph': (154, 254)}
Graph(canvas_size, graph_bottom_left, graph_top_right, background_color=None, pad=None, change_submits=False, drag_submits=False enable_events=False, key=None, tooltip=None, right_click_menu=None, visible=True)
Table
已知的Table 可视化问题。 一直存在一个难以捉摸的问题,即在单击表标题或其附近时,tkinter会变得疯狂,并在移动鼠标时不断调整列的大小。自从第一次发布该 Table 元素以来就存在此问题。它在版本4.3中修复。
从 Window.Read “表元素” 的调用返回的值是当前突出显示的行号的列表。
新的PySimpleGUIQt是添加的 Table 方法 Get 。此方法返回当前在GUI中显示的表。为了获得用户可能对该表进行的任何编辑,需要使用此方法。
Table( values, headings=None, visible_column_map=None, col_widths=None, def_col_width=10, auto_size_columns=True, max_col_width=20, select_mode=None, display_row_numbers=False, num_rows=None, row_height=None, font=None, justification='right', text_color=None, background_color=None, alternating_row_color=None, row_colors=None, vertical_scroll_only=True, size=(None,None), change_submits=False, enable_events=False, bind_return_key=False, pad=None, key=None, tooltip=None, right_click_menu=None, visible=True):
values- 表的数组 headings-表示标题的字符串列表(如果有) visible_column_map-布尔列表。如果为True,则显示该位置的列。默认为所有列 col_widths-列宽列表 def_col_width-默认列宽。默认为10 auto_size_columns-bool。如果True列宽由表内容确定,则 max_col_width-列的最大宽度。默认为25 select_mode-可以选择表行,但当前不执行任何操作 display_row_numbers-bool。如果为True,则在行旁边显示数字 num_rows =一次要显示的行数(与size [0]相同) row_height =行应高的像素数。通常将其保留为默认值 字体-表条目 对齐的字体 -左,右,居中 text_color- 交替行颜色的文本 颜色-如果设置将改变交替行的背景颜色 row_colors-表示(行号,颜色)的元组列表,例如row_colors = (((5,'white','blue'),(0,'red'),(15,'yellow')) vertical_scroll_only-如果True不会显示水平滚动条。注意-必须禁用以获得水平滚动条 background_color-单元格背景色 大小-(无,行数)-不使用,使用num_rows代替 enable_events-选定行时将返回“行选定”事件 change_submits-指示enable_events的旧方法 bind_return_key-如果双击或返回则返回事件行高亮显示时按下返回键填充 - 包装键的元素填充 -用于查找元素的键 工具提示-工具提示文本
从表元素读取返回值 从Window.Read“树元素” 的调用返回的值是当前突出显示的行号的列表。 更新通话 Update方法可用于更改已显示的表。该调用采用单个参数,值,这是要显示的新表。整个表被替换。 def Update(self, values=None): values 是一个包含行的表,就像创建表元素时传入的一样。
Tree
树元素和表元素是近亲。在表元素中找到的许多参数都适用于树元素。特别是标题信息,列宽等。与表不同,树没有标准格式。因此,必须构造传递到树元素的数据结构。这是使用TreeData类完成的。流程如下: 获取一个TreeData对象 将数据“插入”树中 将填充的TreeData对象传递给Tree元素
TreeData格式
def TreeData() def Insert(self, parent, key, text, values, icon=None)
要将数据“插入”到树中,将调用TreeData方法Insert。 Insert(parent_key, key, display_text, values) 要指示在树的开头插入,请使用父键“”。因此,树中的每个顶级节点都会有一个父节点=“” 此代码创建一个TreeData对象并填充3个值 treedata = sg.TreeData() treedata.Insert("", '_A_', 'A', [1,2,3]) treedata.Insert("", '_B_', 'B', [4,5,6]) treedata.Insert("_A_", '_A1_', 'A1', ['can','be','anything'])
请注意,您可以对display_text和keys使用相同的值。您唯一需要注意的是您不能重复按键。 读取窗口时,表格元素将返回用户选择的行的列表。如果未选择行,则该列表将为空。
如果您希望在树项旁边显示图标,请在的调用中指定该图标 Insert 。您使用可选 icon 参数传入文件名或Base64字节字符串。
def Insert(self, parent, key, text, values, icon=None): """ Inserts a node into the tree. This is how user builds their tree, by Inserting Nodes This is the ONLY user callable method in the TreeData class :param parent: (Node) the parent Node :param key: (Any) Used to uniquely identify this node :param text: (str) The text that is displayed at this node's location :param values: List[Any] The list of values that are displayed at this node :param icon: Union[str, bytes] """
树元素和表元素是近亲。在表元素中找到的许多参数都适用于树元素。特别是标题信息,列宽等。 Tree( data=None, headings=None, visible_column_map=None, col_widths=None, col0_width=10, def_col_width=10, auto_size_columns=True, max_col_width=20, select_mode=None, show_expanded=False, change_submits=False, enable_events=False, font=None, justification='right', text_color=None, background_color=None, num_rows=None, row_height=None, pad=None, key=None, tooltip=None, right_click_menu=None, visible=True)
class Tree(data=None - data in TreeData format headings=None - list of strings representing your headings visible_column_map=None - list of bools indicating which columns to display col_widths=None - list of column widths col0_width=10 - width of the first column which has the text data def_col_width=10 - default column width auto_size_columns=True - if true will autosize columns (currenly only sizes to col heading width) max_col_width=20 - max width for columns in characters select_mode=None - not yet used show_expanded - Bool - if True the tree will be fully expanded when shown font=None - the display font justification='right' - justification for data display text_color=None- color of text to display background_color=None - background color num_rows=None - number of rows to display row_height=None - height of rows in pixels pad=None - element padding key=None - key for element tooltip=None - tooltip
Tab and Tab Group
PySimpleGUI的另一个“容器元素”。就像窗口包含布局一样,它能够“包含”布局。其他容器元素包括Column和Frame元素。 就像窗口和其他容器元素一样,Tab元素的布局也包含任何所需布局中元素的任何所需组合。您可以在Windows等内部的“列”中的“选项卡”内部设置选项卡。
Tab布局看起来与Window布局完全一样,即它们是Elements列表的列表。 将Tab元素放入窗口的方式与所有其他元素不同。 您不能将选项卡直接放置在窗口的布局中。 选项卡包含在TabGroups中。它们不会放置在其他布局中。要将选项卡放入窗口,请首先将TabElement放入TabGroupElement中,然后将TabGroupElement放入Window布局中。
首先,我们有选项卡布局定义。它们反映了您在屏幕快照中看到的内容。选项卡1中包含1个文本元素。选项卡2具有文本和输入元素。 tab1_layout = [[sg.T('This is inside tab 1')]] tab2_layout = [[sg.T('This is inside tab 2')], [sg.In(key='in')]] 整个窗口的布局如下所示: layout = [[sg.TabGroup([[sg.Tab('Tab 1', tab1_layout), sg.Tab('Tab 2', tab2_layout)]])], [sg.RButton('Read')]]
窗口布局具有TabGroup,在Tab Group中是两个Tab元素。 关于所有这些容器元素要注意的一件重要事情……它们在布局上都带有“列表列表”。它们都有一个以[[ 您将要[[ ]]在调试选项卡式窗口时将此结构牢记在心。忽略一个或两个必要的[ 如前所述,旧选项卡仅限于仅在窗口级别。换句话说,选项卡的大小等于整个窗口的大小。“新样式”标签不是这种情况。这就是为什么当您发现旧代码不再适用于新的PySimpleGUI版本时不会感到沮丧的原因。值得花一些时间来转换代码。
Reading Tab Groups
当读取返回时,选项卡组将返回一个值。他们返回当前选择的选项卡。如果选择/更改了该组中的选项卡,则还可以设置一个change_submits参数,该参数会导致读取返回。属于切换到的选项卡的键或标题将作为值返回
Tab Element Methods
Update(disabled = None, visible=None)
ab元素的定义是 Tab(title, layout, title_color=None, background_color=None, font=None, pad=None disabled=False border_width=None key=None tooltip=None)
TabGroup的定义是 TabGroup(layout, title_color=None background_color=None font=None pad=None border_width=None change_submits = False key=None tooltip=None)
Pane
Pane Element是3.20版中的新功能,它是超酷的tkinter功能。您不会在PySimpleGUIQt中找到此对象,只有PySimpleGUI。很难描述这些事情之一。可以将它们视为可以滑动的“无标签的标签”。
Pane(pane_list, background_color=None, size=(None, None), pad=None, orientation='vertical', show_handle=True, relief=RELIEF_RAISED, handle_size=None, border_width=None, key=None, visible=True):
窗格元素的每个“窗格”必须是Column Element。该参数pane_list是列元素的列表。 如果您尝试内联声明所有内容,则调用可能会显得有些毛茸茸,如本例所示。 sg.Pane([col5, sg.Column([[sg.Pane([col1, col2, col4], handle_size=15, orientation='v', background_color=None, show_handle=True, visible=True, key='_PANE_', border_width=0, relief=sg.RELIEF_GROOVE),]]),col3 ], orientation='h', background_color=None, size=(160,160), relief=sg.RELIEF_RAISED, border_width=0) 将这些内容与可见性结合在一起,就可以创建一个有趣的界面,整个窗格从视图中隐藏起来,直到用户需要为止。这是产生“动态”窗口的一种方法
指定“图标”时,可以使用3种不同的格式。-文件名 -base64字节字符串*' -内存中位图或其他“原始”图像 filename data_base64data 您将在initialize语句和Update方法上找到3个用于指定这3个选项的参数。
Colors
从2.5版开始,您可以更改窗口和Elements的背景颜色。
尽管您可以逐个元素或逐个窗口级别进行操作,但到目前为止,最简单的方法是调用SetOptions。 请注意,一旦更改了这些选项,它们就会在程序的其余执行过程中被更改。在您将其更改为其他名称(可能是系统默认颜色)之前,所有窗口均具有该外观。 此调用设置所有不同的颜色选项。 SetOptions(background_color='#9FB8AD', text_element_background_color='#9FB8AD', element_background_color='#9FB8AD', scrollbar_color=None, input_elements_background_color='#F7F3EC', progress_meter_color = ('green', 'blue') button_color=('white','#475841'))
SystemTray
这是仅PySimpleGUIQt和PySimpleGUIWx功能。不知道使用tkinter的方法。Qt和Wx实现的SystemTray源代码相同。您只需更改导入语句即可切换框架。
除了运行普通窗口外,现在还可以在系统托盘中放下一个图标,您可以阅读该图标来获取菜单事件。有一个新的SystemTray对象,其用法与Window对象非常相似。您首先得到一个,然后执行读取以获取事件。
这是SystemTray对象的定义。 SystemTray(menu=None, filename=None, data=None, data_base64=None, tooltip=None): ''' SystemTray - create an icon in the system tray :param menu: Menu definition :param filename: filename for icon :param data: in-ram image for icon :param data_base64: basee-64 data for icon :param tooltip: tooltip string ''' 您会注意到,有3种不同的方法来指定图标图像。base-64参数允许您在.py代码中定义一个作为已编码图像的变量,因此您不需要任何其他文件。非常方便的功能。
System Tray Design Pattern
这是您可以用来快速入门的设计模式。 该程序将创建系统任务栏图标并执行阻止读取。如果从系统托盘中选择了“打开”项目,则会显示一个弹出窗口。 import PySimpleGUIQt as sg menu_def = ['BLANK', ['&Open', '---', '&Save', ['1', '2', ['a', 'b']], '&Properties', 'E&xit']] tray = sg.SystemTray(menu=menu_def, filename=r'default_icon.ico') while True: # The event loop menu_item = tray.Read() print(menu_item) if menu_item == 'Exit': break elif menu_item == 'Open': sg.Popup('Menu item chosen', menu_item) 设计模式将创建一个图标,该图标将显示此菜单。
Menu Definition
menu_def = ['BLANK', ['&Open', '&Save', ['1', '2', ['a', 'b']], '!&Properties', 'E&xit']]
使用列表定义菜单。“菜单项”是一个字符串,它指定: 文本显示的 键盘快捷键*键 有关在菜单上使用按键的更多信息,请参见菜单按键部分。 没有按键和键盘快捷键的条目是一个简单的字符串 'Menu Item' 如果要使“ M”成为键盘快捷键,请&在快捷键字母前放置一个。 '&Menu Item' 您可以添加“键”以使菜单项唯一,或作为显示菜单文本的另一种方式来标识菜单项。通过将键放置::在文本之后,将其添加到文本部分。 'Menu Item::key' 第一个条目可以忽略。'BLANK在此示例中选择了“。之所以这样,是因为通常您会在菜单栏上的某些标题下指定这些菜单。但是这里没有标题,因此您可以用所需的任何值填充它。 分隔符 如果要在2个项目之间使用分隔符,请添加该条目'---',它将在菜单中的该位置添加一个分隔符项目。 禁用的菜单项 如果要禁用菜单项,请!在菜单项之前放置一个
SystemTray Methods
Read
def Read(timeout=None) ''' Reads the context menu :param timeout: Optional. Any value other than None indicates a non-blocking read :return: String representing meny item chosen. None if nothing read. ''' 该timeout参数指定事件等待多长时间。如果在超时时间内没有任何反应,则返回“超时事件”。这些类型的读取使得可以异步运行。要不受阻碍地运行,请指定timeout=0 读取返回所选菜单项的菜单文本(含键)。如果您指定Open::key为菜单项,并且用户单击了Open,则Open::key在完成读取后,您将收到字符串。 读取特殊的返回值 除菜单项外,“读取”调用还可以返回几个特殊值。他们包括: EVENT_SYSTEM_TRAY_ICON_DOUBLE_CLICKED-双击托盘图标EVENT_SYSTEM_TRAY_ICON_ACTIVATED-单击托盘图标EVENT_SYSTEM_TRAY_MESSAGE_CLICKED-单击消息气球如果没有设置超时值的事件,则返回TIMEOUT_KEY
Hide
隐藏图标。请注意,隐藏图标时不会显示任何消息气球。 def Hide()
Close
做与隐藏相同的事情 def Close()
UnHide
显示一个以前隐藏的图标 def UnHide()
ShowMessage
在系统任务栏区域中的图标上方显示气球。您可以指定自己的图标以显示在气球中,也可以设置messageicon为预设值之一。此消息有一个自定义图标。
预设messageicon值为: SYSTEM_TRAY_MESSAGE_ICON_INFORMATION SYSTEM_TRAY_MESSAGE_ICON_WARNING SYSTEM_TRAY_MESSAGE_ICON_CRITICAL SYSTEM_TRAY_MESSAGE_ICON_NOICON ShowMessage(title, message, filename=None, data=None, data_base64=None, messageicon=None, time=10000): ''' Shows a balloon above icon in system tray :param title: Title shown in balloon :param message: Message to be displayed :param filename: Optional icon filename :param data: Optional in-ram icon :param data_base64: Optional base64 icon :param time: How long to display message in milliseconds :return: ''' 请注意,在Windows上可能需要更改注册表以使消息提示框可见。要解决此问题,您必须创建在此屏幕截图中看到的DWORD。
Update
您可以在SystemTray对象中更新这些项目中的任何一项。 菜单定义 图标*工具提示 全部更改或仅更改1。 Update(menu=None, tooltip=None,filename=None, data=None, data_base64=None,) ''' Updates the menu, tooltip or icon :param menu: menu defintion :param tooltip: string representing tooltip :param filename: icon filename :param data: icon raw image :param data_base64: icon base 64 image :return: '''
Keyboard & Mouse Capture
从版本2.10开始,您可以捕获键盘按键和鼠标滚轮事件。键盘键可用于例如检测PDF查看器的上一页和下一页键。要使用此功能,Window调用return_keyboard_events中有一个布尔设置,该设置被设置为True,以使键和按钮一起返回。 按键和滚轮事件的返回方式与按钮完全相同。 对于滚轮事件,如果将鼠标向上滚动,则button文本为MouseWheel:Up。对于向下滚动,返回的文本是MouseWheel:Down 键盘按键返回2种按键事件。对于“普通”键(a,b,c等),将返回代表该键的单个字符。修饰符和特殊键作为字符串返回,分为2部分: Key Sym:Key Code 键Sym是一个字符串,例如'Control_L'。密钥代码是该密钥的数字表示。按下左控制键将返回值'Control_L:17'
import PySimpleGUI as sg # Recipe for getting keys, one at a time as they are released # If want to use the space bar, then be sure and disable the "default focus" with sg.Window("Keyboard Test", return_keyboard_events=True, use_default_focus=False) as window: text_elem = sg.Text("", size=(18, 1)) layout = [[sg.Text("Press a key or scroll mouse")], [text_elem], [sg.Button("OK")]] window.Layout(layout) # ---===--- Loop taking in user input --- # while True: event, value = window.Read() if event == "OK" or event is None: print(event, "exiting") break text_elem.Update(event) 您要关闭默认焦点,以便在按空格键时不会选择任何按钮。
实时键盘捕获 通过调用使用实时键盘捕获 import PySimpleGUI as sg with sg.Window("Realtime Keyboard Test", return_keyboard_events=True, use_default_focus=False) as window: layout = [[sg.Text("Hold down a key")], [sg.Button("OK")]] window.Layout(layout) while True: event, value = window.Read(timeout=0) if event == "OK" or event is None: print(event, value, "exiting") break if event != sg.TIMEOUT_KEY: print(event)
Persistent windows (Window stays open after button click)
用户单击按钮后,有两种方法可以使窗口保持打开状态。
一种方法是使用单击按钮时“读取”窗口而不是“关闭”窗口的按钮。在窗口中找到的典型按钮(包括快捷按钮)将关闭窗口。其中包括“确定”,“取消”,“提交”等。“按钮元素”也将关闭窗口。
import PySimpleGUI as sg layout = [[sg.Text('Persistent window')], [sg.Input()], [sg.RButton('Read'), sg.Exit()]] window = sg.Window('Window that stays open').Layout(layout) while True: event, values = window.Read() if event is None or event == 'Exit': break print(event, values) window.Close()
该RButton元素创建一个按钮,点击时将控制权返回给用户,但将离开窗口打开并可见。在非阻止窗口中也使用此按钮。不同之处在于调用了哪个方法来读取窗口。Read没有参数的普通调用将被阻止,timeout值为零的调用将不会被阻止。
请注意, 执行时会清除InputText和MultiLine元素。如果您不想在a 之后清除输入字段,则可以在创建这些元素时将参数设置为True。清除功能逐个元素打开和关闭。 ReadReaddo_not_clear
这背后的原因是持久性Windows通常是“表单”。当“提交”表单时,您希望所有字段都保留为空白,以便下一个数据输入将从一个新窗口开始。另外,在实现“聊天窗口”类型的界面时,每次读取/发送聊天数据后,都希望清除输入字段。将其视为Texting应用程序。
一种方法是使用非阻塞窗口
Read(timeout = t, timeout_key='timeout')
对于GUI,如果可以使用它们,则在超时的非阻塞情况下使用GUI进行读取是一件非常好的事情。如果您的设备可以稍等片刻,请使用这种读取方法。您可以添加到超时值的时间越长,占用的CPU时间就越少。
假设您有一个要每100毫秒“轮询”的设备。“简单的出路”和直到最近的唯一出路是: # YOU SHOULD NOT DO THIS.... while True: # Event Loop event, values = window.ReadNonBlocking() # DO NOT USE THIS CALL ANYMORE read_my_hardware() # process my device here time.sleep(.1) # sleep 1/10 second 该程序将快速测试用户输入,然后处理硬件。然后,它将休眠100毫秒,而gui则没有响应,然后它将再次使用GUI进行登录。我完全意识到这是一种粗糙的处理方式。我们说的是简单的东西,而没有尝试使用线程等来“正确处理”。这是出于演示目的。 一种新的更好的方法。...使用读取超时机制,睡眠就消失了。 # This is the right way to poll for hardware while True: # Event Loop event, values = window.Read(timeout = 100) read_my_hardware() # process my device here 此事件循环将每100毫秒运行一次。您正在进行一次Read调用,因此使用该操作所做的任何事情都会立即返回给您,并且您最多需要等待100ms的时间才能让用户执行操作。如果用户不执行任何操作,则读取将超时并且执行将返回到程序。
Non-Blocking Windows (Asynchronous reads)
有两种执行非阻塞读取的方法。 “旧方法”是: event, values = sg.ReadNonBlocking() 新方法 event, values = sg.Read(timeout=0) 如果您是第一次阅读此书,则应使用新方法。 2个调用的区别在于事件的值。对于ReadNonBlocking,None如果没有其他要报告的事件,则为event 。但是,这有一个“问题”。对于正常的Read调用,事件值为None表示该窗口已关闭。对于ReadNonBlocking,返回封闭窗口的方式是通过将values变量设置为None来实现。
sg.TIMEOUT_KEY
如果您使用新的timeout = 0方法,则事件值None表示窗口已关闭,就像正常的Read一样。剩下的问题是当没有其他事件发生时将其设置为什么。该值将是的值timeout_key。如果您在读取调用中未指定timeout_key值,那么它将被设置为默认值:TIMEOUT_KEY =' timeout ' 如果要在循环中测试“无事件”,则将这样编写: while True: event, value = window.Read(timeout=0) if event is None: break # the use has closed the window if event == sg.TIMEOUT_KEY: print("Nothing happened") 谨慎使用异步窗口。可能有一个看似异步的窗口,但事实并非如此。 在进入异步窗口之前,请尝试查找其他方法。发出此请求的原因是异步Windows反复轮询tkinter。如果您的循环中没有睡眠,那么您将消耗100%的CPU时间。成为一个好公民很重要。不要不必要地消耗CPU周期。 非阻塞通常保留为“最后手段”。当阻塞读取就可以了时,人们使用非阻塞读取的次数就太多了。 有一种混合方法……读取超时。如果您能够通过使用这种类型的读取来节省更多的CPU时间,那么您将在令人印象深刻的仪表上获得更高的分数。 使用非阻塞窗口的最合法时间是直接使用硬件时。也许您正在驾驶串行总线。如果查看Demo_OpenCV_Webcam.py程序中的事件循环,您会看到该读取是非阻塞读取。但是,事件循环中有一个发生阻塞的地方。循环中要阻止的点是从网络摄像头读取帧的调用。当框架可用时,您希望将其快速传送到输出设备,因此您不希望GUI阻塞。您希望阻止从硬件读取。 在演示中可以找到另一个示例,该示例用于控制Raspberry Pi上的机器人。在该应用程序中,您想要阅读方向按钮,前进,后退等,并立即采取措施。如果您使用的是RealtimeButtons,则目前唯一的选择是使用非阻塞窗口。如果要使按钮具有实时响应性,则必须将超时设置为零。 但是,使用这些按钮,在事件循环中添加睡眠至少将使其他进程有时间执行。但是,它将饿死您的GUI。在您整个睡眠期间,您的GUI均未执行。
Periodically CallingRead
假设您最终使用了非阻塞读取...那么您需要做一些内务处理。您可以定期“刷新”可见的GUI。在两次GUI更新之间等待的时间越长,窗口的感觉就越迟钝。由您决定是否进行这些调用,否则您的GUI将冻结。 与非阻塞窗口进行交互的方法有2种。 1.像读取普通窗口一样读取该窗口 。2.在不读取该窗口的情况下“刷新”该窗口的值。这是一项快速操作,旨在向用户显示最新值 使用异步窗口时,会显示该窗口,可以读取用户输入,但是您的代码会不断变化。您的责任是PySimpleGUI.Read定期致电。一秒钟几次或更长时间将产生相当灵活的GUI。 ##退出(关闭)永久窗口 如果您的窗口有一个关闭窗口的按钮,则PySimpleGUI将自动为您关闭该窗口。如果您所有的按钮都是ReadButtons,则由您决定完成后关闭窗口。 要关闭窗口,请调用Close方法。 window.Close()
Persistent Window Example - Running timer that updates
import PySimpleGUI as sg import time # ---------------- Create Form ---------------- sg.ChangeLookAndFeel('Black') sg.SetOptions(element_padding=(0, 0)) layout = [[sg.Text('')], [sg.Text('', size=(8, 2), font=('Helvetica', 20), justification='center', key='text')], [sg.ReadButton('Pause', key='button', button_color=('white', '#001480')), sg.ReadButton('Reset', button_color=('white', '#007339'), key='Reset'), sg.Exit(button_color=('white', 'firebrick4'), key='Exit')]] window = sg.Window('Running Timer', no_titlebar=True, auto_size_buttons=False, keep_on_top=True, grab_anywhere=True).Layout(layout) # ---------------- main loop ---------------- current_time = 0 paused = False start_time = int(round(time.time() * 100)) while (True): # --------- Read and update window -------- event, values = window.Read(timeout=10) current_time = int(round(time.time() * 100)) - start_time # --------- Display timer in window -------- window.FindElement('text').Update('{:02d}:{:02d}.{:02d}'.format((current_time // 100) // 60, (current_time // 100) % 60, current_time % 100))
Instead of a Non-blocking Read --- Use change_submits = True or return_keyboard_events = True
如果要在创建窗口后更改窗口中的Elements,则将调用Element的Update方法。 注意必须先读取或完成一个窗口,然后才能进行任何更新调用。 这是更新文本元素的示例 import PySimpleGUI as sg layout = [ [sg.Text('My layout', key='_TEXT_')], [sg.Button('Read')]] window = sg.Window('My new window').Layout(layout) while True: # Event Loop event, values = window.Read() if event is None: break window.Element('_TEXT_').Update('My new text value')
注意Update调用的位置。如果要在事件循环之外的Read调用之前更新Text Element ,则必须首先在窗口上调用Finalize。 在此示例中,更新是在读取之前完成的。因此,将Finalize调用添加到Window创建中。 import PySimpleGUI as sg layout = [ [sg.Text('My layout', key='_TEXT_')], [sg.Button('Read')] ] window = sg.Window('My new window').Layout(layout).Finalize() window.Element('_TEXT_').Update('My new text value') while True: # Event Loop event, values = window.Read() if event is None: break
注意Update调用的位置。如果要在事件循环之外的Read调用之前更新Text Element ,则必须首先在窗口上调用Finalize。 在此示例中,更新是在读取之前完成的。因此,将Finalize调用添加到Window创建中。 import PySimpleGUI as sg layout = [ [sg.Text('My layout', key='_TEXT_')], [sg.Button('Read')] ] window = sg.Window('My new window').Layout(layout).Finalize() window.Element('_TEXT_').Update('My new text value') while True: # Event Loop event, values = window.Read() if event is None: break
您可以使用Update来执行以下操作:使 一个元素(出现)更改为另一个元素 禁用按钮,滑块,输入字段等 更改按钮的文本 更改元素的文本或背景颜色 将文本添加到滚动输出窗口 更改列表中的选择 *等 完成此操作的方式是通过适用于几乎所有Elements的Update方法。这是使用已更新的持久窗口的程序示例。
在某些程序中,这些更新是响应另一个元素而发生的。该程序采用微调器和滑块的输入值,并使用它们来调整文本元素的大小。Spinner和Slider在左侧,正在更改的Text元素在右侧。
# Testing async window, see if can have a slider # that adjusts the size of text displayed import PySimpleGUI as sg fontSize = 12 layout = [[sg.Spin([sz for sz in range(6, 172)], font=('Helvetica 20'), initial_value=fontSize, change_submits=True, key='spin'), sg.Slider(range=(6,172), orientation='h', size=(10,20), change_submits=True, key='slider', font=('Helvetica 20')), sg.Text("Aa", size=(2, 1), font="Helvetica " + str(fontSize), key='text')]] sz = fontSize window = sg.Window("Font size selector", grab_anywhere=False).Layout(layout) # Event Loop while True: event, values= window.Read() if event is None: break sz_spin = int(values['spin']) sz_slider = int(values['slider']) sz = sz_spin if sz_spin != fontSize else sz_slider if sz != fontSize: fontSize = sz font = "Helvetica " + str(fontSize) window.FindElement('text').Update(font=font) window.FindElement('slider').Update(sz) window.FindElement('spin').Update(sz) print("Done.")
在事件循环内,我们使用那些Elements的键读取Spinner和Slider的值。 例如,values['slider']是Slider元素的值。 如果Slider或Spinner更改,则此程序将更改所有3个元素。这是通过以下语句完成的: window.FindElement('text').Update(font=font) window.FindElement('slider').Update(sz) window.FindElement('spin').Update(sz) 请记住此设计模式,因为如果使用持久窗口,则将经常使用它。 它的工作原理如下。的调用window.FindElement返回它们所提供的Element对象key。然后,通过调用其Update方法来更新此元素。这是Python的“链接”功能的另一个示例。我们可以使用长格式编写以下代码: text_element = window.FindElement('text') text_element.Update(font=font) 此练习的要点是,密钥是PySimpleGUI设计的关键。它们既用于读取窗口的值,也用于标识元素。如前所述,它们在Button调用中用作目标。
在事件循环内,我们使用那些Elements的键读取Spinner和Slider的值。 例如,values['slider']是Slider元素的值。 如果Slider或Spinner更改,则此程序将更改所有3个元素。这是通过以下语句完成的: window.FindElement('text').Update(font=font) window.FindElement('slider').Update(sz) window.FindElement('spin').Update(sz) 请记住此设计模式,因为如果使用持久窗口,则将经常使用它。 它的工作原理如下。的调用window.FindElement返回它们所提供的Element对象key。然后,通过调用其Update方法来更新此元素。这是Python的“链接”功能的另一个示例。我们可以使用长格式编写以下代码: text_element = window.FindElement('text') text_element.Update(font=font) 此练习的要点是,密钥是PySimpleGUI设计的关键。它们既用于读取窗口的值,也用于标识元素。如前所述,它们在Button调用中用作目标。
用于查找元素的Window方法调用为: FindElement 或缩短版本 Element 当您看到对window.FindElement或window.Element的调用时,便知道正在寻址一个元素。通常,这样做是为了使您可以调用元素的Update方法。
ProgressBar /进度表 请注意,要更改进度条的进度,请调用UpdateBar,而不是Update。这是实施Update调用之前遗留下来的旧命名约定。
Menus
MenuBar
从3.01版开始,您可以将MenuBar添加到窗口中。您可以使用与列表一样的窗口布局来指定菜单。从3.17开始,菜单选择作为事件返回,也与值字典一样。返回的值将是整个菜单项,包括键(如果已指定)。 这个定义: menu_def = [['File', ['Open', 'Save', 'Exit',]], ['Edit', ['Paste', ['Special', 'Normal',], 'Undo'],], ['Help', 'About...'],]
注意','和[]的位置。正确实现嵌套菜单以实现级联菜单是很棘手的。查看粘贴后如何将特殊和普通作为列表。这意味着“粘贴”具有一个层叠菜单,其中包含“特殊”和“普通”项。
要将菜单添加到Window,请将Menu或MenuBar元素放入布局中。 layout = [[sg.Menu(menu_def)]] 将菜单元素放置在布局中的位置并不重要,因为它始终位于窗口顶部。
Right Click Menus
要将菜单添加到Window,请将Menu或MenuBar元素放入布局中。 layout = [[sg.Menu(menu_def)]] 将菜单元素放置在布局中的位置并不重要,因为它始终位于窗口顶部。
Menu Shortcut keys
所需要做的就是在要显示的字母前加下划线“&”。按住Alt键时,您将看到带有标记的下划线的菜单。 您可以添加的另一点修饰是列表中的分隔符。要在菜单选项列表中添加一行,请创建一个如下所示的菜单项:'---' 这是带有下划线和分隔符的示例菜单。 # ------ Menu Definition ------ # menu_def = [['&File', ['&Open', '&Save', '---', 'Properties', 'E&xit' ]], ['&Edit', ['Paste', ['Special', 'Normal',], 'Undo'],], ['&Help', '&About...'],]
Disabled Menu Entries
如果您要禁用菜单项之一,请放置“!” 在菜单项前面。要在前面的示例中禁用“粘贴”菜单条目,该条目为: ['!&Edit', ['Paste', ['Special', 'Normal',], 'Undo'],] 如果您想将禁用的菜单项标志/字符从“!”更改为 给别的东西,改变变量MENU_DISABLED_CHARACTER
Keys for Menus
从版本3.17开始,您可以将a添加key到菜单项中。该key值将被删除,然后再插入菜单。当您收到菜单事件时,将key返回整个菜单项,包括。通过::在菜单项后添加,然后按键来指示键。 要将“。”添加key _MY_KEY_到“特殊”菜单项,代码应为: ['&Edit', ['Paste', ['Special::_MY_KEY_', 'Normal',], 'Undo'],] 如果要将指示键的字符从'::'更改为其他内容,请更改变量 MENU_KEY_SEPARATOR
Running Multiple Windows
both windows active
import PySimpleGUI as sg # Design pattern 2 - First window remains active layout = [[ sg.Text('Window 1'),], [sg.Input(do_not_clear=True)], [sg.Text('', key='_OUTPUT_')], [sg.Button('Launch 2'), sg.Button('Exit')]] win1 = sg.Window('Window 1').Layout(layout) win2_active = False while True: ev1, vals1 = win1.Read(timeout=100) win1.FindElement('_OUTPUT_').Update(vals1[0]) if ev1 is None or ev1 == 'Exit': break if not win2_active and ev1 == 'Launch 2': win2_active = True layout2 = [[sg.Text('Window 2')], [sg.Button('Exit')]] win2 = sg.Window('Window 2').Layout(layout2) if win2_active: ev2, vals2 = win2.Read(timeout=100) if ev2 is None or ev2 == 'Exit': win2_active = False win2.Close()
only 1 active window
import PySimpleGUIQt as sg # Design pattern 1 - First window does not remain active layout = [[ sg.Text('Window 1'),], [sg.Input(do_not_clear=True)], [sg.Text('', key='_OUTPUT_')], [sg.Button('Launch 2')]] win1 = sg.Window('Window 1').Layout(layout) win2_active=False while True: ev1, vals1 = win1.Read(timeout=100) if ev1 is None: break win1.FindElement('_OUTPUT_').Update(vals1[0]) if ev1 == 'Launch 2' and not win2_active: win2_active = True win1.Hide() layout2 = [[sg.Text('Window 2')], # note must create a layout from scratch every time. No reuse [sg.Button('Exit')]] win2 = sg.Window('Window 2').Layout(layout2) while True: ev2, vals2 = win2.Read() if ev2 is None or ev2 == 'Exit': win2.Close() win2_active = False win1.UnHide() break
Layouts版面
5 specific techniques of generating layouts
1.布局+布局串联 [[A]] + [[B]] = [[A], [B]] 2.同一行上的元素加法 [[A] + [B]] = [[A, B]] 3.列表理解以生成行 [A for x in range(10)] = [A,A,A,A,A...] 4.列表推导生成多行 [[A] for x in range(10)] = [[A],[A],...] 5.用户定义元素/复合元素
Brute Force
import PySimpleGUI as sg layout = [ [sg.Text('1. '), sg.In(key=1)], [sg.Text('2. '), sg.In(key=2)], [sg.Text('3. '), sg.In(key=3)], [sg.Text('4. '), sg.In(key=4)], [sg.Text('5. '), sg.In(key=5)], [sg.Button('Save'), sg.Button('Exit')] ] window = sg.Window('To Do List Example', layout) event, values = window.Read()
Build By Concatenating Rows
import PySimpleGUI as sg layout = [] for i in range(1,6): layout += [sg.Text(f'{i}. '), sg.In(key=i)], layout += [[sg.Button('Save'), sg.Button('Exit')]] window = sg.Window('To Do List Example', layout) event, values = window.Read()
Create Several Rows Using List Comprehension
layout = [[sg.Text(f'{i}. '), sg.In(key=i)] for i in range(1,6)]
Concatenating Multiple Rows
layout = [[sg.Text(f'{i}. '), sg.In(key=i)] for i in range(1,6)] layout += [[sg.Button('Save'), sg.Button('Exit')]]
在上面的示例中,我们知道第一行是输入行的生成布局。最后一行在布局上添加了另一种布局...请注意格式为[[]]。此按钮定义是一个完整的布局,可以添加到列表理解中 [[sg.Button('Save'), sg.Button('Exit')]]
最终得到了以下一条语句,该语句为GUI 创建了整个布局: layout = [[sg.Text(f'{i}. '), sg.In(key=i)] for i in range(1,6)] + [[sg.Button('Save'), sg.Button('Exit')]]
Final "To Do List" Program
import PySimpleGUI as sg layout = [[sg.Text(f'{i}. '), sg.In(key=i)] for i in range(1,6)] + [[sg.Button('Save'), sg.Button('Exit')]] window = sg.Window('To Do List Example', layout) event, values = window.read()
import PySimpleGUI as sg event, values = sg.Window('To Do List Example', layout=[[sg.Text(f'{i}. '), sg.In(key=i)] for i in range(1,6)] + [[sg.Button('Save'), sg.Button('Exit')]]).Read()
Example - List Comprehension to Build Rows - Table Simulation - Grid of Inputs
Building the Header
import PySimpleGUI as sg headings = ['HEADER 1', 'HEADER 2', 'HEADER 3','HEADER 4'] # the text of the headings header = [[sg.Text(' ')] + [sg.Text(h, size=(14,1)) for h in headings]] # build header layout
Building the Input Elements
input_rows = [[sg.Input(size=(15,1), pad=(0,0)) for col in range(4)] for row in range(10)]
Putting it all together
import PySimpleGUI as sg headings = ['HEADER 1', 'HEADER 2', 'HEADER 3','HEADER 4'] header = [[sg.Text(' ')] + [sg.Text(h, size=(14,1)) for h in headings]] input_rows = [[sg.Input(size=(15,1), pad=(0,0)) for col in range(4)] for row in range(10)] layout = header + input_rows window = sg.Window('Table Simulation', layout, font='Courier 12') event, values = window.Read()
User Defined Elements 用户定义元素
[sg.Button('1', button_color=('white', 'blue'), size=(5, 1), font=("Helvetica", 20)), sg.Button('2', button_color=('white', 'blue'), size=(5, 1), font=("Helvetica", 20)), sg.Button('3', button_color=('white', 'blue'), size=(5, 1), font=("Helvetica", 20)), sg.Button('log', button_color=('white', 'blue'), size=(5, 1), font=("Helvetica", 20)), sg.Button('ln', button_color=('white', 'blue'), size=(5, 1), font=("Helvetica", 20)), sg.Button('-', button_color=('white', 'blue'), size=(5, 1), font=("Helvetica", 20))],
def CBtn(button_text): return sg.Button(button_text, button_color=('white', 'blue'), size=(5, 1), font=("Helvetica", 20))
[CBtn('1'), CBtn('2'), CBtn('3'), CBtn('log'), CBtn('ln'), CBtn('-')],
[CBtn(t) for t in ('1','2','3', 'log', 'ln', '-')]
Compound Elements复合元素
def ToDoItem(num): return [sg.Text(f'{num}. '), sg.CBox(''), sg.In()]
import PySimpleGUI as sg def ToDoItem(num): return [sg.Text(f'{num}. '), sg.CBox(''), sg.In()] layout = [ToDoItem(x) for x in range(1,6)] + [[sg.Button('Save'), sg.Button('Exit')]] window = sg.Window('To Do List Example', layout) event, values = window.read()
Window Object
Window Location
PySimpleGUI计算窗口的中心,并将窗口居中显示在屏幕上。如果您想将窗口放在其他位置,例如系统默认值(0,0),则有两种方法。首先是创建窗口时。使用location参数设置窗口的位置。第二种方法是使用该SetOptions调用,该调用将在将来为所有窗口设置默认窗口位置。
Window Size
通过访问Size属性来获取窗口的大小。该窗口必须被读取一次或完成才能使该值正确。请注意,这是属性,而不是呼叫。my_windows_size = window.Size
window = Window('My Title', layout).Finalize()
如果使用PySimpleGUI 4.2及更高版本: window = Window('My Title', layout, finalize=True)
Element Sizes
设置元素大小的方法有多种: 全局默认大小-使用SetOptions功能更改 在窗口级别-使用default_element_size调用中的参数进行更改Window 在元素级别-每个元素都有一个size参数
元素大小以字符为单位(有例外)。文本元素 size = (20,1)的大小为20个字符,宽1个字符。 PySimpleGUI的默认元素大小为(45,1)。 有几个小部件,其中大小值之一是像素而不是字符。这对于进度表和滑块是正确的。第二个参数是像素的“高度”。
No Titlebar
如果您希望创建没有窗口标题栏的干净美观的窗口,请在创建窗口时使用no_titlebar选项。 确保为您的用户提供“退出”按钮,否则他们将无法关闭窗口! 没有标题栏的Windows依赖于“grab_anywhere = True”选项来启用,否则您将无法移动窗口。 不带标题栏的Windows可用于轻松创建浮动启动器。
Grab Anywhere
这是PySimpleGUI独有的功能。 注意-如果用户使用启用了grap_anywhere的按钮关闭非阻塞窗口,则会打印一条警告消息。这些消息没有危害,但可能会使用户感到困扰。如果您希望启用非阻塞窗口,则在创建窗口时只需获取grab_anywhere = True。
Always on top
要将窗口保持在屏幕上所有其他窗口的顶部,请在创建窗口时将keep_on_top = True设置为True。此功能使浮动工具栏非常有用,并且始终在桌面上可见。
Focus
PySimpleGUI将为您设置默认的焦点位置。这通常表示第一个输入字段。您可以将焦点设置为特定元素。如果要自行设置焦点,则应通过use_default_focus=False在Window调用中进行设置来关闭自动焦点。
The creation part of a window
1.创建一个Window对象 2.将布局添加到窗口 3.可选-如果要在Read通话前进行更改,请完成
这是一个新颖的概念,而不是使用链接,使用参数进行Window调用。从PySimpleGUI端口4.2开始的情况。 window = sg.Window('My Title', layout, finalize=True)
finalize=True,调用以强制窗口经历初始化的最后阶段。这将导致分配tkinter资源,以便随后对其进行修改。这也会导致您的窗口出现。如果您不希望在调用Finalize时出现窗口,请在窗口的创建参数中将Alpha设置为0。 如果要调用元素的Update方法或调用Graph元素的图形基元,则必须先调用Read或Finalize在进行这些调用之前。
子主题:Read(timeout=None, timeout_key=TIMEOUT_KEY 读取窗口的输入值,并以流行的方式单击按钮返回事件、值。通过设置timeout = 读取超时之前的毫秒数(此后将返回“超时事件”),可以添加超时。timeout_key的值将作为事件返回。如果您未指定超时键,则将TIMEOUT_KEY返回该值。 如果将超时设置为0,则读取将立即返回,而不是等待输入或超时。这是窗口的真正非阻塞“读取”。
这是Window对象的定义: Window( title, default_element_size=DEFAULT_ELEMENT_SIZE, default_button_element_size=(None,None), auto_size_text=None, auto_size_buttons=None, location=(None,None), size=(None,None), element_padding=None, button_color=None, font=None, progress_bar_color=(None,None), background_color=None, border_depth=None, auto_close=False, auto_close_duration=DEFAULT_AUTOCLOSE_TIME, icon=DEFAULT_WINDOW_ICON, force_toplevel=False, alpha_channel=1, return_keyboard_events=False, use_default_focus=True, text_justification=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, resizable=False, disable_close=False, disable_minimize=False, right_click_menu=None): 参数说明。您会发现为每个参数指定了相同的参数Element,并在Row规范中找到了其中一些参数。在Element指定的值将优先于Row和window值。
default_element_size - Size of elements in window in characters (width, height) default_button_element_size - Size of buttons on this window auto_size_text - Bool. True if elements should size themselves according to contents. Defaults to True auto_size_buttons - Bool. True if button elements should size themselves according to their text label location - (x,y) Location to place window in pixels size - (w,h) forces a window to be a paricular size element_padding - (w,h) default padding amount for elements font - Font name and size for elements of the window button_color - Default color for buttons (foreground, background). Can be text or hex progress_bar_color - Foreground and background colors for progress bars background_color - Color of the window background border_depth - Amount of 'bezel' to put on input boxes, buttons, etc. auto_close - Bool. If True window will autoclose auto_close_duration - Duration in seconds before window closes icon - .ICO file that will appear on the Task Bar and end of Title Bar force_top_level - Bool. If set causes a tk.Tk window to be used as primary window rather than tk.TopLevel. Used to get around Matplotlib problem alpha_channel - Float 0 to 1. 0 is invisible, 1 is fully visible, Anything between will be semi-transparent return_keyboard_events - if True key presses are returned as buttons use_default_focus - if True and no focus set, then automatically set a focus text_justification - Justification to use for Text Elements in this window no_titlebar - Create window without a titlebar grab_anywhere - Grab any location on the window to move the window keep_on_top - if True then window will always stop on top of other windows on the screen. Great for floating toolbars. resizable - if True - user can manually changge the wize of the window. Defaults to False disable_close - if True user will not be able to close using the X. disable_minimize - if True user will not be able to minimize the window right_click_menu - menu definition that will be used on wall elements that support right click. If a definition is specified on an element then it will be used instead.
您将在本文档中看到一些在Windows上起作用的方法(功能)。您将主要拨打的电话是: window.Layout(layout) - Turns your definition of the Window into Window window.Finalize() - creates the tkinter objects for the Window. Normally you do not call this window.Read() - Read the Windows values and get the button / key that caused the Read to return. Can have an optional timeout window.ReadNonBlocking() - NO LONGER USED! window.Refresh() - Use if updating elements and want to show the updates prior to the nex Read window.Fill(values_dict) - Fill each Element with entry from the dictionary passed in window.SaveToDisk(filename) - Save the Window's values to disk window.LoadFromDisk(filename) - Load the Window's values from disk window.Close() - To close your window, if a button hasn't already closed it window.Disable() - Use to disable the window inputwhen opening another window on top of the primnary Window window.Enable() - Re-enable a Disabled window window.FindElement(key, silent_on_error=False) - Returns the element that has a matching key value window.Move(x,y) - Moves window to location x,y on screen' window.SetAlpha(alpha) - Changes window transparency window.BringToFront() - Brings the window to the top of other windows on the screen window.Disappear(), Reappear() - Uses alpha channel to make window disappear window.Hide(), UnHide() - Hides a window window.CurrentLocation() - Returns current window location window.Size = w,h - Forces a window to be a particular size. Note this is a property not a method window.Size - Tuple (w,h)The size of the current window. Note this is a property window.Minimize() - Minimizes window to taskbar
视窗方法 创建窗口后,可以在窗口上执行许多操作。您在创建Windows对象之后调用它们。 布局(行)-调用以设置窗口布局。必须在读取之前调用。最有可能与Window的创建“链接”。 window = sg.Window('My window title').Layout(layout) Finalize()-调用以强制窗口经历初始化的最后阶段。这将导致分配tkinter资源,以便随后对其进行修改。这也会导致您的窗口出现。如果您不希望在调用Finalize时出现窗口,请在窗口的创建参数中将Alpha设置为0。如果要调用元素的Update方法或调用Graph元素的图形基元,则必须先调用Read或Finalize在进行这些调用之前。 读取(超时=无,timeout_key ='__ TIMEOUT_ _')-读取窗口的输入值,并以流行的方式单击按钮,返回事件,值。通过设置timeout =读取超时之前的毫秒数(此后将返回“超时事件”),可以添加超时。timeout_key的值将作为事件返回。如果您未指定超时键,则将TIMEOUT_KEY返回该值。如果将超时设置为0,则读取将立即返回,而不是等待输入或超时。这与旧的ReadNonBlocking调用相同。 ReadNonBlocking()(不再使用) 从技术上来讲,此调用仍然有效,但是已将其删除。如果要获得相同的结果,请调用Read with timeout = 0。 读取窗口的输入值和单击按钮,但不要阻塞。它将立即返回。 考虑改为使用非零超时读取! 如果您在事件循环中没有其他阻塞调用,将消耗100%的CPU。 刷新()-导致更改要在屏幕上显示的窗口。通常不需要,除非立即进行了更改,或者在下一次调用Read之前需要一段时间。 SetIcon(icon,pngbase64)-设置将在标题栏上显示的窗口图标。可以是文件名或base64字符串。 填充(values_dict)-使用字典中显示的值填充Windows字段。 元素(键,silent_on_error = False)(简写版本) FindElement(键,silent_on_error =假)-返回具有匹配键的Element。如果找不到该键,则返回一个错误元素,这样,如果用户尝试执行“更新”,该程序就不会崩溃。将显示一个弹出消息 FindElementWithFocus()-返回当前具有焦点的Element。如果未找到任何元素,则返回None。 SaveToDisk(文件名)-将窗口的值保存到磁盘 LoadFromDisk(文件名)-根据先前保存的文件填写窗口的字段 GetScreenDimensions()-返回以像素为单位的屏幕尺寸(w,h) 当前位置()-返回当前屏幕位置(x,y) 移动(x,y)-将窗口移到屏幕上的(x,y)位置 最小化()-将窗口发送到任务栏 关()-关闭一个窗口,阻止或不阻止 CloseNonBlocking()(不再使用。代替使用Close)关闭一个非阻塞窗口 禁用()-停止窗口响应,直到调用启用 启用()-重新启用先前禁用的窗口 隐藏()-完全隐藏一个窗口,包括从任务栏中删除 取消隐藏()-恢复使用“隐藏”隐藏的窗口 消失()-使窗口消失,同时将图标保留在任务栏上 再现()-重新显示以前使用Disappear()消失的窗口 SetAlpha(alpha)-设置窗口的透明度。0是完全透明的。1完全可见,正常。也可以使用属性Window.AlphaChannel代替方法函数的调用
Debug Output (EasyPrint = Print = eprint)
API的“简易”系列中的另一个调用是EasyPrint。与其他常用的PySimpleGUI调用一样,同一调用还有其他名称。您可以使用Print或eprint除EasyPrint。它们都做同样的事情,输出到调试窗口。如果调试窗口没有打开,则第一个调用将打开它。除了在代码中添加“ sg.Print”调用外,无需执行任何操作。只需粘贴以下语句,您甚至可以将对“打印”的调用替换为对EasyPrint的调用print = sg.EasyPrint
Print是易于使用的更好的工具之一。它只是print用大写字母P。sg.Print('this will go to the debug window')
import PySimpleGUI as sg for i in range(100): sg.Print(i)
EasyPrint支持sep和end关键字参数。可以使用SetOptions带有debug_win_size参数的调用来更改调试窗口的大小。有一个选项告诉PySimpleGUI将所有的stdout和stderr输出重新路由到该窗口。为此,将EasyPrint的参数do_not_reroute_stdout设置为False。在将此参数设置为True的情况下调用一次后,以后所有对法线的调用print都将进入调试窗口。如果关闭调试窗口,则下次打印时将重新打开。如果要使用代码关闭窗口,则可以调用EasyPrintClose()或PrintClose()
OneLineProgressMeter
借助一些技巧,您可以使用“进度表”窗口提供一种打破循环的方式。取消按钮会产生的False返回值OneLineProgressMeter。通常返回True。确保将一个添加到循环计数器,以使计数器从1变为最大值。如果不加一,计数器将永远不会达到最大值。相反,它将从0变为max-1
OneLineProgressMeter(title, current_value, max_value, key, *args, orientation=None, bar_color=DEFAULT_PROGRESS_BAR_COLOR, button_color=None, size=DEFAULT_PROGRESS_BAR_SIZE, border_width=DEFAULT_PROGRESS_BAR_BORDER_WIDTH):
for i in range(1,10000): sg.OneLineProgressMeter('My Meter', i+1, 10000, 'key','Optional message')
Popup
Popup
return-Union [str,None]返回所按下按钮的文本。如果用户关闭带有X的窗口,则不会返回任何内容
sg.Popup('Popup') # Shows OK button sg.PopupOk('PopupOk') # Shows OK button sg.PopupYesNo('PopupYesNo') # Shows Yes and No buttons sg.PopupCancel('PopupCancel') # Shows Cancelled button sg.PopupOKCancel('PopupOKCancel') # Shows OK and Cancel buttons sg.PopupError('PopupError') # Shows red error button sg.PopupTimed('PopupTimed') # Automatically closes sg.PopupAutoClose('PopupAutoClose') # Same as PopupTimed
Popup(args,-(任意)您的变元数。加载呼叫以查看内容! title=None, button_color=None,-元组[str,str]按钮的颜色(前景,背景) background_color=None, text_color=None, button_type=0,-(枚举)不是用户设置的!确定将显示哪些预定义按钮(默认值= POPUP_BUTTONS_OK)。有很多Popup函数,它们调用Popup,更改此参数以获得所需的效果。-button_type的选择是: POPUP_BUTTONS_YES_NO POPUP_BUTTONS_CANCELLED POPUP_BUTTONS_ERROR POPUP_BUTTONS_OK_CANCEL POPUP_BUTTONS_OK POPUP_BUTTONS_NO_BUTTONS auto_close=False, auto_close_duration=None,-(int)以秒为单位的时间,以保持窗口打开,然后自动关闭 custom_text=(None, None),-Union [Tuple [str,str],str]一个字符串或一对字符串,其中包含要在按钮上显示的文本 non_blocking=False,-(布尔)如果为True,则将立即从函数返回,而无需等待用户输入。 icon=None,-Union [str,bytes]图标显示在窗口上。与窗口调用相同的格式 line_width=None,-(int)字符的行宽。默认为MESSAGE_BOX_LINE_WIDTH font=None, no_titlebar=False,-(布尔)如果为True,则不会在窗口周围显示框架,而在顶部显示标题栏 grab_anywhere=False,-(布尔)如果True可以抓住任何地方移动窗口。如果no_titlebar为True,那么也应该启用grab_anywhere keep_on_top=False, location=(None, None))-Tuple [int,int]在屏幕上显示窗口左上角的位置。默认为屏幕居中显示的窗口
PopupScrolled
PopupScrolled(args, title=None, button_color=None, yes_no=False,-(布尔)如果为True,则显示“是”和“否”按钮,而不是“确定” auto_close=False, auto_close_duration=None, size=(None, None),-Tuple [int,int](w,h)w =字符宽,h =行高 location=(None, None), non_blocking=False)
典型用法: sg.PopupScrolled(my_text)
PopupScrolled会自动调整窗口大小的文本大小。指定None在一个高度场size参数来获取自动调整大小的高度。此调用将创建一个滚动框,其宽度为80个字符,高度取决于文本的行数。sg.PopupScrolled(my_text, size=(80, None)) 请注意,滚动发生之前的默认最大行数设置为50。在50行开始滚动。 如果non_blocking设置了参数,则该调用将不会阻止等待用户关闭窗口。执行将立即返回给用户。当您希望转储调试信息而又不中断程序流程时非常方便。
PopupNoWait
PopupNoWait(args, title=None, button_type=0, button_color=None, background_color=None, text_color=None, auto_close=False, auto_close_duration=None, non_blocking=True, icon=None, line_width=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None))
弹出调用PopupNoWait或PopupNonBlocking将创建一个弹出窗口,然后立即将控件返回给您。所有其他弹出功能将被阻止,等待用户关闭弹出窗口。 此功能在调试时希望将某些内容显示为输出,但又不想通过阻塞更改程序的总体时序时非常方便。认为它像一个print声明。这些弹出窗口之一上没有返回值。
Popup Input
PopupGetText
使用此弹出窗口可从用户获取一行文本。显示带有文本输入字段的弹出窗口。返回输入的文本,如果关闭/取消则返回无
PopupGetText(message, title=None, default_text="", password_char="",-(str)要显示的字符,而不是实际键入的字符 size=(None, None),-InputText元素的Tuple [int,int](宽度,高度) button_color=None,-Tuple [str,str]按钮的颜色(文本,背景) background_color=None, text_color=None, icon=None,-窗口图标使用的Union [bytes,str]文件名或base64字符串 font=None, no_titlebar=False,-(布尔)如果为True,则不会显示标题栏 grab_anywhere=False, keep_on_top=False, location=(None, None))
import PySimpleGUI as sg text = sg.PopupGetText('Title', 'Please input something') sg.Popup('Results', 'The value returned from PopupGetText', text)
PopupGetFile
从用户获取文件名。有一些选项可配置要显示的对话框的类型。通常会显示一个“打开文件”对话框。显示带有文本输入字段和浏览按钮的弹出窗口,以便用户可以选择文件。返回Union [str,None]字符串,表示所选文件,如果取消或使用X关闭窗口,则为None。如果您选择一个已经存在的文件名,则会出现一个警告弹出框,询问是否可以。您还可以指定一个不存在的文件。使用“打开”对话框,您不能选择不存在的文件。
PopupGetFile(message,-向用户显示(str)消息 title=None,-(str)窗口标题 default_path="",-(str)显示给用户作为起点的路径(填写到输入字段中) default_extension="",-(str)如果用户未输入扩展名,请将其添加到文件名(仅在saveas对话框中使用) save_as=False,-(布尔)如果为True,则会显示“另存为”对话框,该对话框将在覆盖之前进行验证 multiple_files=False,-(布尔)如果为True,则允许选择多个以';'返回的文件 每个文件名之间 file_types=(('ALL Files', '*.*'),),-Tuple [Tuple [str,str]]使用通配符显示的扩展列表。 no_window=False,-(布尔)如果为True,则不会显示PySimpleGUI窗口。而是只显示了tkinter对话框 size=(None, None),-InputText元素的Tuple [int,int](宽度,高度) button_color=None, background_color=None, text_color=None, icon=None, font=None,-Union [str,Tuple [str,int]]指定字体系列,大小等 no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None)-(str)文件系统中的位置以开始浏览
text = sg.PopupGetFile('Please enter a file name') sg.Popup('Results', 'The value returned from PopupGetFile', text)
PopupGetFolder
创建用于获取文件夹名称的窗口看起来与获取文件名称相同。不同之处在于浏览按钮的功能。 PopupGetFile显示“打开文件”对话框,同时PopupGetFolder 显示“打开文件夹”对话框。显示带有文本输入字段和浏览按钮的弹出窗口,以便可以选择一个文件夹。返回Union [str,None]字符串代表所选的路径,如果取消或用X关闭窗口则为None
PopupGetFolder(message, title=None, default_path="", no_window=False, size=(None, None), button_color=None, background_color=None, text_color=None, icon=None, font=None, no_titlebar=False, grab_anywhere=False, keep_on_top=False, location=(None, None), initial_folder=None)
text = sg.PopupGetFolder('Please enter a folder name') sg.Popup('Results', 'The value returned from PopupGetFolder', text)
PopupAnimated
动画弹出窗口使您可以轻松显示通过GIF文件指定的“加载”样式动画,该文件存储在文件或base64变量中。一次显示动画一帧。此功能具有自己的内部时钟,意味着您可以在任何频率下调用它,并且视频帧的显示速率保持恒定。也许帧每30毫秒更新一次,但事件循环每10毫秒运行一次。您不必担心延迟,只需在循环中每次都调用它即可。要关闭动画弹出窗口,使用调用PopupAnimatedimage_source=None。这将关闭所有当前打开的PopupAnimated窗口。
PopupAnimated(image_source,-Union [str,bytes]是文件名或base64字符串。 message=None, background_color=None, text_color=None, font=None, no_titlebar=True, grab_anywhere=True, keep_on_top=True, location=(None, None), alpha_channel=None,-(浮动)窗口透明度0 =不可见1 =完全可见。之间的值是透明的 time_between_frames=0,-int)每帧之间的时间间隔(以毫秒为单位) transparent_color=None)-(str)此颜色在您的窗口中将完全透明。甚至可以点击
Reads using an event
Pattern 1 - "One-shot Window" - Read a window one time then close it模式1-“一次性窗口”-读取一次窗口然后将其关闭
如果您不使用“事件循环”(不多次读取窗口),这将是您将遵循的最常见模式。窗口被读取并关闭。窗口中的输入字段将作为字典返回给您(语法上看起来像列表查找)
import PySimpleGUI as sg layout = [[sg.Text('SHA-1 and SHA-256 Hashes for the file')], [sg.InputText(), sg.FileBrowse()], [sg.Submit(), sg.Cancel()]] window = sg.Window('SHA-1 & 256 Hash', layout) event, values = window.Read() window.Close() source_filename = values[0] # the first input element is values[0]
Pattern 2 A - Persistent window (multiple reads using an event loop)模式2 A-持久窗口(使用事件循环多次读取)
一些更高级的程序在窗口保持可见的状态下运行。收集输入值,但不关闭窗口,而是保持可见状态,这是向用户输出信息和收集输入数据的一种方式。该代码将显示一个窗口并打印值,直到用户单击退出按钮或使用X关闭窗口为止。
import PySimpleGUI as sg layout = [[sg.Text('Persistent window')], [sg.Input()], [sg.Button('Read'), sg.Exit()]] window = sg.Window('Window that stays open', layout) while True: event, values = window.Read() if event is None or event == 'Exit': break print(event, values) window.Close()
Pattern 2 B - Persistent window (multiple reads using an event loop + updates data in window)模式2 B-持久窗口(使用事件循环多次读取+更新窗口中的数据)
从用户那里读取输入,并将该输入显示为窗口中的文本。您的程序可能会同时执行这两项活动(输入和输出),因此这将为您提供一个很大的起点。
do_not_clear输入调用中的参数确定按钮事件后输入字段的操作。如果该值为True,则在单击按钮后输入值仍然可见。如果为False,则清除输入字段中的任何输入内容。如果要构建带有数据输入的“表单”类型的窗口,则可能需要使用False。默认为不清除输入元素(do_not_clear=True)。
在PySimpleGUI中,键非常重要,因为它们使您能够使用要使用的名称来标识和使用Elements。除以外,其他任何键都可以None。要访问在下面的示例中读取的输入元素的数据,将使用values['_IN_']而不是values[0]像以前一样。 import sys if sys.version_info[0] >= 3: import PySimpleGUI as sg else: import PySimpleGUI27 as sg layout = [[sg.Text('Your typed chars appear here:'), sg.Text('', key='_OUTPUT_') ], [sg.Input(key='_IN_')], [sg.Button('Show'), sg.Button('Exit')]] window = sg.Window('Window Title', layout) while True: # Event Loop event, values = window.Read() print(event, values) if event is None or event == 'Exit': break if event == 'Show': # change the "output" element to be the value of "input" element window.Element('_OUTPUT_').Update(values['_IN_']) window.Close()
Multitheaded Programs
这些线程程序的关键是从线程到事件循环的通信。这些演示选择的机制使用Python内置queue模块。事件循环轮询这些队列,以查看是否已从要显示的线程之一发送了某些内容。
使用纯PySimpleGUI(基于tkinter)-您的GUI绝不能以除主程序线程之外的任何方式运行,并且任何线程都不能直接调用PySimpleGUI调用。
The Event Loop / Callback Functions
一个PySimpleGUI事件循环的解剖结构如下,一般来说。*实际的“循环”部分是一个while True循环*“读取”事件和窗口具有的任何输入值*检查窗口是否关闭或用户希望退出*一系列if event ....语句
用户使用窗口右上角的“ X”关闭窗口,event则将为None。对于“永久窗口”,请 始终为您的用户提供一个离开窗口的方法。否则,您将得到永远无法正确关闭的窗口。在进行此操作时,请确保window.Close()在事件循环后进行了调用,以确保窗口关闭。
如果您没有为元素指定键,则将顺序分配一个数字。对于您不打算修改或读取值的元素(例如文本元素),可以跳过添加键。对于其他元素,您可能需要添加键,以便可以轻松访问值并对其执行操作。
Operations That Take a "Long Time"(不响应)
操作可以分解成较小的部分,则可以Window.Refresh()不时致电以避免出现此消息。例如,如果您正在运行循环,则将该呼叫与其他工作放在一起。这将使GUI保持愉快状态,并且Window不会抱怨。
另一方面,如果您的操作不受控制或无法添加Refresh调用,则下一个可用的选择是将长操作移入线程。
event, values = window.Read()
window.Read()
最常见的窗口读取语句如下所示: window = sg.Window("My title", layout).Read() 要使用字典,您将需要:*用关键字标记要在字典中的每个输入元素key。 如果窗口中的任何元素都有一个key,则所有返回值都将通过字典返回。如果某些元素没有键,则将它们从零开始编号。
event
Window closed event
要遵循的另一个约定是检查是否用X关闭窗口。 这是非常重要的事件。如果不检查此内容而尝试使用该窗口,则程序将崩溃。请检查关闭的窗口并正常退出程序。完成操作后,请关闭窗口,即使退出程序也会关闭它们。如果您不关闭窗口,则tkinter有时会生成错误/警告。
当用户单击X关闭窗口时,不返回任何内容。 如果您的窗口有一个事件循环,需要反复读取它,请记住给您的用户一个“输出”。您应该始终检查None值,并且提供某种“退出”按钮是一种好习惯。
event, values = window.Read() if event in (None, 'Exit'): break
if event is None or event == 'Exit': break
Button Click Events
默认情况下,按钮将始终返回单击事件,对于实时按钮,则始终返回按钮按下事件。您无需执行任何操作即可启用按钮单击。要禁用事件,请使用其Update方法禁用按钮。
可以通过enable_events=True在Button调用中进行设置来启用其他“ Button Modified”事件。这些事件在某个按钮“写入”时触发,通常是因为该按钮在另一个按钮中被列为“目标”。
“读取”调用中的按钮值将是2个值之一:1.按钮的文本-默认值2.按钮的键-如果指定了键。如果在创建按钮时设置了键,则无论该按钮上显示什么文本,都将返回该键。如果未设置任何键,则返回按钮文本。如果未单击任何按钮,但是窗口仍然返回,则事件值是导致事件生成的键。例如,如果enable_events在Input元素上设置,并且有人在该Input框中键入字符,则事件将是输入框的键。
Element Events
Name events InputText any change Combo item chosen Option menu item chosen Listbox selection changed Radio selection changed Checkbox selection changed Spinner new item selected Multiline any change Text clicked Status Bar clicked Graph clicked TabGroup tab clicked Slider slider moved Table row selected Tree node selected ButtonMenu menu item chosen Right click menu menu item chosen
Other Events
Menubar menu item chosen for MenuBar menus and ButtonMenu menus
您将收到MenuBar和ButtonMenu的键。使用该键读取返回值字典中的值。显示的值将是所选菜单项的全文加号。请记住,您可以将按键放在菜单项上。您将在菜单定义中定义的文本和键一起获得。
Right Click menu item chosen
与菜单栏和按钮菜单不同,您将直接接收菜单项文本及其键值。您不会进行字典查找来获取值。它是WindowRead()返回的事件代码。
Windows - keyboard, mouse scroll wheel
Windows能够返回键盘事件。如果是特殊键,则以单个字符或字符串形式返回。鼠标滚轮事件也是字符串。在代码中放入打印件以查看返回的内容。
Timeouts
如果您在读取中设置了超时参数,则将返回系统TIMEOUT_KEY。如果您在Read调用中指定了自己的超时键,则将返回该值。
values
对于返回值,从上到下,从左到右扫描窗口。作为输入字段的每个字段都将在返回值中占据一个位置。如果key在创建元素时未指定a ,则会为您创建一个,它们是从0开始的整数。如果布局中没有带键的元素,那么它将是一个列表。但是,某些元素(如某些按钮)会自动添加一个键。 最好在所有输入类型元素上使用键。
默认情况下,返回值是列表,每个输入字段一个条目,但是对于除最简单的Windows之外的所有窗口,返回值都是字典。这是因为您可能会在布局中使用“键”。当您这样做时,它将强制返回值成为字典。 作为输入元素的每个元素在返回值列表中都有一个值。如果您确定这些值将作为列表返回,那么您可能会很聪明并将其直接解压缩为变量。
要获取输入字段的值,请使用用作key值的任何值作为索引值。因此,要获取名称字段的值,将其写为,values['_NAME_']
一种约定是,键名全部用大写字母开头,结尾处带有下划线。您无需执行此操作...您的键值可能如下所示: key = '_NAME__' 这种命名约定的原因是,当您扫描代码时,这些键值会跳出来。您立即知道这是关键。尝试扫描上面的代码,看看是否弹出这些键。 key = '_NAME__'
event, (filename, folder1, folder2, should_overwrite) = sg.Window('My title', window_rows).Read()
event, values = sg.Window('My title', window_rows).Read() event, value_list = window.Read() value1 = value_list[0] value2 = value_list[1]
有很多输入字段时,此方法不好。如果您在窗口中插入一个新元素,那么您将不得不整理您的解压缩包,将每个语句修改为reference value_list[x]。 更为常见的方法是通过将键放在“重要”元素(您希望从中获取值并希望与之交互的元素)上来将您的值作为字典返回。
Custom window API Calls自定义窗口API
步骤:1.在纸上绘制GUI 2.将GUI分成几行3.用Element名称标记每个Element 4.使用标签作为伪代码编写Python代码
PySimpleGUI中自定义窗口的关键是将窗口视为GUI元素的行。每行被指定为这些元素的列表。将各行放在一起,您将获得一个窗口。这意味着GUI被定义为一系列列表,这是一种Python的事物查看方式。
两种类型的窗口。1.持久窗口- Window.Read()方法返回,并且该窗口继续可见。这对于诸如聊天窗口或计时器之类的应用程序或在屏幕上保持活动状态的应用程序非常有用。2.异步窗口-最棘手的窗口。必须格外小心。例如MP3播放器或状态仪表板。异步窗口会定期更新(刷新)。您可以轻松发现它们,因为它们将timeout在读取调用中具有一个参数。 event, values = window.Read(timeout=100)
import PySimpleGUI as sg layout = [[sg.Text('Enter a Number')], [sg.Input()], [sg.OK()] ] event, values = sg.Window('Enter a number example', layout).Read() sg.Popup(event, values[0])
浏览文件按钮是一件棘手的事情。值得庆幸的是,PySimpleGUI负责将其与它旁边的输入字段相关联。结果,该代码看起来几乎就像纸上的窗口一样。 import PySimpleGUI as sg layout = [[sg.Text('Filename')], [sg.Input(), sg.FileBrowse()], [sg.OK(), sg.Cancel()] ] event, values = sg.Window('Get filename example', layout).Read() sg.Popup(event, values[0])
Common Element Parameters通用元素参数
key
与window.FindElement和返回值一起使用
键是一种使用值“标记”元素的方法,该值将用于标识该元素。将键放入元素的定义中后,从Read返回的值将使用该键告诉您该值。例如,如果您有一个输入字段:Input(key='mykey') 您的阅读如下: event, values = Read() 然后从读取中获取输入值将是: values['mykey'] 如果要在元素上调用Update,则还可以使用相同的键。请参阅下面有关更新的部分以了解该用法。 键可以是任何东西。假设您有一个带有输入元素网格的窗口。您可以将它们的行和列位置用作键(元组 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
tooltip
将鼠标悬停在要素上,您将看到带有此文本的弹出窗口
如果您希望对窗口的用户更加友善,则可以通过将参数设置tooltip为某些文本字符串来为其创建工具提示。您将需要提供自己的换行符/文本换行。如果您不想手动添加它们,请查看标准库包textwrap。
可以通过设置TOOLTIP_BACKGROUND_COLOR为您选择的颜色字符串来更改PySimpleGUI的tkinter版本上工具提示的背景颜色。颜色的默认值为: TOOLTIP_BACKGROUND_COLOR = "#ffffe0"
size
宽度,高度)-通常以字符宽,行高为单位进行度量。有时他们的意思是像素
指定为元素保留的空间量。对于基于字符的元素(例如文本),它是 (# characters, # rows)。有时它是像素测量,例如Image元素。有时还会像Slider元素(字符长像素宽)上的混合。某些元素(文本和按钮)具有on默认情况下的自动调整大小设置。它将根据内容确定元素的大小。结果是按钮和文本字段将是创建它们的字符串的大小。您可以关闭它。例如,对于“按钮”,效果是该窗口中所有按钮的大小均相同。
在非tkinter端口中,可以通过2种方式设置特定的元素大小。一种是size像以前一样使用常规参数。这将是字符和行。另一种方法是使用新参数size_px。此参数允许您直接以像素为单位指定大小。设置为size_px=(300,200)将会创建300 x 200像素的元素。 此外,如果尺寸超过转换阈值size,则还可以使用参数指示像素。 这意味着什么?这意味着如果您的宽度> 20(DEFAULT_PIXEL_TO_CHARS_CUTOFF),则假定您是在说像素,而不是字符。但是,某些“通常较大”的元素的截断值为100。例如,这些元素包括Multline和Output元素。 如果您对用于进行字符到像素转换的数学方法感到好奇,那么它是很粗糙的,但是功能丰富。借助以下变量完成转换:DEFAULT_PIXELS_TO_CHARS_SCALING = (10,26),转换只是将您的size[0]乘以10,然后将您的size[1]乘以26。
Colors
颜色名称或#RRGGBB字符串
代表颜色的字符串。只要涉及到颜色,就可以指定tkinter颜色名称,例如'lightblue'或RGB十六进制值'#RRGGBB'。对于按钮,color参数是一个元组(文本颜色,背景颜色) 任何时候在PySimpleGUI中将颜色写为元组时,找出哪种颜色是背景的方法就是用单词“ on”替换“,”。(“白色”,“红色”)指定一个按钮,该按钮为“红色上的白色”。适用于有颜色元组的任何地方。
从2.5版开始,您可以更改窗口和Elements的背景颜色。
尽管您可以逐个元素或逐个窗口级别进行操作,但到目前为止,最简单的方法是调用SetOptions。 请注意,一旦更改了这些选项,它们就会在程序的其余执行过程中被更改。在您将其更改为其他名称(可能是系统默认颜色)之前,所有窗口均具有该外观。 此调用设置所有不同的颜色选项。 SetOptions(background_color='#9FB8AD', text_element_background_color='#9FB8AD', element_background_color='#9FB8AD', scrollbar_color=None, input_elements_background_color='#F7F3EC', progress_meter_color = ('green', 'blue') button_color=('white','#475841'))
Pad
元素周围的填充量
元素周围的空间量(以像素为单位)。默认值为(5,3),这意味着在x轴的每一侧保留5个像素,在y轴的每一侧保留3个像素。您可以使用SetOptions调用在全局基础上或在元素基础上进行更改。 如果您希望一侧上的像素多于另一侧,则可以将数字分成2个数字。如果要在左侧200像素,在右侧3像素,则填充为((200,3),3)。在此示例中,仅x轴被拆分。
Font
指定字体系列,大小和样式。Windows上的字体家族包括:* Arial * Courier * Comic, * Fixedsys * Times * Verdana * Helvetica (我认为是默认设置),字体因系统而异,但是,Tk 8.0会在所有平台上自动将Courier,Helvetica和Times映射到其对应的本机姓氏。同样,字体家族不能导致Tk 8.0及更高版本上的字体规范失败。 如果您希望将字体系列保留为默认设置,则可以将非字体名称的任何内容作为字体。 有2种格式可用于指定字体...字符串和元组Tuple-(系列,大小,样式)字符串-“ Family Size Styles” 若要指定带下划线的Helvetica字体,其值的大小为15 :(“ Helvetica”,15,“ underline italics”),“ Helvetica 15 underline italics”
visible
使元素出现和消失
您可以创建最初不可见的元素,以后可以使它们可见。要创建不可见的元素,请像平常一样将元素放置在布局中并添加参数 visible=False。 当您希望使该Element可见时,您只需调用Element的Update方法并传递参数visible=True visible参数也可以与Column and Frame“容器”元素一起使用。
enable_events
-打开特定于元素的事件
SetOptions(icon=None button_color=(None,None) element_size=(None,None), margins=(None,None), element_padding=(None,None) auto_size_text=None auto_size_buttons=None font=None border_width=None slider_border_width=None slider_relief=None slider_orientation=None autoclose_time=None message_box_line_width=None progress_meter_border_depth=None progress_meter_style=None progress_meter_relief=None progress_meter_color=None progress_meter_size=None text_justification=None text_color=None background_color=None element_background_color=None text_element_background_color=None input_elements_background_color=None element_text_color=None input_text_color=None scrollbar_color=None, text_color=None debug_win_size=(None,None) window_location=(None,None) tooltip_time = None
参数说明 icon button_color - button color (foreground, background) element_size - element size (width, height) in characters margins - tkinter margins around outsize element_padding - tkinter padding around each element auto_size_text - autosize the elements to fit their text auto_size_buttons - autosize the buttons to fit their text font - font used for elements border_width - amount of bezel or border around sunken or raised elements slider_border_width - changes the way sliders look slider_relief - changes the way sliders look slider_orientation - changes orientation of slider autoclose_time - time in seconds for autoclose boxes message_box_line_width - number of characers in a line of text in message boxes progress_meter_border_depth - amount of border around raised or lowered progress meters progress_meter_style - style of progress meter as defined by tkinter progress_meter_relief - relief style progress_meter_color - color of the bar and background of progress meters progress_meter_size - size in (characters, pixels) background_color - Color of the main window's background element_background_color - Background color of the elements text_element_background_color - Text element background color input_elements_background_color - Input fields background color element_text_color - Text color of elements that have text, like Radio Buttons input_text_color - Color of the text that you type in scrollbar_color - Color for scrollbars (may not always work) text_color - Text element default text color text_justification - justification to use on Text Elements. Values are strings - 'left', 'right', 'center' debug_win_size - size of the Print output window window_location - location on the screen (x,y) of window's top left cornder tooltip_time - time in milliseconds to wait before showing a tooltip. Default is 400ms
Global Settings
让我们进行一些有趣的自定义!使PySimpleGUI看起来像您想要的样子。您可以使用功能设置全局设置PySimpleGUI.SetOptions。每个选项都有一个用于设置它的可选参数。
这些设置适用于所有窗口SetOptions。“行”选项和“元素”选项将优先于这些设置。可以将设置视为设置级别,其中窗口级别为最高,元素级别为最低。因此,级别为: 窗口水平 行级 元素等级 每个较低级别将覆盖较高级别的设置。更改设置后,在程序执行期间它们将保持更改状态(除非再次更改)。
Creating a Windows .EXE File
可以创建一个可以分发给Windows用户的.EXE文件。无需在要运行其的PC上安装Python解释器。假设您运行的是Windows的最新版本,它需要的所有内容都在一个EXE文件中。 安装软件包后,您需要安装PySimpleGUI和PyInstaller(只需安装一次) pip install PySimpleGUI pip install PyInstaller 要从使用PySimpleGUI的程序创建EXE文件,请 my_program.py在Windows命令提示符下输入以下命令: pyinstaller -wF my_program.py 您将只剩下一个文件, my_program.exe位于dist 执行pyinstaller 命令的文件夹下命名 的文件夹中 。 仅此而已... my_program.exe 在您选择的Windows计算机上运行 文件。 “就是这么简单。” (著名的遗言几乎使所有被引用的东西搞砸了) 您的EXE文件应该在没有创建“外壳窗口”的情况下运行。仅GUI窗口应显示在任务栏上。 如果您因以下原因而崩溃: ValueError: script '.......\src\tkinter' not found 然后尝试添加--hidden-import tkinter到您的命令
Creating a Mac App File
在Mac上运行此命令 pyinstaller --onefile --add-binary ='/ System / Library / Frameworks / Tk.framework / Tk':'tk'--add-binary ='/ System / Library / Frameworks / Tcl.framework / Tcl':' tcl'your_program.py
Fun Stuff
Debug Output
调试输出 确保并检查高级API部分中描述的EasyPrint(打印)功能。保持代码原样,将stdout和stderror路由到滚动窗口。 玩得开心,将这些行添加到脚本的顶部 import PySimpleGUI as sg print = sg.Print 这会将您的所有打印语句转换为显示在屏幕窗口而不是终端中的打印。
Look and Feel
外观 使用该SetOptions功能拨打您喜欢的外观。您可以在一个函数调用中更改所有默认值。一行代码来自定义整个GUI。 或从2.9版开始,您可以使用预定义的配色方案从外观上进行选择。使用描述字符串调用ChangeLookAndFeel。 sg.ChangeLookAndFeel('GreenTan') 描述字符串的有效值为: GreenTan LightGreen BluePurple Purple BlueMono GreenMono BrownBlue BrightColors NeutralBlue Kayak SandyBeach TealMono 要查看最新的颜色选择列表,请查看PySimpleGUI.py文件底部的ChangLookAndFeel功能。 您也可以将该ChangeLookAndFeel功能与该SetOptions功能结合使用,以快速修改其中一种罐装配色方案。也许您喜欢这些颜色,但边框却更深。您可以完全拨打所需的电话。
ObjToString
是否曾经想过轻松地轻松显示对象内容?使用ObjToString可以很好地格式化对象的递归遍历。 这个说法: print(sg.ObjToSting(x)) 这是输出 <class '__main__.X'> abc = abc attr12 = 12 c = <class '__main__.C'> b = <class '__main__.B'> a = <class '__main__.A'> attr1 = 1 attr2 = 2 attr3 = three attr10 = 10 attrx = x 您会很快想知道如果没有它怎么编码。
Known Issues
虽然不是“问题”,但这是严厉的警告 不要尝试PySimpleGUI从多个线程进行调用!它tkinter基于并且tkinter有多个线程的问题
进度计 - 计的可视图形部分可能已关闭。将来可能会返回到本机tkinter进度表解决方案。现在,使用“自定义”进度表。从好的方面来说,所示的统计信息非常准确,并且可以告诉您一些有关代码性能的信息。如果您同时使用来运行2个或更多进度表,则OneLineProgressMeter需要使用“取消”按钮而不是X来关闭进度表
异步窗口 -这些包括“简易”窗口(OneLineProgressMeter和EasyPrint / Print)。如果您开始重叠打开异步窗口和普通窗口,那么事情就会变得更加松散。仍在跟踪问题,并使其每天变得更加可靠。看到空白窗口时,您会知道有问题。
EasyPrint -EasyPrint是一项很棒的新功能。您进行打印,输出将进入带有滚动条的窗口,您可以从中进行复制和粘贴。作为一项新功能,它存在一些潜在的问题。与其他GUI窗口存在已知的交互问题。例如,关闭“打印”窗口也可以关闭其他打开的窗口。现在,在其他窗口也关闭之前,请不要关闭调试打印窗口。