在上一篇文章中,我们使用textbox接收用户输入多行的文字。如果需要接收用户单行输入,或者接收用户多种类型的单行数据输入,则可以分别使用enterbox和multenterbox。
enterbox的函数原型是:
enterbox(msg='Enter something.',title=' ',default='',strip=True,image=None,root=None)
其中msg和title的含义和前面两个组件的含义一样。第三个参数是输入框中的默认值。strip用于设置是否去除返回的输入字符串前后的空格。image可以用于给这个对话框添加一张图片,它将会在提示信息和输入框之间添加一个图片组件。
下面我们来看一个enterbox的示例。
from easygui import *name = enterbox("请输入您的姓名","个人信息","",True,"python.png")print(name)
它的运行结果如下:
添加的图片将按照图片原始大小显示。如果在文本框中输入的值前后有空格,因为程序中将strip参数设置成了True,所以将会被去掉。也可以直接访问下面地址查看运行效果。
https://www.cncoding.cn/python/public_133951
如果需要一次性输入多个值,则可以使用multenterbox(),它的原型如下:
multenterbox(msg='Fill in values for the fields.',title=' ',fields=[],values=[],callback=None,run=True)
其中fields是输入框前的提示标签文字,以列表形式指定;values是各个输入框的默认值,也以列表形式指定,values的元素个数可以和fields中的不同;callback为点击对话框上的OK按钮之后的回调函数。run为是否打开显示这个对话框,如果为False,只会创建这个multenterbox()对象,而不会显示它。(说实话我现在也没想明白它用在什么场合)
这里用一个官方的案例来作为示例,说明它的用法:
from easygui import *class Demo2():def __init__(self):msg = "Without flicker. Enter your personal information"title = "Credit Card Application"fieldNames = ["Name", "Street Address", "City", "State", "ZipCode"]fieldValues = [] # we start with blanks for the valuesfieldValues = multenterbox(msg, title, fieldNames, fieldValues,callback=self.check_for_blank_fields)print("Reply was: {}".format(fieldValues))def check_for_blank_fields(self, box):# make sure that none of the fields was left blankcancelled = box.values is Noneerrors = []if cancelled:passelse: # check for errorsfor name, value in zip(box.fields, box.values):if value.strip() == "":errors.append('"{}" is a required field.'.format(name))all_ok = not errorsif cancelled or all_ok:box.stop() # no problems foundbox.msg = "\n".join(errors)Demo2()
其初始运行效果如下:
可以访问以下链接直接运行查看结果。
https://www.cncoding.cn/python/public_133052
和enterbox()类似的还有两个用于特殊用途的单行输入对话框:passwordbox用于接收输入密码,integerbox用于接收用户数字输入;和multenterbox类似的有multpasswordbox,它和multenterbox非常类似,只是多个输入框中最后一个输入框,用于输入密码,其他用法和multenterbox基本一样,此处不再赘述。
