2.1 設(shè)計(jì)GUI之PySimpleGUI的基礎(chǔ)教程

學(xué)習(xí)資源Trinket: PySimpleGUI Program

PySimpleGUI 是一個十分 Pythonic 的 GUI 框架。為了敘述方便將 PySimpleGUI 簡記為 sg,窗口(Window)主題有超過 100 個可供選擇,您可以使用函數(shù) sg.preview_all_look_and_feel_themes() 查看所有主題。切換主題需要使用回調(diào)函數(shù) sg.change_look_and_feel("主題名稱")

import PySimpleGUI as sg

# 變換主題
sg.change_look_and_feel('Material1')

下面將討論 PySimpleGUI 的幾個核心組件,雖然每個組件的參數(shù)可能很多,但是我們只需要了解其核心參數(shù)即可,所以,下面的介紹僅僅列出函數(shù)的核心參數(shù),比如像 sg.Window(title, layout, size=(5, 1)) 這種形式。

1 sg.Popup 設(shè)計(jì) I/O

sg.Popupprint 相當(dāng)(用于輸出(Output)),它創(chuàng)建了一個支持任意數(shù)量的任意 Python 支持的數(shù)據(jù)類型作為參數(shù)輸入的 Window。變體有:sg.PopupOKsg.PopupOKCancel,sg.PopupCancelsg.PopupError,sg.PopupAutoClose,sg.PopupYesNosg.PopupTimed。

關(guān)于輸入(Input)可以使用 sg.PopupGetText,sg.PopupGetFilesg.PopupGetFolder 獲取用戶的文本,文件,文件夾輸入。

2 sg.Window 創(chuàng)建窗口

GUI 的設(shè)計(jì)目標(biāo)一般都需要有一個用于和用戶進(jìn)行交互的窗口(Window)界面,為此 PySimpleGUI 提供 sg.Window 類創(chuàng)建窗口。使用方法:sg.Window(title, layout) ,其中 title 表示窗口的標(biāo)題,layout 指定窗口的布局。

圖1 一個簡單的 Window 布局

圖1 提供了一個自定義 Window 布局以及如何使用其與用戶交互的例子。下面對圖1 的代碼進(jìn)行拆解。第 7~9 行定義了 Window 的布局,第 12 行定義了一個 Window,第 14~23 行定義了 Window 的交互方法,第 24 行將 Window 關(guān)閉以釋放資源。其中 sg.Textsg.T == sg.Text == sg.Txt)會將字符串打印到 Window,sg.Inputsg.I == sg.InputText == sg.Input == sg.In)用于獲取用戶的輸入,sg.Button(sg.B == sg.Button)表示 Window 的按鈕。下面看看 Window.Read 的輸出:

圖2 測試 Window.Read 的輸出

從圖2 可以看出 values 是關(guān)鍵字為數(shù)字序號的 dict,而 event 一般代表 Window 的按鈕。然而,若 Window 中的 sg.Input 很多,我們僅僅依靠數(shù)字序號將十分不方便,為此我們需要傳入 key 修改 dict 的關(guān)鍵字。具體實(shí)現(xiàn)見圖3。

圖3 修改 sg.In 的關(guān)鍵字

接下來您便可以使用關(guān)鍵字獲取對應(yīng)的表單數(shù)據(jù)。

3 在窗口顯示用戶輸入

窗口 sg.Window 的元素可以通過類似于 dict 的方式進(jìn)行更新及獲取:

圖4 在窗口顯示用戶輸入

圖4 顯示了 sg.Window元素(也可稱為“小部件”,“組件”)可以通過關(guān)鍵字(即 -OUTPUT-)獲取,使用 update 方法更新。

這里的sg.Window元素,即:

IN = window['-IN-']
IN

顯示為:

<PySimpleGUI.PySimpleGUI.InputText at 0x20d358068c8>

獲取該元素的值:

IN.get()

顯示結(jié)果為:

'平安是福'

4 創(chuàng)建 To Do List

下面我們創(chuàng)建 To Do 表單:

圖5 創(chuàng)建 To Do List

圖5 中 出現(xiàn)了復(fù)選項(xiàng) sg.CBox,它的返回值是 True 或者 False,而 window.save_to_disk('ToDoList.out') 將 Window 的配置保存在磁盤,window.load_from_disk('ToDoList.out') 載入磁盤保存的 Window 配置。

5 創(chuàng)建菜單欄

先上代碼:

import PySimpleGUI as sg

# ------ Menu Definition ------ #
menu_def = [['&File', ['&Open', '&Save', 'E&xit', 'Properties']],
            ['&Edit', ['Paste', ['Special', 'Normal', ], 'Undo'], ],
            ['&Help', '&About...']]

relief_list = [sg.RELIEF_RAISED, sg.RELIEF_SUNKEN, sg.RELIEF_FLAT, 
               sg.RELIEF_RIDGE, sg.RELIEF_GROOVE, sg.RELIEF_SOLID]

def layout_relief(element):
    return sg.Text(element,
                   size=(30, 1), justification='center', 
                   font=("Helvetica", 25), relief=element)
    

layout = [[sg.Menu(menu_def, tearoff=True)]]
layout += [[layout_relief(element)] for element in relief_list]

window = sg.Window('Everything bagel', layout, default_element_size=(40, 1), grab_anywhere=False)
event, values = window.read()
window.close()

menu_def 定義了多級菜單欄,relief_list 展示了文本顯示的樣式,sg.Text 的參數(shù) size=(30, 1) 表示文本框是寬30個字符,高1個字符。具體效果見圖6:

圖6 創(chuàng)建多級菜單欄

6 方法名稱簡寫

  1. 下拉列表:Combo == InputCombo == DropDown == Drop
  2. 文本輸入:InputText == Input == In
  3. 復(fù)選框:CBox == CB == Check
  4. 按鈕:Button== ReadButton == RButton == ReadFormButton
  5. 多行文本框:Multiline == MLine

7 “選擇器” 按鈕

“選擇器” 按鈕("Chooser" Buttons)會彈出一個對話框用于選擇 filename, date, color 等等。這些按鈕直接可以通過名稱便可以知道其代表的含義,即 FileBrowse, FolderBrowse, FileSaveAs , FilesSaveAs, CalendarButton, ColorChooserButton。比如使用 FolderBrowse 打開文件夾并將文件夾名稱傳遞給 sg.In,效果圖見圖7:

圖7 打開文件夾并將文件夾名稱傳遞給 `sg.In`

也可以自定義按鈕:layout = [[sg.Button('My Button', key='_BUTTON_KEY_')]]。

8 其他方法簡介

  1. Listbox 示例:layout = [[sg.Listbox(values=['Listbox 1', 'Listbox 2', 'Listbox 3'], size=(30, 6))]],效果見圖8:
圖8 Listbox + 帶表頭的表格
  1. 多行文本輸入輸出:sg.Multiline,效果見圖9:
圖9 多行輸入輸出
  1. Slider(滑動條)sg.Slider,效果見圖10:
圖10 滑塊
  1. 單選 sg.Radio 與多選 sg.Checkbox,具體效果見圖11:
圖11 單選與復(fù)選項(xiàng)

需要注意的是 sg.Radio 的第2個參數(shù)是用來標(biāo)識此選項(xiàng)是否歸屬于指定的 ID。

  1. 上/下微調(diào)控件(An up/down spinner control)sg.Spin,效果圖見圖12:
圖12 上/下微調(diào)控件
  1. Progress Meter
import PySimpleGUI as sg

# layout the window
layout = [[sg.Text('A custom progress meter')],
          [sg.ProgressBar(1000, orientation='h', size=(20, 20), key='progressbar')],
          [sg.Cancel()]]

# create the window`
window = sg.Window('Custom Progress Meter', layout)
progress_bar = window['progressbar']
# loop that would normally do something useful
for i in range(1000):
    # check to see if the cancel button was clicked and exit loop if clicked
    event, values = window.read(timeout=10)
    if event in ['Cancel', 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()

效果圖見圖13:

圖13 進(jìn)度條

7 Column

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

window = sg.Window('Compact 1-line window with column', layout)
event, values = window.read()
window.Close()

sg.Popup(event, values, line_width=200)

顯示效果見圖14:

圖14 數(shù)據(jù)列
  1. 運(yùn)行 sg.main() 有驚喜,截圖見圖15:
圖15 sg.main
  1. 創(chuàng)建一個控制面板(資料來源:)

代碼(圖片被轉(zhuǎn)換為了Base64字符):

import PySimpleGUI as sg

"""
    Creates a grid of buttons include of a column for scrolling
    This window looks much like a control panel
    
    NOTE - The SCROLLING using the mousewheel is known to have a bug in the tkinter port.  You will need to have your mouse over the scrollbar to scroll with the mousewheel
"""

def GraphicButton(text:str, key:str, image_data):
    text = text.replace('_', ' ')
    button = sg.Button('', image_data=image_data, button_color=('white', '#9FB8AD'), font='Any 15', key=key, border_width=0)
    text = sg.Text(text, font='Any 10', size=(15,1), justification='center',)
    return sg.Column([[button],[text]], element_justification='c')

def main():
    sg.ChangeLookAndFeel('GreenTan')

    layout  = [ [sg.Text('Control Panel. Click Abort to exit.')]]
    layout += [[sg.Column([[GraphicButton(png_names[i+j*5], png_names[i+j*5] , png_images[i+j*5]) for i in range(2)] for j in range(7)], scrollable=True, size=(400,400))]]

    window = sg.Window('Control Panel', layout, font='any 15', finalize=True)
    while True:                               # ---===--- The event loop --- #
        event, values = window.read()
        print(event)
        if event in ('Exit','Abort', None):   # Exit button or X
            break
    window.close()


Abort = b"..."
...
vars = dir()
png_images = []
png_names = []
for var in vars:
    png_images.append(eval(var))
    png_names.append(var)

main()

顯示效果圖見圖16:

圖16 控制面板
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。