2.5 PySimpleGUI 的幾個(gè) Demo

1 同步改變字體大小

代碼:

import PySimpleGUI as sg
font_size = 12
layout = [[sg.Spin([sz for sz in range(6, 172)], font=('Helvetica 20'), 
                   initial_value=font_size, 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(font_size), key='text')]]

window = sg.Window("Font size selector", layout, return_keyboard_events=True, grab_anywhere=False)
# Event Loop
sz = font_size
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 != font_size else sz_slider
    if sz != font_size:
        font_size = sz
        font = "Helvetica "  + str(font_size)
        window['text'].update(font=font)
        window['slider'].update(sz)
        window['spin'].update(sz)

print("Done.")
window.close()

效果見圖1:

圖1 改變字體大小

改變圖1 中的滑塊或者 spin 均可改變字體大小。

2 捕獲鍵盤和鼠標(biāo)輸入

代碼:

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"

text_elem = sg.Text(size=(18, 1))

layout = [[sg.Text("Press a key or scroll mouse")],
          [text_elem],
          [sg.Button("Exit")]]

window = sg.Window("Keyboard Test", layout,  return_keyboard_events=True, use_default_focus=False)

# ---===--- Loop taking in user input --- #
while True:
    event, value = window.read()

    if event in ("Exit", None):
        print(event, "exiting")
        break
    else:
        text_elem.update(event)
window.close()

效果見圖2:

圖2 捕獲鍵盤和鼠標(biāo)輸入

sg.Window 中傳入?yún)?shù) return_keyboard_events=True 即可捕獲鍵盤輸入。

3 創(chuàng)建多個(gè) Windows

3.1 兩個(gè)窗口同時(shí)存在

代碼:

import PySimpleGUI as sg

# Design pattern 2 - First window remains active

layout = [[ sg.Text('Window 1'),],
          [sg.Input(do_not_clear=True)],
          [sg.Text(size=(15,1), key='_OUTPUT_')],
          [sg.Button('Launch 2'), sg.Button('Exit')]]

win1 = sg.Window('Window 1', layout)

win2_active = False
while True:
    ev1, vals1 = win1.read(timeout=100)
    win1['_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', layout2)
    if win2_active:
        ev2, vals2 = win2.read(timeout=100)
        if ev2 is None or ev2 == 'Exit':
            win2_active  = False
            win2.close()
win1.close()

效果圖見圖3:

圖3 同時(shí)存在的兩個(gè)窗口

3.2 隱藏兩個(gè)窗口中的一個(gè)

代碼:

import PySimpleGUI as sg

# Design pattern 1 - First window does not remain active
sg.change_look_and_feel('LightGreen')
layout = [[ sg.Text('Window 1'),],
          [sg.Input(do_not_clear=True)],
          [sg.Text(size=(15,1),  key='_OUTPUT_')],
          [sg.Button('Launch 2')]]
win1 = sg.Window('Window 1', layout)
win2_active=False
while True:
    ev1, vals1 = win1.read(timeout=100)
    if ev1 is None:
        break
    win1['_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', layout2)
        while True:
            ev2, vals2 = win2.read()
            if ev2 is None or ev2 == 'Exit':
                win2.close()
                win2_active = False
                win1.un_hide()
                break
win1.close()

4 主題預(yù)覽

代碼1:

import PySimpleGUI as sg

window = sg.Window('Testing the Debugger', [[sg.Text('Debugger Tester'), sg.In('Input here'), sg.B('Push Me')]])

while True:
    event, values = window.Read(timeout=500)
    if event == sg.TIMEOUT_KEY:
        continue
    if event is None:
        break
    print(event, values)
window.Close()

效果圖見圖4:

圖4 主題預(yù)覽

4.2 自選預(yù)覽主題

代碼2:

import PySimpleGUI as sg

"""
    Allows you to "browse" through the look and feel settings.  Click on one and you'll see a
    Popup window using the color scheme you chose.  It's a simple little program that also demonstrates
    how snappy a GUI can feel if you enable an element's events rather than waiting on a button click.
    In this program, as soon as a listbox entry is clicked, the read returns.
"""

sg.change_look_and_feel('Dark Brown')

layout = [[sg.Text('Look and Feel Browser')],
          [sg.Text('Click a look and feel color to see demo window')],
          [sg.Listbox(values=sg.list_of_look_and_feel_values(),
                      size=(20, 12), key='-LIST-', enable_events=True)],
          [sg.Button('Exit')]]

window = sg.Window('Look and Feel Browser', layout)

while True:  # Event Loop
    event, values = window.read()
    if event in (None, 'Exit'):
        break
    sg.change_look_and_feel(values['-LIST-'][0])
    sg.popup_get_text('This is {}'.format(values['-LIST-'][0]))

window.close()

效果圖見圖5:

圖5 自選預(yù)覽主題

5 sg.Graph 畫出條形圖

代碼:

import PySimpleGUI as sg
import random
sg.change_look_and_feel('Dark Blue 3')
BAR_WIDTH = 50
BAR_SPACING = 75
EDGE_OFFSET = 3
canvas_size = (500, 500)  # canvas 區(qū)域的 (寬, 高)
graph_bottom_left = (0, 0)  # 左下角坐標(biāo)
graph_top_right = (500, 500)  # 右上角坐標(biāo)

graph = sg.Graph(canvas_size, graph_bottom_left, graph_top_right)

layout = [[sg.Text('條形圖')],
          [graph],
          [sg.Button('OK')]]

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

while True:
    event, values = window.read()
    graph.Erase()
    if event is None:
        break

    for i in range(7):
        graph_value = random.randint(0, 400)
        graph.DrawRectangle(top_left=(i * BAR_SPACING + EDGE_OFFSET, graph_value),
                            bottom_right=(i * BAR_SPACING + EDGE_OFFSET + BAR_WIDTH, 0), fill_color='blue')
        graph.DrawText(text=graph_value, location=(
            i*BAR_SPACING+EDGE_OFFSET+25, graph_value+10))
window.close()

效果見圖6:

圖6 條形圖
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容