第 6 章
测试题
- 要用 EasyGui 显示一个消息框,可以使用 msgbox(),如下:
easygui.msgbox("This is the answer!")
要用 EasyGui 得到一个字符串输入,要使用 enterbox。
要得到整数输入,可以使用 enterbox(这会由用户得到一个字符串),然后把它转换为 int。或者也可以直接使用 integerbox。
要从用户那里得到浮点数,可以使用一个 enterbox(这会提供一个字符串),然后使用 float() 函数把这个字符串转换成一个浮点数。
默认值就像“自动获得的答案”。以下是一种可能使用默认值的情况:你在编写程序,你班里的所有学生都必须输入他们的名字和地址,你可以把你居住的城市名作为地址中的默认城市。这样一来,学生们就不用再键入城市了(除非他们居住在其他城市)。
动手试一试
- 以下是一个使用 EasyGui 的温度转换程序:
# tempgui1.py
# EasyGui version of temperature-conversion program
# converts Fahrenheit to Celsius
import easygui
easygui.msgbox('This program converts Fahrenheit to Celsius')
temperature = easygui.enterbox('Type in a temperature in Fahrenheit:')
Fahr = float(temperature)
Cel = (Fahr - 32) * 5.0 / 9
easygui.msgbox('That is ' + str(Cel) + ' degrees Celsius.')
- 下面这个程序会询问你的名字以及地址的各个部分,然后显示完整的地址。要理解这个程序,如果了解如何强制换行会很有帮助:换行会让后面的文本从新的一行开始。为达到这个目的,需要使用 \n。这会在第 21 章解释,不过下面先提前了解一下:
# address.py
# Enter parts of your address and display the whole thing
import easygui
name = easygui.enterbox("What is your name?")
addr = easygui.enterbox("What is your street address?")
city = easygui.enterbox("What is your city?")
state = easygui.enterbox("What is your state or province?")
code = easygui.enterbox("What is your postal code or zip code?")
whole_addr = name + "\n" + addr + "\n" + city + ", " + state + "\n" + code
easygui.msgbox(whole_addr, "Here is your address:")
