[学习笔记] Python【第035讲:图形用户界面入门:EasyGui】总结

[扩展阅读] EasyGUI 学习文档【超详细中文版】
Python 模块EasyGui详细介绍
0、安装 EasyGUI

C:\Users\sjk>D:

D:\Program Files (x86)\python\Scripts>**pip install easygui**
Collecting easygui
  Downloading easygui-0.98.1-py2.py3-none-any.whl (90 kB)
     |████████████████████████████████| 90 kB 3.5 kB/s
Installing collected packages: easygui
Successfully installed easygui-0.98.1
WARNING: You are using pip version 20.1.1; however, version 20.2.2 is available.
You should consider upgrading via the 'd:\program files (x86)\python\python.exe -m pip install --upgrade pip' command.

D:\Program Files (x86)\python\Scripts>**python -m pip install --upgrade pip -i https://pypi.douban.com/simple**
Looking in indexes: https://pypi.douban.com/simple
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.VerifiedHTTPSConnection object at 0x042086D0>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed')': /simple/pip/
Collecting pip
  Downloading https://pypi.doubanio.com/packages/5a/4a/39400ff9b36e719bdf8f31c99fe1fa7842a42fa77432e584f707a5080063/pip-20.2.2-py2.py3-none-any.whl (1.5 MB)
     |████████████████████████████████| 1.5 MB 1.3 MB/s
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 20.1.1
    Uninstalling pip-20.1.1:
      Successfully uninstalled pip-20.1.1
Successfully installed pip-20.2.2

D:\Program Files (x86)\python\Scripts>pip --version
pip 20.2.2 from d:\program files (x86)\python\lib\site-packages\pip (python 3.8)

D:\Program Files (x86)\python\Scripts>

**

一、使用按钮组件

**
根据需求,EasyGUI 在 buttonbox() 上建立了一系列的函数供调用
1、msgbox()

>>> import easygui as g
>>> help(g.msgbox)
Help on function msgbox in module easygui.boxes.derived_boxes:

msgbox(msg='(Your message goes here)', title=' ', ok_button='OK', image=None, root=None)
    Display a message box
    
    :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

msgbox(msg=’(Your message goes here)’, title=’ ', ok_button=‘OK’, image=None, root=None)
msgbox() 显示一个消息和提供一个"OK"按钮,你可以指定任意的消息和标题,你甚至可以重写"OK"按钮的内容。
重写 “OK” 按钮最简单的方法是使用关键字参数:

>>> import easygui as g
>>> g.msgbox('学好python', 'come on!')
'OK'
>>> g.msgbox('学好python', 'come on!', 'Yes')
'Yes'
>>> g.msgbox('学好python', ok_button='Yes')  #是这一句
'Yes'
>>> 

在这里插入图片描述
2、ccbox()

>>> import easygui as g
>>> help(g.ccbox)
Help on function ccbox in module easygui.boxes.derived_boxes:

ccbox(msg='Shall I continue?', title=' ', choices=('C[o]ntinue', 'C[a]ncel'), image=None, default_choice='Continue', cancel_choice='Cancel')
    Display a msgbox with choices of Continue and Cancel.
    
    The returned value is calculated this way::
    
        if the first choice ("Continue") is chosen,
          or if the dialog is cancelled:
            return True
        else:
            return False
    
    If invoked without a msg argument, displays a generic
    request for a confirmation
    that the user wishes to continue.  So it can be used this way::
    
        if ccbox():
            pass # continue
        else:
            sys.exit(0)  # exit the program
    
    :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'

>>> 

ccbox(msg=‘Shall I continue?’, title=’ ', choices=(‘C[o]ntinue’, ‘C[a]ncel’), image=None, default_choice=‘C[o]ntinue’, cancel_choice=‘C[a]ncel’)
ccbox() 提供一个选择:“C[o]ntinue” 或者 “C[a]ncel”,并相应的返回 True 或者 False。
注意:“C[o]ntinue” 中的 [o] 表示快捷键,也就是说当用户在键盘上敲一下 o 字符,就相当于点击了 “C[o]ntinue” 按键。

import sys
import easygui as g

if g.ccbox('一起玩?',choices=('好啊^_^', '不了T_T')):
    g.msgbox('结束,回家')
else:
    sys.exit(0)

在这里插入图片描述
3、ynbox()
ynbox(msg=‘Shall I continue?’, title=’ ‘, choices=(’[]Yes’, ‘[]No’), image=None, default_choice=’[]Yes’, cancel_choice=’[]No’)
跟 ccbox() 一样,只不过这里默认的 choices 参数值不同而已,[] 表示将键盘上的 F1 功能按键作为 “Yes” 的快捷键使用。

>>> import easygui as g
>>> help(g.ynbox)
Help on function ynbox in module easygui.boxes.derived_boxes:

ynbox(msg='Shall I continue?', title=' ', choices=('[<F1>]Yes', '[<F2>]No'), image=None, default_choice='[<F1>]Yes', cancel_choice='[<F2>]No')
    Display a msgbox with choices of Yes and No.
    
    The returned value is calculated this way::
    
        if the first choice ("Yes") is chosen, or if the dialog is cancelled:
            return True
        else:
            return False
    
    If invoked without a msg argument, displays a generic
    request for a confirmation
    that the user wishes to continue.  So it can be used this way::
    
        if ynbox():
            pass # continue
        else:
            sys.exit(0)  # exit the program
    
    :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'

>>> 

4、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)
可以使用 buttonbox() 定义自己的一组按钮,buttonbox() 会显示一组由你自定义的按钮
当用户点击任意一个按钮的时候,buttonbox() 返回按钮的文本内容。
如果用户点击取消或者关闭窗口,那么会返回默认选项(第一个选项)。

>>> import easygui as g
>>> help(g.buttonbox)
Help on function buttonbox in module easygui.boxes.button_box:

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 msg, a title, an image, and a set of buttons.
    The buttons are defined by the members of the choices global_state.
    
    :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

>>> 
>>> import easygui as g
>>> g.buttonbox('Do you like?', choices=('banana', 'apple', 'orange'))
'banana'
>>> 

5、indexbox()
indexbox(msg=‘Shall I continue?’, title=’ ', choices=(‘Yes’, ‘No’), image=None, default_choice=‘Yes’, cancel_choice=‘No’)
基本跟 buttonbox() 一样,区别就是当用户选择第一个按钮的时候返回序号 0, 选择第二个按钮的时候返回序号 1。

>>> import easygui as g
>>> g.indexbox('Do you like?', choices=('banana', 'apple', 'orange')) #可以有三个选项

6、boolbox()
boolbox(msg=‘Shall I continue?’, title=’ ‘, choices=(’[Y]es’, ‘[N]o’), image=None, default_choice=‘Yes’, cancel_choice=‘No’)
如果第一个按钮被选中则返回 True,否则返回 False。

>>> import easygui as g
>>> g.boolbox('Do you like?', choices=('banana', 'apple'))

7、 如何在 buttonbox 里边显示图片
当你调用一个 buttonbox 函数(例如 msgbox(), ynbox(), indexbox() 等等)的时候,你还可以为关键字参数 image 赋值,可以设置一个 .gif 格式的图像(PNG 格式的图像也是支持的哦_):
安装PIL第三方库:

C:\Users\sjk>**pip install Pillow -i https://pypi.tuna.tsinghua.edu.cn/simple**
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting Pillow
  Downloading https://pypi.tuna.tsinghua.edu.cn/packages/9c/f0/00f71c1a52859f8f1b82ed6bc2bf5890321511b642c01242d38df02bb5d0/Pillow-7.2.0-cp38-cp38-win32.whl (1.8 MB)
     |████████████████████████████████| 1.8 MB 3.3 MB/s
Installing collected packages: Pillow
Successfully installed Pillow-7.2.0

C:\Users\sjk>python -m pip install pillow -i https://pypi.tuna.tsinghua.edu.cn/simple
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Requirement already satisfied: pillow in d:\program files (x86)\python\lib\site-packages (7.2.0)

C:\Users\sjk>

PIL安装成功后,就可以设置一个 .jpg格式的图像了。

>>> import easygui as g
>>> g.buttonbox('大家说我长得帅吗?', image=r'C:\Users\sjk\Pictures\Saved Pictures\2.png', choices=('帅', '不帅', '!@#$%'))
'C:\\Users\\sjk\\Pictures\\Saved Pictures\\2.png'
>>> g.buttonbox('大家说我长得帅吗?', image=r'C:\Users\sjk\Pictures\Saved Pictures\1.jpg', choices=('帅', '不帅', '!@#$%'))
'C:\\Users\\sjk\\Pictures\\Saved Pictures\\1.jpg'
>>> 

8、choicebox()
choicebox(msg=‘Pick an item’, title=’’, choices=[], preselect=0, callback=None, run=True)
按钮组件方便提供用户一个简单的按钮选项,但如果有很多选项,或者选项的内容特别长的话,更好的策略是为它们提供一个可选择的列表。
choicebox() 为用户提供了一个可选择的列表,使用序列(元祖或列表)作为选项,这些选项会按照字母进行排序。
另外还可以使用键盘来选择其中一个选项(比较纠结,但一点儿都不重要):
例如当按下键盘上的 “g” 键,将会选中的第一个以 “g” 开头的选项。再次按下 “g” 键,则会选中下一个以 “g” 开头的选项。在选中最后一个以 “g” 开头的选项的时候,再次按下 “g” 键将重新回到在列表的开头的第一个以 “g” 开头的选项。
如果选项中没有以 “g” 开头的,则会选中字符排序在 “g” 之前(“f”)的那个字符开头的选项
如果选项中没有字符的排序在 “g” 之前的,那么在列表中第一个元素将会被选中。
9、multchoicebox()
10、enterbox()
11、integerbox()
12、multenterbox()
13、passwordbox()
14、textbox()
15、codebox()
16、diropenbox()
17、fileopenbox()
18、filesavebox()
19、EgStore
20、exceptionbox()

二、动动手:

0. 先练练手,把我们的刚开始的那个猜数字小游戏加上界面吧?
在这里插入图片描述

import random
import easygui as g

g.msgbox("嗨,欢迎进入第一个界面小游戏^_^")
secret = random.randint(1, 10)
#temp = input('不妨猜一下小甲鱼现在心里想的是哪个数字:')
#guess = int(temp)

msg = '不妨猜一下小甲鱼现在心里想的是哪个数字(1~10):'
title = '数字小游戏'

while 1:
    #temp = input('no,please again:')
    #guess = int(temp)
    guess = g.integerbox(msg, title, lowerbound=1, upperbound=10)
    if guess == secret:
        g.msgbox('your guess is right')
        g.msgbox('very good')
        break
    else:
        if guess > secret:
            g.msgbox('too big')
        else:
            g.msgbox('too small')

g.msgbox('game over')

1. 如下图,实现一个用于登记用户账号信息的界面(如果是带 * 号的必填项,要求一定要有输入并且不能是空格)。

import easygui as g

msg = '请填写以下联系方式'
title = '账号中心'
fieldNames = [" *用户名", " *真实姓名", "  固定电话", " *手机号码", "  QQ", " *E-mail"]
fieldValues = [] #定义,可以删掉?注释之后运行无影响
fieldValues = g.multenterbox(msg, title, fieldNames)

# make sure that none of the fields was left blank
while 1:
    if fieldValues == None: #点击取消按钮操作
        break
    errmsg = ''  #报错提示初始值
    for i in range(len(fieldNames)): #len(fieldNames)=6
        option = fieldNames[i].strip() #strip()去除首尾空格
        if fieldValues[i].strip() == '' and option[0] == '*':
            errmsg += ('【%s】为必填项。\n\n' % fieldNames[i])
    if errmsg == '': #无报错提示,退出程序,否则,报错提示,重新进入输入界面
        break
    fieldValues = g.multenterbox(errmsg, title, fieldNames, fieldValues)

print("用户资料如下:%s" % str(fieldValues))


#fieldValues[i].strip() == '':判断是否为空字符,如果是空字符的话,这里表示没有输入
#errmsg += ('【%s】为必填项。\n\n' % fieldNames[i])可有下面的例子知,将fieldNames[i]中的字符串写入errmsg中
>>> f = ['123', 'ab']
>>> err = ''
>>> err
''
>>> err += f[1]
>>> err
'ab'
>>> 

#strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
#注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

2. 提供一个文件夹浏览框,让用户选择需要打开的文本文件,打开并显示文件内容
在这里插入图片描述

import easygui as g
import os

file_path = g.fileopenbox(default="*.txt")

with open(file_path, encoding='utf-8') as f:
    title = os.path.basename(file_path) #os.path.basename(path)返回文件名,如record.txt
    msg = "文件【%s】的内容如下:" % title
    text = f.read()
    g.textbox(msg, title, text)


**#diropenbox(msg=None, title=None, default=None)**
diropenbox() 函数用于提供一个对话框,返回用户选择的目录名(带完整路径哦),如果用户选择 “Cancel” 则返回 None。
default 参数用于设置默认的打开目录(请确保设置的目录已存在)。

#**textbox(msg='', title=' ', text='', codebox=False, callback=None, run=True)**
textbox() 函数默认会以比例字体(参数 codebox=True 设置为等宽字体)来显示文本内容(自动换行),这个函数适合用于显示一般的书面文字。
注:text 参数设置可编辑文本区域的内容,可以是字符串、列表或者元祖类型。

3. 在上一题的基础上增强功能:当用户点击“OK”按钮的时候,比较当前文件是否修改过,如果修改过,则提示“覆盖保存”、”放弃保存”或“另存为…”并实现相应的功能。
(提示:解决这道题可能需要点耐心,因为你有可能会被一个小问题卡住,但请坚持,自己想办法找到这个小问题所在并解决它!
在这里插入图片描述
答:这道题会出现的一个小问题就是 easygui.textbox 函数会在返回的字符串后边追加一个行结束符(“\n”),因此在比较字符串是否发生改变的时候我们需要人工将这个行结束符忽略。
好像最新版本的 textbox 是不会追加换行符了?(个人验证不会追加换行符)

import easygui as g
import os

file_path = g.fileopenbox(default="*.txt")

with open(file_path, encoding='utf-8') as old_file:
    title = os.path.basename(file_path)
    msg = "文件【%s】的内容如下:" % title
    text = old_file.read()
    text_after = g.textbox(msg, title, text)

#if text != text_after[:-1]: #最新版本的 textbox 是不会追加换行符了   
if text != text_after: #不对text_after文本进行修改,则不会往下执行了
    # textbox 的返回值会追加一个换行符(之前版本)
    choice = g.buttonbox("检测到文件内容发生改变,请选择以下操作:", "警告", ("覆盖保存", "放弃保存", "另存为..."))
    if choice == "覆盖保存":
        with open(file_path, "w") as old_file:
            #old_file.write(text_after[:-1])
            old_file.write(text_after)
    if choice == "放弃保存":
        pass
    if choice == "另存为...":
        another_path = g.filesavebox(default=".txt")
        if os.path.splitext(another_path)[1] != '.txt':
            another_path = os.path.splitext(another_path)[0] #添加这一句是为了将除.txt文件以外的格式的文件如0831_3.py的扩展名.py删掉
            another_path += '.txt'
            #os.path.splitext(another_path)[0] += '.txt' #tuple 类型一旦初始化就不能修改,所以你要是修改它就会报错。
        with open(another_path, "w") as new_file:
            #new_file.write(text_after[:-1])
            new_file.write(text_after)

#os.path.splitext(another_path)[0] += '.txt'会报错:
Traceback (most recent call last):
  File "D:/Program Files/1/35讲/0901_6.py", line 27, in <module>
    os.path.splitext(another_path)[0] += '.txt'
TypeError: 'tuple' object does not support item assignment
是因为元组tuple 类型一旦初始化就不能修改,要是修改它就会报错。
可以进行一个赋值操作:another_path = os.path.splitext(another_path)[0]
然后再another_path += '.txt' 这样就避免了修改tuple类型


#if text != text_after[:-1]:
字符串text_after[:-1]就是少一个最后一个字符而已
1.text_after[-1]
表示索引,index:
-1就是倒数第一个元素,索引从左往右是0,1,2,3……从右往左是-1,-2,-3……
2. print(a[:-1])
除了最后一个取全部
>>> b = ['12', '34', '56']
>>> b
['12', '34', '56']
>>> b[:-1]
['12', '34']
>>> c = '12345'
>>> c
'12345'
>>> c[:-1]
'1234'

4. 写一个程序统计你当前代码量的总和,并显示离十万行代码量还有多远?
要求一:递归搜索各个文件夹
要求二:显示各个类型的源文件和源代码数量
要求三:显示总行数与百分比
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值