advPython-6

pySimpleGUI-练习篇

界面英汉转换

""" 版本1.0 """
import PySimpleGUI as sg

layout = [
    [sg.B("中文"), sg.B("English")],
    [sg.T("请输入基本信息!", key='-TIP-')],
    [sg.T('姓名', key='-NAME-', size=(8, 1)), sg.In()],
    [sg.T('性别', key='-GENDER-', size=(8, 1)), sg.In()],
    [sg.T('国籍', key='-NATIONALITY-', size=(8, 1)), sg.In()],
    [sg.B("确认", key='-Y-'), sg.B("取消", key='-N-')]
]

window = sg.Window('Python pySimpleGUI', layout)

while True:
    event, values = window.read()
    print(event)

    if event == None:
        break

    if event == 'English':
        window["-TIP-"].update(value='Please enter basic infomation!')
        window["-NAME-"].update(value='Name')
        window["-GENDER-"].update(value='Gender')
        window["-NATIONALITY-"].update(value='Nationality')
        window['-Y-'].update('Confirm')
        window['-N-'].update('Cancel')

    if event == "中文":
        window["-TIP-"].update("请输入基本信息!")
        window["-NAME-"].update("姓名")
        window["-GENDER-"].update("性别")
        window["-NATIONALITY-"].update("国籍")
        window['-Y-'].update('确定')
        window['-N-'].update('取消')

window.close()

下拉菜单的更新方法

import PySimpleGUI as sg

dictionary = {'小明': 'Python', '小王': 'Java', '小花': 'C', '小壮': 'c++', '小美': 'Gui'}
list1 = [name for name in dictionary]

layout = [
    [sg.Combo(list1, key='-list1-', size=(30, 6), enable_events=True, default_value='小明')],
    [sg.T("语言"), sg.In(key='-INPUT-', size=(22, 1))]
]

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

while True:
    event, values = window.read()
    print(event, values)

    if not event:
        break

    if event == '-list1-':
        window['-INPUT-'].update(dictionary[values['-list1-']])

window.close()

图片格式转换base64

# 如何获取 图片的 base64 格式?以下代码可以实现:
import base64

f = open('图片路径', 'rb')  # 重点!千万要记得写’rb‘模式,否则,默认会用’rt‘模式读取图片,从而报错!
res = f.read()
s = base64.b64encode(res)
print(s)
f.close()

窗口上调用字典的键和值

import PySimpleGUI as sg

dictionary = {'小明': 'Python', '小王': 'Java', '小花': 'C', '小壮': 'c++', '小美': 'Gui'}
list1 = [name for name in dictionary]

layout = [
    [sg.LB(list1, key='-list-', size=(30, 6), enable_events=True)],
    [sg.T("语言"), sg.In(key='-INPUT-', size=25)]
]

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

while True:
    event, values = window.read()
    print(event, values)

    if not event:
        break
    if event == "-list-":
        name = values['-list-'][0]
        window["-INPUT-"].update(dictionary[name])

window.close()

多窗口

import PySimpleGUI as sg

# 主题
sg.theme('GreenTan')

layout0 = [
    [sg.Button("window1", size=(20, 3)), sg.Button("window2", size=(20, 3))]
]
win0 = sg.Window("window0", layout0, default_element_size=(10, 1))

win1_active = False
win2_active = False

while True:
    ev0, vals0 = win0.read(timeout=10000)  # 大概10秒超时

    # (一)反应超时,自动启动read,并且返回值:ev0 == '__TIMEOUT__'
    if ev0 == '__TIMEOUT__':
        break  # 结束最外层的事件循环,退出整个程序

    # (二)反应未超时,即可进行下面的步骤:

    # 记录当前窗口活动状态
    win0_active = True

    # 退出操作
    if ev0 == sg.WIN_CLOSED or ev0 == 'Exit':
        break

    # 点击window1操作
    if ev0 == "window1" and not win1_active:
        win1_active = True
        win0.hide()
        layout1 = [
            [sg.Button("win1")],
            [sg.Input("12312", key="-12-")]
        ]
        win1 = sg.Window("window1", layout1, default_element_size=(10, 1))
        while True:
            ev1, vals1 = win1.read(timeout=100)
            if ev1 == sg.WIN_CLOSED or ev1 == 'Exit':
                win1_active = False
                win1.close()
                win0.UnHide()
                break

    # 点击window1操作
    if ev0 == "window2" and not win2_active:
        win2_active = True
        win0.hide()
        layout2 = [
            [sg.Button("win2")],
            [sg.Input("123123", key="-13-")]
        ]
        win2 = sg.Window("window2", layout2, default_element_size=(10, 1))
        while True:
            ev2, vals2 = win2.read(timeout=100)
            if ev2 == sg.WIN_CLOSED or ev2 == 'Exit':
                win2_active = False
                win2.close()
                win0.UnHide()
                break

win0.close()

登录窗口练习

import PySimpleGUI as sg

layout = [
    [sg.T("用户名", size=(8, 1)), sg.In("请输入您的用户名", key='-NAME-')],
    [sg.T("密码", size=(8, 1)), sg.In(key='-PASS-', tooltip='密码为3位数', password_char='*')],
    [sg.B('确认输入'), sg.B('清空输入'), sg.B('保存密码'), sg.B('取消保存')],

]

window = sg.Window("Python 练习窗", layout)

# 用户信息
user1 = {'用户名': '小明', '密码': '136'}
user2 = {'用户名': '叶寻', '密码': '135'}
users = [user1, user2]

# 当事件为'保存密码‘时候的操作,变量 switch = 0
switch = 0

while True:

    event, values = window.read()


    def judge(n):

        for user in users:
            if user['用户名'] == values["-NAME-"]:  # 检验账户是否匹配
                if user['密码'] == values['-PASS-']:  # 检验密码是否匹配
                    sg.popup("登录成功")
                    if n == 0:
                        window['-PASS-'].update(value='')  # 登录成功后,默认清空密码信息
                    break

                else:
                    sg.popup("密码错误")
                    break
        else:
            sg.popup("输入错误")


    if not event:
        break

    if event == '确认输入':
        judge(switch)

    if event == '清空输入':
        window['-NAME-'].update(value='')
        window['-PASS-'].update(value='')

    if event == '保存密码':
        switch = 1

    if event == '取消保存':
        switch = 0

window.close()

实现一个红绿灯

"""
3.点击后,更新效果
"""
import PySimpleGUI as sg

layout = [
    [sg.B(
        key='-BA-',
        button_text="绿灯",
        size=(16, 8),
        button_color=('black', 'green')  # 按钮的 文本颜色 和 背景颜色

    )], [sg.B(
        key='-BB-',
        button_text="黄灯",
        size=(16, 8),
        button_color=('black', 'yellow')

    )], [sg.B(
        key='-BC-',
        button_text="红灯",
        size=(16, 8),
        button_color=('black', 'red')

    )]
]

window = sg.Window('Python Light', layout)

while True:
    event, values = window.read()
    print(event)

    if not event:
        break


    def one():
        window['-BA-'].update(
            button_color=('black', 'grey'),  # 按钮颜色
        )


    def two():
        window['-BB-'].update(
            button_color=('black', 'grey'),  # 按钮颜色
        )


    def three():
        window['-BC-'].update(
            button_color=('black', 'grey'),  # 按钮颜色
        )


    def fix():
        window['-BA-'].update(button_color=('black', 'green'))
        window['-BB-'].update(button_color=('black', 'yellow'))
        window['-BC-'].update(button_color=('black', 'red'))


    if event == '-BA-':
        # 先集体自我变色(即初始化界面,防止它有上次残留的颜色)
        fix()
        # 初始化完成后,继续完成‘专项变色’
        two()
        three()

    if event == '-BB-':
        # 先集体自我变色(即初始化界面,防止它有上次残留的颜色)
        fix()
        # 初始化完成后,继续完成‘专项变色’
        one()
        three()

    if event == '-BC-':
        # 先集体自我变色(即初始化界面,防止它有上次残留的颜色)
        fix()
        # 初始化完成后,继续完成‘专项变色’
        one()
        two()

window.close()

实现一个计算器

import PySimpleGUI as sg


def button(x):
    return sg.Button(x, size=(4, 2), button_color='black', pad=(2, 2), font=('黑体', 18))


layout = [
    [sg.Text('', key='-SHOW-')],
    [sg.InputText('', key='-INPUT-', size=(19, 2), font=('黑体', 18))],
    [button(i) for i in ['AC', '(', ')', '%']],
    [button(i) for i in '123+'],
    [button(i) for i in '456-'],
    [button(i) for i in '789X'],
    [button(i) for i in '0.=÷'],
]

window = sg.Window('计算器', layout)

while True:
    event, values = window.read()
    print(event, values)

    if not event:
        break

    if event in list('0123456789+-().'):
        window['-INPUT-'].update(values['-INPUT-'] + event)
        window['-SHOW-'].update('')

    if event == 'X':
        window['-INPUT-'].update(values['-INPUT-'] + '*')
        window['-SHOW-'].update('')

    if event == '÷':
        window['-INPUT-'].update(values['-INPUT-'] + '/')
        window['-SHOW-'].update('')

    if event == '%':
        # eval是内置函数,功能:返回传入的字符串的计算结果

        try:
            window['-INPUT-'].update(eval(values['-INPUT-'] + '/100'))
            window['-SHOW-'].update('')
        except:
            window['-INPUT-'].update('')
            window['-SHOW-'].update('输入有误')

    if event == '=':
        try:
            window['-INPUT-'].update(eval(values['-INPUT-']))
            window['-SHOW-'].update('')
        except:
            window['-INPUT-'].update('')
            window['-SHOW-'].update('输入有误')

    if event == 'AC':
        window['-INPUT-'].update('')
        window['-SHOW-'].update('')

window.close()

带界面的PDF合并工具

import PySimpleGUI as sg

layout = [
    [sg.Text("选择文件夹:", size=(18, 1)), sg.InputText(), sg.FolderBrowse('选择')],
    [sg.Text("输入合并后的文件名:", size=(18, 1)), sg.InputText(), sg.Button("开始合并")],
    [sg.ML(size=(80, 15))]
]

window = sg.Window('PDF 合并工具', layout)

while True:
    event, values = window.read()
    print(event, values)

    if not event:
        break

window.close()

进度条

import PySimpleGUI as sg
import time

# 布局,是一个用户定义的二维列表。
# 第一维德元素分居不同的行上,第二维度上的元素们居于同一行,不同列上
# 此处定义的列表  由三部分组成 Text文件 ProgressBar进度条 Cancel取消按钮构成
# Text Progress等有各自的参数设置,如size等。此处不再赘述


layout = [
    [sg.Text('任务完成进度')],
    [sg.ProgressBar(1000, orientation='h', size=(20, 20), key='progressbar')],
    # ProgressBar(进度条)   参数1:MaxValue:1000  orientation='h'(横向)'v'(竖向)
    [sg.Cancel()]
]

# window只需将自定义的布局加载出来即可 第一个参数是窗口标题。
window = sg.Window('机器人执行进度', layout)

# 根据key值获取到进度条
progress_bar = window['progressbar']

# 查看信息
print(progress_bar.__dict__)

# window的read函数分为同步和异步,
# 不带timeout参数即为同步函数 一直等到手动点击按钮才会返回。
# 带timeout参数不为None的为异步函数,timeout时间内,无时间或者点击了按钮都会产生结果。
# 异步方式不会阻塞后面的程序运行。

for i in range(1000):  # 循环
    event, values = window.read(timeout=10)
    # print('当前事件:', event)
    if event == 'Cancel' or event is None:
        break
    progress_bar.UpdateBar(i + 1)

# 检测 ’timeout’ 和 ‘进度条更新‘ 的本质
# i = 0
# while True:
#     event, values = window.read(timeout=888)  # timeout(暂停、超时)  当设定了 timeout = 1000 (ms),不管下面执行到哪里了,继续
#     print('当前事件:', event)
#     if event is None:
#         break
#     if event == 'Cancel':
#         print('你想干嘛')
#
#     if i < 10:
#         number = 500 + i * 50
#         progress_bar.UpdateBar(number, max=2000)
#         # 更新栏通过 '更改当前计数' 和 '最大计数'(最上面已经写了,现在使用新的值覆盖,或者不输入,使用默认)来更改条显示的内容
#         i += 1

window.close()

你可能感兴趣的:(Python进阶,python)