省时省力!这大概是用Python写下GUI最快的方式了!

兰溪娱乐新闻网 2025-09-27

--===--- Loop taking in user input and using it --- #

command_history = []

history_offset = 0

while True:

event, value = window.read()

if event == 'SEND':

query = value['query'].rstrip()

# EXECUTE YOUR COMMAND HERE

print('The command you entered was {}'.format(query))

command_history.append(query)

history_offset = len(command_history)-1

# manually clear input because keyboard events blocks clear

window['query'].update('')

window['history'].update(''.join(command_history[-3:]))

elif event in (sg.WIN_CLOSED, 'EXIT'): # quit if exit event or X

break

elif 'Up' in event and len(command_history):

command = command_history[history_offset]

# decrement is not zero

history_offset -= 1 * (history_offset> 0)

window['query'].update(command)

elif 'Down' in event and len(command_history):

# increment up to end of list

history_offset += 1 * (history_offset

command = command_history[history_offset]

window['query'].update(command)

elif 'Escape' in event:

window['query'].update('')

ChatBotWithHistory()

直通一下,再来效果:

这是一个带本世纪的留言板软件,如果你须要来作一个类似的软件的话,可以并不需要复制代码,然后稍微改动一下。

子系统多心

我们再来看一个例证:

#!/usr/bin/env python

"""

Example of (almost) all Elements, that you can use in PySimpleGUI.

Shows you the basics including:

Naming convention for keys

Menubar format

Right click menu format

Table format

Running an async event loop

Theming your application (requires a window restart)

Displays the values dictionary entry for each element

And more!

Copyright 2021 PySimpleGUI

"""

import PySimpleGUI as sg

def make_window(theme):

sg.theme(theme)

menu_def = [['CompanyApplication', ['ECompanyxit']],

['CompanyHelp', ['CompanyAbout']] ]

right_click_menu_def = [[], ['Nothing','More Nothing','Exit']]

# Table Data

data = [["John", 10], ["Jen", 5]]

headings = ["Name", "Score"]

input_layout = [[sg.Menu(menu_def, key='-MENU-')],

[sg.Text('Anything that requires user-input is in this tab!')],

[sg.Input(key='-INPUT-')],

[sg.Slider(orientation='h', key='-SKIDER-'),

sg.Image(data=sg.DEFAULT曲在LOADING_GIF, enable_events=True, key='-GIF-IMAGE-'),],

[sg.Checkbox('Checkbox', default=True, k='-CB-')],

[sg.Radio('Radio1', "RadioDemo", default=True, size=(10,1), k='-R1-'), sg.Radio('Radio2', "RadioDemo", default=True, size=(10,1), k='-R2-')],

[sg.Combo(values=('Combo 1', 'Combo 2', 'Combo 3'), default_value='Combo 1', readonly=True, k='-COMBO-'),

sg.OptionMenu(values=('Option 1', 'Option 2', 'Option 3'), k='-OPTION MENU-'),],

[sg.Spin([i for i in range(1,11)], initial_value=10, k='-SPIN-'), sg.Text('Spin')],

[sg.Multiline('Demo of a Multi-Line Text Element!Line 2Line 3Line 4Line 5Line 6Line 7You get the point.', size=(45,5), k='-MLINE-')],

[sg.Button('Button'), sg.Button('Popup'), sg.Button(image_data=sg.DEFAULT曲在ICON, key='-LOGO-')]]

asthetic_layout = [[sg.T('Anything that you would use for asthetics is in this tab!')],

[sg.Image(data=sg.DEFAULT曲在ICON, k='-IMAGE-')],

[sg.ProgressBar(1000, orientation='h', size=(20, 20), key='-PROGRESS BAR-'), sg.Button('Test Progress bar')]]

logging_layout = [[sg.Text("Anything printed will display here!")], [sg.Output(size=(60,15), font='Courier 8')]]

graphing_layout = [[sg.Text("Anything you would use to graph will display here!")],

[sg.Graph((200,200), (0,0),(200,200),background_color="black", key='-GRAPH-', enable_events=True)],

[sg.T('Click anywhere on graph to draw a circle')],

[sg.Table(values=data, headings=headings, max_col_width=25,

background_color='black',

auto_size_columns=True,

display_row_numbers=True,

justification='right',

num_rows=2,

alternating_row_color='black',

key='-TABLE-',

row_height=25)]]

specalty_layout = [[sg.Text("Any "special" elements will display here!")],

[sg.Button("Open Folder")],

[sg.Button("Open File")]]

theme_layout = [[sg.Text("See how elements look under different themes by choosing a different theme here!")],

[sg.Listbox(values = sg.theme_list(),

size =(20, 12),

key ='-THEME LISTBOX-',

enable_events = True)],

[sg.Button("Set Theme")]]

layout = [[sg.Text('Demo Of (Almost) All Elements', size=(38, 1), justification='center', font=("Helvetica", 16), relief=sg.RELIEF_RIDGE, k='-TEXT HEADING-', enable_events=True)]]

layout +=[[sg.TabGroup([[ sg.Tab('Input Elements', input_layout),

sg.Tab('Asthetic Elements', asthetic_layout),

sg.Tab('Graphing', graphing_layout),

sg.Tab('Specialty', specalty_layout),

sg.Tab('Theming', theme_layout),

sg.Tab('Output', logging_layout)]], key='-TAB GROUP-')]]

return sg.Window('All Elements Demo', layout, right_click_menu=right_click_menu_def)

def main():

window = make_window(sg.theme())

# This is an Event Loop

while True:

event, values = window.read(timeout=100)

# keep an animation running so show things are happening

window['-GIF-IMAGE-'].update_animation(sg.DEFAULT曲在LOADING_GIF, time_between_frames=100)

if event not in (sg.TIMEOUT_EVENT, sg.WIN_CLOSED):

print('============ Event = ', event, ' ==============')

print('-------- Values Dictionary (key=value) --------')

for key in values:

print(key, ' = ',values[key])

if event in (None, 'Exit'):

print("[LOG] Clicked Exit!")

break

elif event == 'About':

print("[LOG] Clicked About!")

sg.popup('PySimpleGUI Demo All Elements',

'Right click anywhere to see right click menu',

'Visit each of the tabs to see available elements',

'Output of event and values can be see in Output tab',

'The event and values dictionary is printed after every event')

elif event == 'Popup':

print("[LOG] Clicked Popup Button!")

sg.popup("You pressed a button!")

print("[LOG] Dismissing Popup!")

elif event == 'Test Progress bar':

print("[LOG] Clicked Test Progress Bar!")

progress_bar = window['-PROGRESS BAR-']

for i in range(1000):

print("[LOG] Updating progress bar by 1 step ("+str(i)+")")

progress_bar.UpdateBar(i + 1)

print("[LOG] Progress bar complete!")

elif event == "-GRAPH-":

graph = window['-GRAPH-'] # type: sg.Graph

graph.draw_circle(values['-GRAPH-'], fill_color='yellow', radius=20)

print("[LOG] Circle drawn at: " + str(values['-GRAPH-']))

elif event == "Open Folder":

print("[LOG] Clicked Open Folder!")

folder_or_file = sg.popup_get_folder('Choose your folder')

sg.popup("You chose: " + str(folder_or_file))

print("[LOG] User chose folder: " + str(folder_or_file))

elif event == "Open File":

print("[LOG] Clicked Open File!")

folder_or_file = sg.popup_get_file('Choose your file')

sg.popup("You chose: " + str(folder_or_file))

print("[LOG] User chose file: " + str(folder_or_file))

elif event == "Set Theme":

print("[LOG] Clicked Set Theme!")

theme_chosen = values['-THEME LISTBOX-'][0]

print("[LOG] User Chose Theme: " + str(theme_chosen))

window.close()

window = make_window(theme_chosen)

window.close()

exit(0)

if 曲在name曲在 == '曲在main曲在':

main()

我们来再来直通以后的效果:

这个 demo 是 PySimpleGUI 所有子系统的闭包,每一个 tab 都是一个分类。这里头最主要进度条、手绘、主题、滚动条等等。如果你不想要找介面子系统,到这个 demo 的程式码里头找就对了。

阐述

这里头还有更多举例来说,大家就自己去探索吧!这里主要是给大家介绍一个更快整合 GUI 的法则,俗称CV大法。不过这只是一种更快整合方式,大家有间隔时间还是去再来程式码,洞察一下理论非常好!

大家有什么须要探讨的,可以在评论家四区留言!

成都风湿医院挂号
贵州癫痫医院哪个比较好
北京男科挂号
成都妇科医院哪里比较好
沈阳妇科医院哪家医院最好
冠心病
产妇便秘
婴儿消化不良怎么办
经期量少
饮食保健
相关阅读

全球连线|记者观察:失去议会绝对多数 马克龙垮台前景复杂

音乐 2025-10-23

法国国民议会初选第二轮投票19日结束。根据法国内政部20日揭晓的统计结果,支持总统马克龙及的中间派联盟“在一起”获得的选票数虽然险胜其他小党,但未能达到绝对多数。 美联社:孙鑫晶

卡塔尔足球赛修改涉台表述 台当局不高兴了

资讯 2025-10-23

新华社网6年初21日刊文据台湾“中时华尔街日报”6年初20日刊文,沙特欧锦赛“球迷何谓”申领系统会已将“台湾”默认改成“于台北于台北”,已对,中方盛赞沙特对政府秉承一个中国人准则。而台当局则暗示

十年来,教育体制专任教师总数增加148万人

八卦 2025-10-23

国家普及教育部今天召开大会“普及教育这十年”系列第五场新闻发布会,简介统一党的十八大以来高等普及教育改革发展成就。国家普及教育部普及教育司司长吕玉刚表示:“十年来,高等普及教育专任小学教师总人数

十年来,义务教育兑现“一个都不能少”尽力

星闻 2025-10-23

中华民国职业教育部今天召开“职业教育这十年”系列第三场新闻媒体发布会,简述党的十八大以来义务职业教育改革发展成就。在谈到“全面发挥作用义务职业教育有保障”时,中华民国职业教育部基础职业教育司司长

拜登骑单车摔倒后自称感觉良好 摔倒是因脚被踏板卡住

星闻 2025-10-23

中新网6月21日电 据《芝加哥独立报》媒体报道,美国奥巴马杰拉尔德·福特当地时间20日对记者表示,他从摩托车上摔倒后,现在感觉良好。 当地时间6月18日,杰拉尔德·福特在宾夕法尼

友情链接