EasyGUI库
随着Python在数据科学、机器学习和Web开发等多个领域的广泛应用,图形用户界面(GUI)开发也变得越来越重要。对于初学者和快速原型设计来说,使用复杂的GUI库可能会让人感到望而生畏。幸运的是,Python的EasyGUI库提供了一个简单而直观的方式来创建基本的图形用户界面,无需深入了解复杂的GUI编程概念。
EasyGUI是一个用于非常简单的Python GUI编程的库。与Tkinter等更高级的库相比,EasyGUI通过提供一系列预构建的对话框和简单的函数调用来简化GUI开发过程。这使得开发者可以专注于应用程序的逻辑,而不是花费大量时间在界面设计上。
主要特点
- 简单易用:EasyGUI提供了直观的API,通常只需要一行代码就可以调用各种对话框,如消息框、选择框、文件选择框等。
- 跨平台兼容性:EasyGUI可以在Windows、macOS和Linux等多个操作系统上运行,确保您的应用程序具有广泛的可达性。
- 自定义选项:尽管EasyGUI强调的是简单性,但它仍然提供了一定程度的自定义能力,如更改对话框的标题、添加自定义按钮等。
- 集成Python标准库:EasyGUI基于Python的标准Tkinter库构建,这意味着您可以在需要时轻松集成更复杂的Tkinter功能。
使用场景
- 快速原型设计:当您需要快速测试一个想法或展示一个概念验证时,EasyGUI可以帮助您快速构建一个简单的界面。
- 小型项目和教育目的:对于不需要复杂界面的小型项目,或者在教学环境中向学生介绍GUI编程的概念,EasyGUI是一个理想的选择。
- 脚本和工具:对于需要简单用户输入的脚本或工具,使用EasyGUI可以提供一个比命令行更友好的交互方式。
安装
C:\> pip install easygui
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting easygui
Using cached https://pypi.tuna.tsinghua.edu.cn/packages/8e/a7/b276ff776533b423710a285c8168b52551cb2ab0855443131fdc7fd8c16f/easygui-0.98.3-py2.py3-none-any.whl (92 kB)
Installing collected packages: easygui
Successfully installed easygui-0.98.3
导入
>>> import easygui
>>> easygui.__all__
['buttonbox', 'diropenbox', 'fileopenbox', 'filesavebox', 'textbox', 'ynbox', 'ccbox', 'boolbox', 'indexbox', 'msgbox', 'integerbox', 'multenterbox', 'enterbox', 'exceptionbox', 'choicebox', 'codebox', 'passwordbox', 'multpasswordbox', 'multchoicebox', 'EgStore', 'eg_version', 'egversion', 'abouteasygui', 'egdemo']
由以上列表,可以看到easygui共包含了19种对话框样式。
对话框样式
1. 消息框 msgbox
msgbox(msg='(Your message goes here)', title=' ', ok_button='OK', image=None, root=None)
The ``msgbox()`` function displays a text message and offers an OK button. The message text appears in the center of the window, the title text appears in the title bar, and you can replace the "OK" default text on the button.
:param str msg: the msg to be displayed
:param str title: the window title
:param str ok_button: text to show in the button
:param str image: Filename of image to display
:param tk_widget root: Top-level Tk widget
:return: the text of the ok_button
显示文本消息并提供“确定”按钮。消息文本显示在窗口的中心,标题文本显示在标题栏中,可以替换按钮上的“确定”默认文本,例如:
easygui.msgbox("备份完成!", title="结束", ok_button="干得好!")
2. 确认框 ccbox
ccbox(msg='Shall I continue?', title=' ', choices=('C[o]ntinue', 'C[a]ncel'), image=None, default_choice='Continue', cancel_choice='Cancel')
The ``ccbox()`` function offers a choice of Continue and Cancel, and returns either True (for continue) or False (for cancel).
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted when the gui appears
:param str cancel_choice: If the user presses the 'X' close, which button should be pressed
:return: True if 'Continue' or dialog is cancelled, False if 'Cancel'
提供了“继续”和“取消”选项,并返回True(表示继续)或False(表示取消)。默认的按钮文本为:'Continue' 和 'Cancel',也可以使用按钮文本自定义,例如:
easygui.ccbox(msg, title, choices=('退出[E]','取消[C]'))
3. 布尔框 boolbox
boolbox(msg='Shall I continue?', title=' ', choices=('[T]rue', '[F]alse'), image=None, default_choice='[T]rue', cancel_choice='[F]alse')
The ``boolbox()`` (boolean box) displays two buttons. Returns returns ``True`` if the first button is chosen. Otherwise returns ``False``.
:param str msg: The message shown in the center of the dialog window.
:param str title: The window title text.
:param list choices: A list or tuple of strings for the buttons' text.
:param str image: The filename of an image to display in the dialog window.
:param str default_choice: The text of the default selected button.
:param str cancel_choice: If the user presses the 'X' close, which button should be pressed
:return: `True` if first button pressed or dialog is cancelled, `False` if second button is pressed.
如果选择了第一个按钮,则返回“True”。否则返回“False”。
与msgbox的联用,代码如下:
importeasyguimessage="What do they say?"title="Romantic Question"ifeasygui.boolbox(message, title, ["They love me", "They love me not"]): easygui.msgbox('You should send them flowers.') else: easygui.msgbox('It was not meant to be.')
4. 是否框 ynbox
ynbox(msg='Shall I continue?', title=' ', choices=('[<F1>]Yes', '[<F2>]No'), image=None, default_choice='[<F1>]Yes', cancel_choice='[<F2>]No')
:param msg: the msg to be displayed
:type msg: str
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted when the gui appears
:param str cancel_choice: If the user presses the 'X' close, which button should be pressed
:return: True if 'Yes' or dialog is cancelled, False if 'No'
提供了Yes和No的选择,并返回“True”或“False”。
importeasyguiresult=easygui.ynbox('Is a hot dog a sandwich?', 'Hot Dog Question') ifresult==True: easygui.msgbox('That is an interesting answer.') else: easygui.msgbox('Well, that is your opinion.')
5. 选择框 choicebox
choicebox(msg='Pick an item', title='', choices=None, preselect=0, callback=None, run=True)
The ``choicebox()`` provides a list of choices in a list box to choose from. The choices are specified in a sequence (a tuple or a list).
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param preselect: Which item, if any are preselected when dialog appears
:return: A string of the selected choice or None if cancelled
在列表框中提供了可供选择的由元组或列表指定的选项列表。
importeasyguimsg="What is your favorite flavor?"title="Ice Cream Survey"choices= ["Vanilla", "Chocolate", "Strawberry", "Coffee Latte"] choice=easygui.choicebox(msg, title, choices) # choice is a stringprint(choice)
注:选择“Chocolate”后点OK就把所选择的项赋值给变量choice,点Cancel则返回None。
6. 整数输入框 integerbox
integerbox(msg='', title=' ', default=None, lowerbound=0, upperbound=99, image=None, root=None)
Show a box in which a user can enter an integer.
In addition to arguments for msg and title, this function accepts integer arguments for "default", "lowerbound", and "upperbound".
The default, lowerbound, or upperbound may be None.
When the user enters some text, the text is checked to verify that it can be converted to an integer between the lowerbound and upperbound.
If it can be, the integer (not the text) is returned.
If it cannot, then an error msg is displayed, and the integerbox is redisplayed.
If the user cancels the operation, None is returned.
:param str msg: the msg to be displayed
:param str title: the window title
:param int default: The default value to return
:param int lowerbound: The lower-most value allowed
:param int upperbound: The upper-most value allowed
:param str image: Filename of image to display
:param tk_widget root: Top-level Tk widget
:return: the integer value entered by the user
显示一个框,用户可以在其中输入整数。除了msg和title的参数外,此函数还接受“default”、“lowerbound”和“upperfound”的整数参数。默认值、下限值或上限值可能为“None”。
当用户输入一些文本时,会检查文本以验证它是否可以转换为介于下限和上限之间的整数。
如果可以,则返回整数(而不是文本)。
如果不能,则会显示一条错误消息,并重新显示integebox。
如果用户取消操作,则返回None。
importeasyguiresult=easygui.integerbox('请输入一个整数:') print(result)
注:输入整数超出上下限或输入的不是一个整数,返回一个msgbox:
7. 按钮选择框 buttonbox
buttonbox(msg='', title=' ', choices=('Button[1]', 'Button[2]', 'Button[3]'), image=None, images=None, default_choice=None, cancel_choice=None, callback=None, run=True)
Display a message, a title, an image, and a set of buttons.
The buttons are defined by the members of the choices argument.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: (Only here for backward compatibility)
:param str images: Filename of image or iterable or iteratable of iterable to display
:param str default_choice: The choice you want highlighted when the gui appears
:return: the text of the button that the user selected
显示多个按钮,按钮由参数choices的元组来定义,按钮的个数取决于元组的元素个数。
importeasyguiasegeg.buttonbox(msg='请选择:', title='自定义确认框', choices=('浏览...', '确定', '取消'), image=None, images=None, default_choice="确定", cancel_choice=None, callback=None, run=True)
8. 单行文本框 enterbox
enterbox(msg='Enter something.', title=' ', default='', strip=True, image=None, root=None)
Show a box in which a user can enter some text.
You may optionally specify some default text, which will appear in the nterbox when it is displayed.
:param str msg: the msg to be displayed.
:param str title: the window title
:param str default: value returned if user does not change it
:param bool strip: If True, the return value will have its whitespace stripped before being returned
:return: the text that the user entered, or None if they cancel the operation.
显示一个框,用户可以在其中输入一些文本。您可以选择指定一些默认文本显示时显示在对话框中,如下图:
importeasyguiasegreply=eg.enterbox('请输入车牌号:','单行文本框', default='例如:苏ENH905') ifreply: eg.msgbox(f'你的输入为:{reply}') else: eg.msgbox('输入为空,或者点了取消Cancel')
9. 多行文本框 textbox
textbox(msg='', title=' ', text='', codebox=False, callback=None, run=True)
Displays a dialog box with a large, multi-line text box, and returns the entered text as a string. The message text is displayed in a proportional font and wraps.
Parameters
----------
msg : string
text displayed in the message area (instructions...)
title : str
the window title
text: str, list or tuple
text displayed in textAreas (editable)
codebox: bool
if True, don't wrap and width is set to 80 chars
callback: function
if set, this function will be called when OK is pressed
run: bool
if True, a box object will be created and returned, but not run
Returns
-------
None
If cancel is pressed
str
If OK is pressed returns the contents of textArea
显示一个带有多行文本框的对话框,并将输入的文本作为字符串返回。例如:
importeasyguiasegtxt='''一、基本信息 姓名:XX 性别:X 年龄:X 婚姻状况:XX 毕业院校:XX 联系电话:XXXXXXXXXXX二、求职意向 意向岗位:XXXX 证书:XXX 薪资要求:面议 工作能力及专长:本人有一定的......。三、工作经历 XXXX年X月~XXXX年X月,......。 XXXX年X月~XXXX年X月,......。四、自我评价 本人对工作......'''reply=eg.textbox(msg='请按以下模板输入你的简历:', title='简历', text=txt, codebox=False, callback=None, run=True) print(reply)
10. 文件打开框 fileopenbox
fileopenbox(msg=None, title=None, default='*', filetypes=None, multiple=False)
Displays an "open file" dialog box and returns the selected file as a string.
The "default" argument specifies a filepath that (normally) contains one or more wildcards.
fileopenbox() will display only files that match the default filepath.
If omitted, defaults to "\*" (all files in the current directory).
:param str msg: the msg to be displayed.
:param str title: the window title
:param str default: filepath with wildcards
:param object filetypes: filemasks that a user can choose, e.g. "\*.txt"
:param bool multiple: If true, more than one file can be selected
:return: the name of a file, or None if user chose to cancel
显示“打开文件”对话框,并将所选文件作为字符串返回。“default”参数指定(通常)包含一个或多个通配符的文件路径。例如,默认打开Excel文件如下:
importeasyguiasegeg.fileopenbox(msg=None, title=None, default='*.xls', filetypes=None, multiple=False)
11. 文件保存框 filesavebox
filesavebox(msg=None, title=None, default='', filetypes=None)
A file to get the name of a file to save.
Returns the name of a file, or None if user chose to cancel.
**About the "default" argument**
The ``default`` argument specifies the path and "glob pattern" for file names. The "\*" value, for example, sets the open file dialog to the current working directory and showing all files.
For another example, setting the ``default`` argument to ``"C:/myjunk/*.py"`` sets the open file dialog to the C:\myjunk folder and showing only files that have the .py file extension. This glob pattern at the end of the ``default`` argument is required: passing ``"C:/myjunk"`` would not set the open file dialog to the C:\myjunk folder, but rather to the C:\ folder and "myjunk" as the initial filename.
Note that on Windows, ``fileopenbox()`` automatically changes the path separator to the Windows path separator (backslash).
The "filetypes" argument works like the "filetypes" argument to fileopenbox.
:param str msg: the msg to be displayed.
:param str title: the window title
:param str default: default filename to return
:param object filetypes: filemasks that a user can choose, e.g. " \*.txt"
:return: the name of a file, or None if user chose to cancel
用于获取要保存的文件的名称的文件。返回文件名,如果用户选择取消,则返回“无”。
importeasyguiasegeg.filesavebox(msg=None, title=None, default='*.xls', filetypes=None)
12. 目录打开框 diropenbox
diropenbox(msg=None, title=None, default=None)
A dialog to get a directory name.
Returns the name of a directory, or None if user chose to cancel.
If the "default" argument specifies a directory name, and that directory exists, then the dialog box will start with that directory.
:param str msg: used in the window title on some platforms
:param str title: the window title
:param str default: starting directory when dialog opens
:return: Normalized path selected by user
用于获取目录名的对话框。返回目录的名称,如果用户选择取消,则返回“无”。
如果“default”参数指定了一个目录名,并且该目录存在,则对话框将从该目录开始。
importeasyguiasegeg.diropenbox(msg=None, title=None, default=r'E:\Tables')
13. 索引对话框 indexbox
indexbox(msg='Shall I continue?', title=' ', choices=('Yes', 'No'), image=None, default_choice='Yes', cancel_choice='No')
The ``indexbox()`` function displays a set of buttons, and returns the index of the selected button. For example, if you invoked index box with three choices (A, B, C), indexbox would return 0 if the user picked A, 1 if he picked B, and 2 if he picked C.
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param str image: Filename of image to display
:param str default_choice: The choice you want highlighted when the gui appears
:param str cancel_choice: If the user presses the 'X' close, which button should be pressed
:return: the index of the choice selected, starting from 0
显示一组按钮,并返回所选按钮的索引。例如,如果您使用三个选项(A、B、C)调用索引框,则如果用户选择A,indexbox将返回0,如果用户选择B,则返回1,如果选择C,则返回2。
importeasyguiasegresult=eg.indexbox('Which door do you choose?', 'Win Prizes!', choices=['Door 1', 'Door 2', 'Door 3']) ifresult==2: eg.msgbox('You win a new car!') else: eg.msgbox('Better luck next time.')
14. 例外报告框 exceptionbox
exceptionbox(msg=None, title=None)
Display a box that gives information about an exception that has just been raised.
The caller may optionally pass in a title for the window, or a msg to accompany the error information.
Note that you do not need to (and cannot) pass an exception object as an argument. The latest exception will automatically be used.
:param str msg: the msg to be displayed
:param str title: the window title
:return: None
报告错误或例外异常的信息,调用者可以选择性地传入窗口的标题或伴随错误信息的消息。
15. 代码文本框 codebox
codebox(msg='', title=' ', text='')
Display some text in a monospaced font, with no line wrapping.
This function is suitable for displaying code and text that is formatted using spaces.
The text parameter should be a string, or a list or tuple of lines to be displayed in the textbox.
:param str msg: the msg to be displayed
:param str title: the window title
:param str text: what to display in the textbox
与多行文本框textbox(msg='', title=' ', text='', codebox=False, callback=None, run=True)很相似,少了后三个参数:
16. 密码输入框 passwordbox
passwordbox(msg='Enter your password.', title=' ', default='', image=None, root=None)
Show a box in which a user can enter a password.
The text is masked with asterisks, so the password is not displayed.
:param str msg: the msg to be displayed.
:param str title: the window title
:param str default: value returned if user does not change it
:return: the text that the user entered, or None if they cancel
the operation.
显示一个框,用户可以在其中输入密码。文本用星号屏蔽,因此不会显示密码。
importeasyguiasegeg.passwordbox(msg='请输入密码:', title='密码输入框', default='456123', image=None, root=None)
17. 多重文本框 multenterbox
multenterbox(msg='Fill in values for the fields.', title=' ', fields=[], values=[], callback=None, run=True)
Show screen with multiple data entry fields.
If there are fewer values than names, the list of values is padded with empty strings until the number of values is the same as the number of names.
If there are more values than names, the list of values is truncated so that there are as many values as names.
Returns a list of the values of the fields, or None if the user cancels the operation.
:param str msg: the msg to be displayed.
:param str title: the window title
:param list fields: a list of fieldnames.
:param list values: a list of field values
:return: String
显示包含多个数据输入字段,即同一个对话框中有多个单行文本框。例如:
importeasyguiasegmsg="Enter your personal information"title="Credit Card Application"fieldNames= ["Name","Address","City","State","ZipCode"] fieldValues= [] # we start with blanks for the valuesfieldValues=eg.multenterbox(msg,title, fieldNames) # make sure that none of the fields was left blankwhile1: iffieldValuesisNone: breakerrmsg=""foriinrange(len(fieldNames)): iffieldValues[i].strip() =="": errmsg+= ('"%s" is a required field.\n\n'%fieldNames[i]) iferrmsg=="": break# no problems foundfieldValues=eg.multenterbox(errmsg, title, fieldNames, fieldValues) print("Reply was: %s"%str(fieldValues))
18. 组合密码框 multpasswordbox
multpasswordbox(msg='Fill in values for the fields.', title=' ', fields=(), values=(), callback=None, run=True)
Same interface as multenterbox. But in multpassword box, the last of the fields is assumed to be a password, and is masked with asterisks.
:param str msg: the msg to be displayed.
:param str title: the window title
:param list fields: a list of fieldnames.
:param list values: a list of field values
:return: String
与多重文本框相似,但最后一个是密码框,输入会补星号代替,例如:
importeasyguiasegmsg="输入你的登录信息:"title="组合密码框"fieldNames= ["账号:", "密码:"] fieldValues=eg.multpasswordbox(msg,title, fieldNames) # make sure that none of the fields was left blankwhile1: iffieldValues[0].strip() =="": errmsg='账号不可为空!'fieldValues=eg.multpasswordbox(errmsg, title, fieldNames, fieldValues) eliffieldValues[1].strip() =="": errmsg='密码不可为空!'fieldValues=eg.multpasswordbox(errmsg, title, fieldNames, fieldValues) else: breakprint("账号、密码分别为: %s"%fieldValues)
19. 多项选择框 multchoicebox
multchoicebox(msg='Pick an item', title='', choices=None, preselect=0, callback=None, run=True)
The ``multchoicebox()`` function provides a way for a user to select from a list of choices. The interface looks just like the ``choicebox()`` function's dialog box, but the user may select zero, one, or multiple choices.
The choices are specified in a sequence (a tuple or a list).
:param str msg: the msg to be displayed
:param str title: the window title
:param list choices: a list or tuple of the choices to be displayed
:param preselect: Which item, if any are preselected when dialog appears
:return: A list of strings of the selected choices or None if cancelled.
与单项选择框 choicebox() 相似,只有单项选择和多项选择的区别:
importeasyguiasegmsg="What is your favorite flavor?"title="Ice Cream Survey"choices= ["Vanilla", "Chocolate", "Strawberry", "Rocky Road"] choice=eg.multchoicebox(msg, title, choices)
总结
EasyGUI为Python开发者提供了一个快速创建基本图形用户界面的途径。它降低了GUI开发的门槛,使得即使是没有经验的开发者也能轻松构建出功能完善的界面。尽管它可能不适合复杂的应用程序或专业的软件开发项目,但对于快速原型设计、小型项目和教学目的来说,它是一个强大而高效的工具。通过利用EasyGUI的简单性和灵活性,开发者可以专注于解决问题,而不是纠结于复杂的界面细节。

























































