|
PySimpleGUI --Python图形化界面库
注:4.60.5版本及之前都是免费的,现在5.0.0版本之后开始收费了。
太贵了跑路了
安装:1 布局模板
1.1 常用布局
- import PySimpleGUI as sg
- layout = [
- [],
- [],
- [],
- [],
- [],
- ]
- #每个[]是一行
- window = sg.Window('',layout)
- while True:
- event,values = window.read()
- if event == None:
- break
- window.close()
复制代码
1.2 加号布局
- import PySimpleGUI as sg
- layout = [
- [sg.Text('请输入基本信息')],
- [[sg.Text('姓名')]+[sg.In()]]+[
- [sg.Text('性别')]+[sg.In()]]+[
- [sg.Text('国籍')]+[sg.In()]]+[
- [sg.B('确认')]+[sg.B('取消')]]
- ]
- window = sg.Window('Python布局2',layout)
- while True:
- event, values =window.read()
- if event == sg.WIN_CLOSED:
- break
- if event == '确认':
- break
- window.close()
复制代码 1.3 循环布局
- import PySimpleGUI as sg
- layout = [
- [[sg.In(i)] for i in ['姓名','性别','国籍']]
- ]
- window = sg.Window('Python',layout)
- while True:
- event, values =window.read()
- if event == sg.WIN_CLOSED:
- break
- window.close()
复制代码 2 菜单
2.1 菜单栏
- menu_def = [['&File', ['&New', '&Open', '!Save', 'E&xit', ]],
- ['&Edit', ['C&ut', '&Copy::CP', '&Paste', '&Undo'], ],
- ['&Help', '&About...'], ]
复制代码
2.2 右键菜单
- rightclick=['&Edit', ['C&ut', '&Copy','&Paste', '&Undo']]
- menu_def = [
- ['&File', ['&New', '&Open', '&Save', 'E&xit',]], rightclick,
- ['&Help', '&About...'],
- ]
- #将其用作 Window 构造函数中 right_click_menu 参数的值
- window=psg.Window("Menu", layout, size=(715, 300), right_click_menu=rightclick)
复制代码 3 弹出窗口
3.1 基本弹窗
- popup_ok − 仅显示带有 OK 按钮的 Popup
- popup_ok_cancel − 显示带有 OK 和 Cancel 按钮的弹出窗口
- popup_cancel − 显示带有"cancelled"已取消按钮文本的弹出窗口
- popup_yes_no − 显示带有 Yes 和 No 按钮的弹出窗口
- popup_error − 带有彩色按钮和"Error"错误作为按钮文本的弹出窗口
这些函数返回用户按下的按钮的文本。 例如,如果用户按下 ok-cancel 弹出窗口的 OK 按钮,它会返回 Ok,这可以在进一步的编程逻辑中使用。
以下弹出窗口接受用户以文本形式输入或让用户从选择器中选择文件/文件夹/日期。
- popup_get_text − 显示带有文本输入字段的弹出窗口。 返回输入的文本,如果关闭/取消则返回 None
- popup_get_file − 显示带有文本输入字段和浏览按钮的弹出窗口,以便用户可以选择文件。
- popup_get_folder − 显示带有文本输入字段和浏览按钮的弹出窗口,以便可以选择文件夹。
- popup_get_date − 显示一个日历窗口,获取用户的选择,以元组形式返回(mon, day, year)
- popup_scrolled − 滚动弹窗
- import PySimpleGUI as sg
- pwd = '123'
- list = ['资料1','资料2','资料3','资料4']
- while True:
- result = sg.PopupGetText('密码输入框')
- if pwd ==result :
- break
- elif result ==None:
- exit()
- else:sg.popup('密码错误')
- layoutb=[[sg.LB(list,size=(30,5))]]
- layout=[[sg.Frame('资料库',layoutb)]]
- window=sg.Window('演示',layout)
- while True:
- event, values = window.read()
- if event == None:
- break
- window.close()
- """
- sg.PopupGetFile()#文件选择弹窗
- sg.PopupGetFolder()#文件夹选择
- sg.PopupAnnoying()#没有标题栏可随意移动
- sg.PopupAutoClose()#显示一段时间自动关闭
- sg.PopupCancel()
- sg.PopupOKCancel()
- sg.PopupOK()
- sg.PopupError()
- sg.PopupNoButtons()
- """
复制代码 运行截图:
点击OK
4 元素类
Text 文本元素在窗口中显示一些文本。 通常这意味着单行文本。Input 输入元素显示单个文本输入字段。Multiline 多行元素显示和/或阅读多行文本。 这既是输入元素也是输出元素。Combo 组合元素单行输入和下拉菜单的组合。OptionMenu 元素类似于 Combo。 仅在 TKinter 端口上Checkbox 复选框元素显示复选框和旁边的文本。CBRadio 单选元素在一组其他单选元素中使用,使用户能够在选项列表中仅选择一个选项。RSpin 元素带有向上/向下按钮和单行文本的旋转器。Button 按钮元素定义所有可能的按钮。 诸如 Submit、FileBrowse 之类的快捷方式……每个都创建一个 ButtonButtonMenu 按钮菜单元素创建一个按钮,单击该按钮将显示类似于右键单击菜单的菜单。Slider 滑块元素用于递增/递减值的水平或垂直滑块。Listbox 列表框元素提供一个值列表供用户选择一个或多个。 执行 window.read() 时返回选定行的列表。Image 图像元素在窗口中显示图像。 应仅为 GIF 或 PNG。Graph 图形元素创建绘制图形的区域Canvas 画布元素绘制形状的区域ProgressBar 进度条元素显示一个彩色条,该条在某些操作的进度中带有阴影。Table 表格元素在行和列中显示数据Tree 树元素以树状方式呈现数据,很像文件/文件夹浏览器。Sizer 元素此元素用于添加更多空间。StatusBar 元素StatusBar 元素在底部创建凹陷的文本填充条。Frame 框架元素Frame 元素是一个容器对象,它包含一个或多个其他类型的元素。Column 列元素如果你想设计一个或多个垂直列表示的 GUI 窗口元素,这将非常有用。Tab 元素Tab 元素的使用使设计非常方便、有效且易于用户导航。 Tab 元素也是一个容器元素,例如 Frame 或 Column。4.1 元素类方法
set_tooltip()由应用程序调用以更改元素的工具提示文本set_focus()将当前焦点设置在此元素上set_size()将元素的大小更改为特定大小get_size()以像素为单位返回元素的大小expand()使元素扩展以填充 X 和 Y 方向的可用空间set_cursor()为当前元素设置光标set_right_click_menu()设置单击时调用的右键单击菜单5 主题
- import PySimpleGUI as sg
- print(sg.theme_list())
- sg.theme('DarkRed')
- sg.Popup('弹窗演示')
- # print(sg.theme_button_color())
- sg.theme_button_color(('black', '#ad1d45'))
- sg.Popup('演示弹窗','按键字体变黑色')
复制代码 6 将程序打包成exe
安装pysimplegui-exemaker:- pip install pysimplegui-exemaker
复制代码 运行:- python -m pysimplegui-exemaker.pysimplegui-exemaker
复制代码 7 各种例子
以下是在下学习PySimpleGUI过程中的用到的实例
7.1 下拉菜单
- import PySimpleGUI as sg
- list=['Python','JavaScript','C/C++','PHP','Java','C#','go','vue','VB']
- layout=[[sg.Drop(list,
- default_value='Python',
- key='-LIST-',
- size=(30,6),
- enable_events=None,
- bind_return_key=None,
- font=('楷体',20),
- background_color='yellow',
- text_color='red',
- pad=20,
- tooltip='列表',
- visible=True,
- auto_size_text=True
- )]]
- window=sg.Window('列表',layout)
- while True:
- event, values =window.read()
- if event == None:
- break
- if event == '-LIST-':
- print(values)
- window.close()
复制代码 7.2 下拉菜单更新
- import PySimpleGUI as sg
- #通过值获取键
- def get_keys_by_value(dictionary, value):
- keys = []
- for key, val in dictionary.items():
- if val == value:
- keys.append(key)
- return "".join(keys)
- dict ={'河南':'郑州','河北':'石家庄','浙江':'杭州','湖北':'武汉'}
- list1 = []
- list2 = []
- for i in dict:
- list1.append(i)
- for i in dict:
- list2.append(dict[i])
- layout = [[sg.Combo(list1,key='-DICT1-',size=(40,6),enable_events=True)],
- [sg.T('行政中心'),sg.Input(key='-INPUT-',size=(30))],
- [sg.Combo(list2,key='-DICT2-',size=(40,6),enable_events=True)]]
- window = sg.Window('演示',layout)
- while True:
- event, values =window.read()
- if event == None:
- break
- if event == '-DICT1-':
- window['-DICT2-'].update(dict[values['-DICT1-']])
- window['-INPUT-'].update(dict[values['-DICT1-']])
- if event == '-DICT2-':
- window['-DICT1-'].update(get_keys_by_value(dict,values['-DICT2-']))
- window.close()
复制代码 7.3 中英切换
- import PySimpleGUI as sg
- layout = [[sg.B('中文'),sg.B('English')],
- [sg.T('请输入基本信息',key='-Text1-')],
- [sg.Text('姓名',key='-Name-',size=(8,1)),sg.InputText()],
- [sg.Text('性别',key='-Sex-',size=(8,1)),sg.InputText()],
- [sg.Text('国籍',key='-Nationality-',size=(8,1)),sg.InputText()],
- [sg.Button('确认',key='-Confirm-',size=(8,1)),sg.Button('取消',key='-Cancel-')]
- ]
- window = sg.Window('Python GUI',layout)
- while True:
- event, values =window.read()
- if event ==None:
- break
- if event =='English':
- window['-Text1-'].update(value='Please enter basic information')
- window['-Name-'].update(value='Name')
- window['-Sex-'].update(value='Sex')
- window['-Nationality-'].update(value='Nationality')
- window['-Confirm-'].update(text='Confirm')
- window['-Cancel-'].update(text='Cancel')
- if event =='中文':
- window['-Text1-'].update(value='请输入基本信息')
- window['-Name-'].update(value='姓名')
- window['-Sex-'].update(value='性别')
- window['-Nationality-'].update(value='国籍')
- window['-Confirm-'].update(text='确认')
- window['-Cancel-'].update(text='取消')
- window.close()
复制代码 7.4 列元素
- import PySimpleGUI as sg
- layoutL = [[sg.T('标题')],
- [sg.In('请输入文章标题')],
- [sg.T('作者')],
- [sg.In('请输入姓名或笔名')]]
- layoutR = [[sg.ML('请输入正文内容',size=(30,20))],
- [sg.B('确认提交')],
- ]
- layout = [[sg.Col(layoutL,
- background_color='black',
- size=(200,100),
- scrollable=True,
- vertical_scroll_only=None,
- right_click_menu=None,
- visible=True,
- justification='left',
- element_justification='Center',
- vertical_alignment='top',
- grab=True,#True可以拖动
- expand_x=True,
- expand_y=True
- ),
- sg.Col(layoutR)]]
- window = sg.Window('列元素',layout)
- while True:
- event, values = window.read()
- if event == None:
- break
- window.close()
复制代码 7.5 列表
- import colorsys
- import PySimpleGUI as sg
- list=['Python','JavaScript','C/C++','PHP','Java','C#','go','vue','VB']
- layout=[[sg.LB(list,
- # default_values=['Python'],
- key='-LIST-',
- select_mode='extended',
- size=(30,6),
- enable_events=None,
- bind_return_key=None,
- font=('楷体',20),
- background_color='yellow',
- text_color='red',
- pad=20,
- tooltip='列表',
- right_click_menu=['&菜单',['粘贴','剪切','复制']],
- visible=True,
- auto_size_text=True
- )]]
- window=sg.Window('列表',layout,size=(800,600))
- while True:
- event, values =window.read()
- if event == None:
- break
- if event == '-LIST-':
- print(values)
- window.close()
复制代码 7.6 列表更新方法
- import PySimpleGUI as sg
- list1=['甲','乙','丙','丁','戊']
- list2=['子','丑','寅','卯','辰']
- layout=[[sg.LB(list1,key='-list-',size=(30,2))],
- [sg.B('天干'),sg.B('地支')],
- [sg.B('set_to_index'),sg.B('scroll_to_index')]]
- window=sg.Window('演示窗口',layout)
- while True:
- event, values =window.read()
- print(event)
- if event == None:
- break
- if event == '天干':
- window['-list-'].update(values=list1)
- if event == '地支':
- window['-list-'].update(values=list2)
- if event == 'set_to_index':
- window['-list-'].update(set_to_index=0)
- print(window['-list-'].get())
- if event == 'scroll_to_index':
- window['-list-'].update(scroll_to_index=3)
- print(window['-list-'].get())
- window.close()
复制代码 7.7 单_多选框属性设定更新
- import PySimpleGUI as sg
- import get_keys_by_value
- list=['非常满意','满意','一般','不满意']
- layout=[[sg.Text('请对这位男士做出评价(单选框)')],
- [sg.R(i,group_id=1,key=i)for i in list],
- [sg.Text('请对这位男士做出评价(多选框)')],
- [sg.CB(i,key=i)for i in list],
- [sg.B('确认提交')]
- ]
- window=sg.Window('演示界面',layout)
- while True:
- event, values = window.read()
- if event == None:
- break
- if event == '确认提交':
- for k,v in values.items():
- if v == True:
- print(k)
- window.close()
复制代码 7.8 单行输入框登录界面
- import PySimpleGUI as sg
- import 菜单
- User1={'用户名':'lisi','密码':'123'}
- User2={'用户名':'zhangsan','密码':'345'}
- UserList=[User1,User2]
- layout = [[sg.Text('账号:'),
- sg.Input(
- '请输入您的账号',
- key='-Account-',
- size=(30,None),#宽、高
- disabled=False,#元素禁用,True时无法输入任何值
- password_char=None, #密码字符
- justification='l',#对齐方式
- background_color='white',#输入框颜色
- text_color='green',
- font=('楷体',12),
- tooltip=None,#悬浮文本
- border_width=5,#边框界线宽度
- enable_events=True,#True输入值会发生一个事件
- do_not_clear=True,#True输入框内容不会被清除,False时发生事件输入会清除
- focus=True,#设定焦点,若为True,则光标显示在此输入框
- pad=None,
- disabled_readonly_background_color='black',#禁用时背景颜色
- disabled_readonly_text_color='red',#禁用时文本颜色
- right_click_menu=None,
- visible=True
- )],
- [sg.T('密码:'),sg.InputText(
- key='-Password-',
- size=(30,None),
- disabled=None,
- tooltip='3位密码',
- password_char='*',
- justification='l',
- background_color='white',
- text_color='green',
- font=('楷体',12),
- border_width=5,#边框界线宽度
- focus=False,
- )],
- [sg.B('确定'),sg.B('取消')],
- [sg.T('',key='-Text-',size=(30,None))]]
- window = sg.Window('Python GUI',layout)
- while True:
- event, values = window.read()
- if event == None:
- break
- if event == '-Account-':
- print('-Account-')
- if event == '确定':
- for user in UserList:
- if values['-Account-']==user['用户名'] and values['-Password-']==user['密码']:
- msg='输入正确'
- sg.popup(msg)
- window.close()
- 菜单.Gui()
- else:
- msg='输入有误'
- sg.popup(msg)
- break
- window.close()
复制代码 7.9 单选框
- import PySimpleGUI as sg
- lista=['非常满意','满意','一般','不满意']
- listb=['请对这位先生做出评价:','请对这位女士做出评价:']
- # layout=[
- # [sg.T('1.'+listb[0])],
- # [sg.R(i,group_id=1)for i in lista],
- # [sg.T('2.'+listb[1])],
- # [sg.R(i,group_id=2)for i in lista]
- # ]
- # layout=(
- # [[sg.T('1.'+listb[0])]]
- # +
- # [[sg.R(i,group_id=1,key='-R1-')]for i in lista]#纵向的单选框[ [sg.R()] for i in list]
- # +
- # [[sg.T('2.'+listb[1])]]
- # +
- # [[sg.R(i,group_id=2,key='-R2-')for i in lista]]
- # +
- # [[sg.B('确认',enable_events=True)]]
- # +
- # [[sg.T('',key='-Text-')]]
- # )
- layout=[[sg.T(str(y+1))]+[sg.R(x,group_id=y,key=(x,y)) for x in lista] for y in range(9)]
- window=sg.Window('演示',layout)
- while True:
- event, values =window.read()
- if event == None:
- break
- if event == '确认':
- if values['-R1-'] and values['-R2-'] != None:
- window['-Text-'].update('感谢您的评价')
- else: window['-Text-'].update('请填写完整')
- window.close()
复制代码 7.10 图片元素
- import PySimpleGUI as sg
- img =r'D:\ph\ph'
- base64_gif=sg.DEFAULT_BASE64_LOADING_GIF
- layout = [[[sg.Image(filename=img+f'{i}.png')]for i in range(1,4)],
- [sg.Image(data=base64_gif,key='-GIF-')]]
- window = sg.Window('演示',layout)
- while True:
- event, values =window.read(timeout=10)
- window['-GIF-'].update_animation(source=base64_gif,time_between_frames=110)
- if event ==None:
- break
- window.close()
复制代码 7.11 图片转编码
- import base64
- f = open(r"C:\\Users\Administrator\Pictures\视频项目\cat.jpg","rb")
- res = f.read()
- s = base64.b64encode(res)
- print(s)
- f.close()
复制代码 7.12 多行文本框
- import PySimpleGUI as sg
- text = """
- 春江潮水连海平,海上明月共潮生。
- 艳艳随波千万里,何处春江无月明。
- 江流宛转绕芳甸,月照花林皆似霰。
- 空里留霜不觉飞,汀上白沙看不见。
- 江天一色无纤尘,皎皎空中孤月轮。
- 江畔何人初见月,江月何年初照人。
- 人生代代无穷已,江月年年望相似。
- """
- layout = [[sg.ML(default_text=text,
- key='-TEXT-',
- disabled=False,
- border_width=None,
- size=(50,6),
- background_color='white',
- text_color='black',
- font=('楷体',20),
- enable_events=True,
- write_only=False,#当True时,只提供写入,窗口不读取,无返回值
- reroute_stdout=True,#print语句会显示在此文本框内
- reroute_cprint=True,#使用cprint将内容打印到此文本框内
- reroute_stderr=False,#捕捉异常时将文本写在此元素内,sys.stderr.write('?')
- autoscroll=False,#如果为True,更多数据添加到末尾时元素的内容将自动滚动
- focus=False,
- tooltip='作者:张若虚',
- justification='center',
- right_click_menu=['菜单',['复制','粘贴','剪切','全选']],
- visible=True,
- do_not_clear=True#False窗口读取一次,内容清除
- )],
- [sg.In(key='-INPUT1-'),
- #垂直分割线
- sg.VerticalSeparator(color='red',
- key='-VERTICAL-',
- pad=((10,10),(10,10))),#间隔((左,右),(上,下))
- sg.B('CPrint',key='-OUTPUT1-')],
- [sg.In(key='-INPUT2-'),
- sg.VerticalSeparator(color='red'),
- sg.B('Print',key='-OUTPUT2-')],
- [sg.B('更新',key='-UPDATE-')]]
- window = sg.Window('Window Title', layout)
- while True:
- event, values = window.read()
- if event ==None:
- break
- if event == '-OUTPUT1-':
- sg.cprint(values['-INPUT1-'],
- end=None,
- sep='',#分割符
- text_color='black',
- background_color='Light green',
- justification='right'
- )
- window['-INPUT1-'].update('')
- if event == '-OUTPUT2-':
- window['-TEXT-'].print(values['-INPUT2-'],
- end=None,
- sep='--', # 分割符
- text_color='black',
- background_color='Light blue',
- justification='left'
- )
- window['-INPUT2-'].update('')
- if event == '-UPDATE-':
- window['-TEXT-'].update(value='你好!',
- disabled=None,
- append=True,
- font=None,
- text_color=None,
- background_color=None,
- justification='left',
- visible=True,
- autoscroll=True
- )
- window.close()
复制代码 7.13 弹窗
- import PySimpleGUI as sg
- a=sg.popup('弹窗\n'*5,
- title='演示',
- button_color=('red', 'green'),
- background_color='black',
- auto_close=True,#自动关闭弹窗
- auto_close_duration=3,#自动关闭弹窗持续时间
- custom_text=('yes','no'),#自定义按钮文本
- non_blocking=False,#非阻塞设定,如果为True,立即执行下一步,不需要等待用户的输入,
- font=('Arial'),
- no_titlebar=False,#不显示标题栏
- grab_anywhere=True,
- # location=(600,700),
- any_key_closes=True,#True敲打任意键就会关闭界面
- image=r'C:\Users\风车小牛马\Pictures\icons\1.png',
- modal=True
- )
- print(a)
复制代码 7.14 弹窗之PopupGetText
- import PySimpleGUI as sg
- pwd = '123'
- list = ['资料1','资料2','资料3','资料4']
- while True:
- result = sg.PopupGetText('密码输入框')
- if pwd ==result :
- break
- elif result ==None:
- exit()
- else:sg.popup('密码错误')
- layoutb=[[sg.LB(list,size=(30,5))]]
- layout=[[sg.Frame('资料库',layoutb)]]
- window=sg.Window('演示',layout)
- while True:
- event, values = window.read()
- if event == None:
- break
- window.close()
- """
- sg.PopupGetFile()#文件选择弹窗
- sg.PopupGetFolder()#文件夹选择
- sg.PopupAnnoying()#没有标题栏可随意移动
- sg.PopupAutoClose()#显示一段时间自动关闭
- sg.PopupCancel()
- sg.PopupOKCancel()
- sg.PopupOK()
- sg.PopupError()
- sg.PopupNoButtons()
- """
复制代码 7.15 按键元素设定
- import PySimpleGUI as sg
- image_file =r'..//image/1.png'
- layout = [[sg.Text('用户名',size=8,background_color='white',text_color='black'),sg.Input(key='-user-')],
- [sg.Text('密码',size=8,background_color='white',text_color='black'),sg.Input(key='-pwd-')],
- [sg.Column([[sg.Button(image_filename=image_file,
- key='-python-',
- image_size=(32,32),
- button_color='white',
- bind_return_key=True,
- auto_size_button=True)]],justification='center')]
- ]#按钮居中对齐
- window = sg.Window('Python练习',layout,keep_on_top=True,background_color='white')
- while True:
- event, values =window.read()
- print(event)
- if event ==None:
- break
- if event =='-python-':
- print(event)
- window.close()
复制代码 7.16 文件选择器和另存为
- import PySimpleGUI as sg
- layout = [[sg.FilesBrowse(button_text="选择文件",
- target='-IN1-',#目标元素
- file_types=(('ALL Files','*.*'),),#选择文件类型
- initial_folder=r'C:\Users\风车小牛马\Pictures\icons'),#默认跳转路径
- sg.In(key='-IN1-')],
- [sg.FolderBrowse(button_text="选择文件夹",target='-IN2-'),sg.In(key='-IN2-')],
- [sg.SaveAs(button_text="另存为",target='-IN3-'),sg.In(key='-IN3-')]]
- window = sg.Window('文件选择器',layout)
- while True:
- event, values = window.read()
- if event ==None:
- break
- window.close()
复制代码 7.17 文本元素
- import PySimpleGUI as sg
- text = '''
- 《逢雪宿芙蓉山主人》
- ——唐代·刘长卿
- 日暮苍山远,
- 天寒白屋贫。
- 柴门闻犬吠,
- 风雪夜归人。
- '''
- layout = [[sg.T(text,
- key='-text-',#元素唯一标识符,用于元素定位
- size=(None,None),#元素宽高(int,int)
- font=('楷体',20),#字体
- auto_size_text=True,#当值设为True时,窗口自动适应文本大小
- enable_events=True,#bool:事件属性,设定为True时,点击文本发生事件
- relief='ridge',#浮雕设计‘raised’,'sunken','flat','ridge','solid','groove'
- border_width=30,#设定relief时,用来设定边界宽度
- text_color='blue',#文本颜色
- background_color='white',#背景颜色
- justification='center',#对齐方式
- pad=None,#元素间隔
- right_click_menu=['&Edit',['&Copy','&Paste','&Undo','&More',['&Setting','&About']]],#右键调出菜单
- grab=False,#设为True时点击移动
- tooltip='这是一个标识文本',
- visible=True#显示窗口
- )]]
- window = sg.Window('文本元素',layout)
- while True:
- event, values = window.read()
- if event ==None:
- break
- if event == '-text-':
- sg.Popup('运行了一个点击事件')
- window.close()
复制代码 7.18 文本元素更新
- import PySimpleGUI as sg
- layout = [[sg.Text('Hypocrite',key='-Text-'),sg.Button('点赞')]]
- window = sg.Window('Python',layout)
- while True:
- event, values =window.read()
- print(event)
- if event == None:
- break
- if event == '点赞':
- window['-Text-'].update(
- value='Hello World!',
- background_color='white',
- text_color='black',
- font=('楷体',20),
- visible=True
- )
- window.close()
复制代码 7.19 标签
- import PySimpleGUI as sg
- lista=['苹果','香蕉','橘子','橙子']
- listb=['白菜','芥菜','包菜','生菜']
- tab1_layout=[[sg.LB(lista,size=(20,10))]]
- tab2_layout=[[sg.LB(listb,size=(20,10))]]
- layout=[[sg.TabGroup([[sg.Tab('水果类',tab1_layout,title_color='red'),
- sg.Tab('蔬菜类',tab2_layout)]],
- tab_location='lefttop',
- title_color='black',#未选中
- tab_background_color='gray',
- selected_title_color='blue',#选中
- background_color='gray',#标签标题所在空白区域的背景颜色
- selected_background_color='white',#选中
- font=('楷体',12),
- enable_events=False,
- border_width=10
- )]]
- window=sg.Window('标签演示',layout,keep_on_top=True,background_color='gray')
- while True:
- event, values = window.read()
- if event == None:
- break
- window.close()
复制代码 7.20 框架元素
- import PySimpleGUI as sg
- list = ['资料1','资料2','资料3','资料4']
- layouta=[[sg.Text('账号'),sg.Input()],
- [sg.Text('账号'),sg.Input()],
- [sg.Col([[sg.B('登录')]],justification='center')]]
- layoutb=[[sg.LB(list,size=(30,5))]]
- layout=[[sg.Frame('登录项',layouta,
- title_color='green',
- background_color=None,
- title_location='n',#12种[东南西北]
- relief="groove",
- key='-a-',
- visible=True
- ),sg.Frame('资料库',layoutb,visible=False,key='-b-')]
- ]
- window=sg.Window('框架',layout)
- while True:
- event, values = window.read()
- if event == None:
- break
- if event =='登录':
- window['-a-'].update(visible=False)
- window['-b-'].update(visible=True)
- window.close()
复制代码 7.21 滑块
- import PySimpleGUI as sg
- flag=0
- layout = [[sg.T('酸性',size=(33,None),justification='left',text_color='red'),
- sg.T('中性',size=(69,None),justification='center',text_color='white'),
- sg.T('碱性',size=(33,None),justification='right',text_color='blue')],
- [sg.Slider(
- range=(0,14),#数值范围
- key='-SD-',#键值
- default_value=7,#起始默认值
- resolution=0.1,#每次移动间隔
- tick_interval=True,#标识
- orientation='horizontal',#方向
- disable_number_display=False,#是否显示滑块旁数值
- border_width=5,#
- relief='raised',#样式
- size=(100,20),#大小
- font=('Arial',12,'bold'),#字体
- background_color='Light blue',#背景颜色
- text_color='red',#文本颜色
- tooltip=None,#悬浮文本
- visible=True#可见状态
- )],
- [sg.Column([[sg.B('上调',size=(10,2)),sg.B('下调',size=(10,2))]], justification='center')],
- [sg.Column([[sg.B('确认'),sg.B('重置')]],justification='center')],
- [sg.T('',key='-TEXT-',justification='center',size=110,font=('楷书'))]
- ]
- window = sg.Window('演示',layout)
- while True:
- event, values = window.read()
- if event == None:
- break
- if event == '确认':
- if values['-SD-'] > 7.0:
- print('PH:',values['-SD-'],'碱性')
- window['-TEXT-'].update('ph:'+str(values['-SD-'])+' 碱性')
- if values['-SD-'] < 7.0:
- print('PH:',values['-SD-'],'酸性')
- window['-TEXT-'].update('ph:' + str(values['-SD-']) + ' 酸性')
- elif values['-SD-'] == 7.0:
- print('PH:',values['-SD-'],'中性')
- window['-TEXT-'].update('ph:' + str(values['-SD-']) + ' 中性')
- if event == '重置':
- window['-SD-'].update(value=7.0)
- if event =='上调':
- flag=values['-SD-']
- flag=flag+0.1
- window['-SD-'].update(value=flag
- )
- if event =='下调':
- flag=values['-SD-']
- flag=flag-0.1
- window['-SD-'].update(value=flag
- )
- window.close()
复制代码 7.22 红绿灯
- import threading
- import time
- import PySimpleGUI as sg
- def update_button(window, key, color):
- window[key].update(button_color=('black', color))
- def traffic_light_controller(window):
- while True:
- update_button(window, '-G-', 'green')
- update_button(window, '-Y-', 'gray')
- update_button(window, '-R-', 'gray')
- for seconds in range(30, 0, -1):
- window['-TIMER-'].update(seconds)
- time.sleep(1)
- update_button(window, '-G-', 'gray')
- update_button(window, '-Y-', 'yellow')
- update_button(window, '-R-', 'gray')
- window['-TIMER-'].update('')
- time.sleep(5)
- update_button(window, '-G-', 'gray')
- update_button(window, '-Y-', 'gray')
- update_button(window, '-R-', 'red')
- for seconds in range(30, 0, -1):
- window['-TIMER-'].update(seconds)
- time.sleep(1)
- layout = [
- [sg.Text('计时器:', size=(15, 1)), sg.Text('', size=(5, 1), key='-TIMER-')],
- [sg.B(button_text='绿灯', button_color=('black', 'gray'), size=(20, 10), key='-G-')],
- [sg.B(button_text='黄灯', button_color=('black', 'gray'), size=(20, 10), key='-Y-')],
- [sg.B(button_text='红灯', button_color=('black', 'gray'), size=(20, 10), key='-R-')]
- ]
- window = sg.Window('交通信号灯', layout, finalize=True)
- # 创建并启动线程
- controller_thread = threading.Thread(target=traffic_light_controller, args=(window,), daemon=True)
- controller_thread.start()
- while True:
- event, values = window.read(timeout=1000) # Timeout in milliseconds, 1000ms = 1 second
- if event == sg.WINDOW_CLOSED:
- break
- # 关闭窗口
- window.close()
复制代码 7.23 菜单
- import PySimpleGUI as sg
- def Gui():
- menu_def = [['File(&F)', ['New', 'Open', '!Save', 'Exit', ]],
- ['Edit', ['Cut', 'Copy::CP', 'Paste', 'Undo'], ],
- ['Help', 'About...'], ]
- right_menu = [['&File', ['&New', '']]]
- layout = [[sg.Menu(menu_def)],
- [sg.Multiline("", key='-IN-',
- expand_x=True, expand_y=True)],
- [sg.Multiline("", key='-OUT-',
- expand_x=True, expand_y=True)],
- [sg.Text("", key='-TXT-',
- expand_x=True, font=("Arial Bold", 14))],
- ]
- window = sg.Window("Menu", layout, size=(715, 300))
- while True:
- event, values = window.read()
- print(event, values)
- if event != sg.WIN_CLOSED:
- window['-TXT-'].update(values[0] + "Menu Button Clicked")
- if event == 'Copy::CP':
- txt = window['-IN-'].get()
- if event == 'Paste':
- window['-OUT-'].update(value=txt)
- if event == sg.WIN_CLOSED:
- break
- window.close()
- Gui()
复制代码 7.24 表格
- import PySimpleGUI as sg
- a=['编号','商品','价格','','','','']
- b=[['001','牛奶','5'],['002','苹果','6'],['003','香烟','10']]
- layout=[[sg.Table(b,#表格内容
- headings=a,#表格头部
- max_col_width=500,#所有列最大宽度
- auto_size_columns=False,#是否自动适应列宽度
- def_col_width=10,#定义列表宽度
- display_row_numbers=True,#是否显示序号列
- justification='c',#对齐方式
- num_rows=15,#定义行数
- row_height=30,
- key='-a-',
- font=('黑体',10),
- text_color='black',
- background_color='Light blue',
- enable_events=True,
- bind_return_key=True
- )]]
- window=sg.Window('表格',layout)
- while True:
- event, values = window.read()
- if event ==None:
- break
- window.close()
复制代码 7.25 计算器
- import PySimpleGUI as sg
- def button(text):
- return sg.B(text,size=(5,3),font=('黑体',18),button_color='black')
- layout = [[sg.ML(size=(15,2), key='-IN-',font=('黑体',28))],
- [sg.T('结果',font=('黑体',12)),sg.In(key='-OUT-',size=(13,1),font=('黑体',28))],
- [button(i) for i in ['AC','(',')','%']],
- [button(i) for i in '123+'],
- [button(i) for i in '456-'],
- [button(i) for i in '789×'],
- [button(i) for i in '0.=÷'],
- ]
- window = sg.Window('计算器',layout)
- x=None
- y=None
- while True:
- event, values = window.read()
- if event ==None:
- break
- if event in list('1234567890+-().'):
- window['-IN-'].update(values['-IN-']+event)
- if event == '%':
- try:
- a=eval(values['-IN-']+'*0.01')
- window['-IN-'].update(values['-IN-'] + '*0.01')
- except:
- window['-IN-'].update('')
- sg.popup('输入有误')
- if event == '×':
- window['-IN-'].update(values['-IN-'] + '*')
- if event == '÷':
- window['-IN-'].update(values['-IN-'] + '/')
- if event == 'AC':
- window['-IN-'].update('')
- window['-OUT-'].update('')
- if event == '=':
- try:
- window['-OUT-'].update(eval(values['-IN-']))
- except Exception as e:
- sg.popup('请输入合法的表达式')
- print('错误报告:',e)
- window.close()
复制代码 7.26 设定模板主题
- import PySimpleGUI as sg
- print(sg.theme_list())
- sg.theme('DarkRed')
- sg.Popup('弹窗演示')
- # print(sg.theme_button_color())
- sg.theme_button_color(('black', '#ad1d45'))
- sg.Popup('演示弹窗','按键字体变黑色')
复制代码 7.27 调用字典
- import PySimpleGUI as sg
- dict ={'河南':'郑州','河北':'石家庄','浙江':'杭州','湖北':'武汉'}
- list = []
- for i in dict:
- list.append(i)
- layout = [[sg.LB(list,key='-DICT-',size=(40,3),enable_events=True)],
- [sg.T('行政中心'),sg.Input(key='-INPUT-',size=(30))]]
- window = sg.Window('演示',layout)
- while True:
- event, values =window.read()
- if event == None:
- break
- if event == '-DICT-':
- window['-INPUT-'].update(dict[values['-DICT-'][0]])
- window.close()
复制代码 7.28 选择菜单和旋转按钮
- import PySimpleGUI as sg
- list = ['Python', 'Java', 'C++', 'JavaScript', 'php']
- layout = [[sg.Text('OptionMenu'),sg.OptionMenu(list,key='-OM-'),
- sg.Text('Spin'),sg.Spin(list,size=(10,1),key='-SP-',enable_events=True)],
- [sg.Text('语言'),sg.In(key='-IN-',size=(25))]]
- window = sg.Window('演示界面',layout)
- while True:
- event, values =window.read()
- if event ==None:
- break
- if event == '-OM-' or event =='-SP-':
- window['-IN-'].update(values['-SP-'])
- window.close()
复制代码 7.29颜色选择器和日历选择
- import PySimpleGUI as sg
- month =['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月']
- week = ['周日','周一','周二','周三','周四','周五','周六']
- layout = [[sg.ColorChooserButton(button_text='颜色选择器'),sg.In()],
- [sg.CalendarButton(button_text='日历选择器',
- close_when_date_chosen=False,
- # default_date_m_d_y=None,
- # locale='',
- format='%Y年%m月%d日',
- begin_at_sunday_plus=1,
- month_names=month,
- day_abbreviations=week,
- title='日历',
- no_titlebar=False,
- location=(700,500),
- ),sg.In()]]
- window = sg.Window('',layout)
- while True:
- event, values = window.read()
- if event == None:
- break
- window.close()
复制代码 7.30 PDF合并工具
- import PySimpleGUI as sg
- import os
- from PyPDF2 import PdfFileReader, PdfFileWriter, PdfWriter, PdfReader
- def FileNameGet(filedir):
- files_list = [os.path.join(root,filepath) \
- for root, dirs, files in os.walk(filedir) \
- for filepath in files\
- if str(filepath).endswith('pdf')]
- return files_list if files_list else[]
- def PDFMerge(filepath,output_file):
- output = PdfWriter()
- output_pages = 0
- pdf_file_name = FileNameGet(filepath)
- if pdf_file_name:
- for pdf_file in pdf_file_name:
- sg.cprint("路径:%s" % pdf_file)
- #读取源PDF文件
- input=PdfReader(open(pdf_file,"rb"))
- #获得源PDF文件中页面页数
- page_count = len(input.pages)
- output_pages += page_count
- sg.cprint("页数:%d" % page_count)
- #分别将page添加到输出output中
- for iPage in range(page_count):
- output.add_page(input.pages[iPage])
- sg.cprint("合并后的总页数:%d." % output_pages)
- output_stream = open(os.path.join(filepath,output_file),"wb")
- try:
- output.write(output_stream)
- output_stream.close()
- except Exception as e:
- sg.cprint("合并失败,请重试")
- sg.cprint("PDF文件合并完成!")
- sg.cprint(f"合并后的文件路径:{filepath}/{output_file}",)
- else:
- sg.cprint("没有可以合并的PDF文件")
- #GUI
- def main():
- layout = [[sg.Text('选择文件夹:',size=(15,1)),sg.In(size=(40,1),key='-file_dir-'),sg.FolderBrowse()],
- [sg.Text('输入合并后的文件名:',size=(15,1)),sg.In(size=(40,1),key='-out_file-'),sg.B('开始合并')],
- [sg.ML(size=(70,15),reroute_cprint=True)]
- ]
- window = sg.Window('PDF合并工具',layout)
- while True:
- event, values = window.read()
- file_dir = values['-file_dir-']
- out_file = values['-out_file-']
- if event ==None:
- break
- if event == '开始合并':
- PDFMerge(file_dir,out_file)
- window.close()
- main()
复制代码 8 资源链接
PySimpleGUI 官方文档
PySimpleGUI GitHub
作者:TheHypocrite
来源:https://www.cnblogs.com/TheHypocrite/p/18292993
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作! |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
x
|