这一章,开始接触到图形界面,GUI用的是easygui,google后得到。
>>> import easygui
>>>
要使用模块前,这是必须的,import模块。
>>> import easygui
>>> easygui.msgbox("Hello world!!")
'OK'
>>>
还可以这样
>>> user_response = easygui.msgbox("Hello world!!")
>>> print user_response
OK
>>>
下面来一个用图形界面选择按钮,代码如下
# 与孩子一起学编程06章
# 2013年8月25日22:25:19
# easygui 使用图形界面 6-1
import easygui
flavor = easygui.buttonbox("What is your favorite ice cream flavor?",
choices = ['Vanilla', 'Chocolate', 'Strawberry'])
easygui.msgbox("You picked " + flavor)
还可以这样
# 与孩子一起学编程06章
# 2013年8月25日22:45:27
# easygui 使用图形界面 6-2
import easygui
flavor = easygui.choicebox("What is your favorite ice cream flavor?",
choices = ['Vanilla', 'Chocolate', 'Strawberry'])
easygui.msgbox("You picked " + flavor)
还可以用输入框自己输入
# 与孩子一起学编程06章
# 2013年8月25日22:46:37
# easygui 使用输入框得到输入 6-3
import easygui
flavor = easygui.enterbox("What is your favorite ice cream flavor")
easygui.msgbox("You entered " + flavor)
默认输入,这样的
# 与孩子一起学编程06章
# 2013年8月25日22:51:36
# easygui 使用默认输入 6-4
import easygui
flavor = easygui.enterbox("What is your favorite ice cream flavor",
default = 'Vanilla')
easygui.msgbox("You entered " + flavor)
这样,就有个默认输入。
怎么输入数字,下面是一个前面用过的一个猜数字游戏,这次,换用图形界面来猜,试试看
# 与孩子一起学编程06章
# 2013年8月25日22:57:48
# 使用easygui的猜数游戏 6-5
import random, easygui
secret = random.randint(1, 99)
guess = 0
tries = 0
easygui.msgbox("""AHOY! I'm the Dread Pirate Roberts, and I have a secret!
It is a number from 1 to 99. I'll give you 6 tries.""")
while guess != secret and tries < 6:
guess = easygui.integerbox("What's yer guess, matey")
if not guess: break
if guess < secret:
easygui.msgbox(str(guess) + " is too low, ye scurvy dog!")
elif guess > secret:
easygui.msgbox(str(guess) + " is too high, landlubber!")
tries = tries + 1
if guess == secret:
easygui.msgbox("Avast! Ye got it! Found my secret, ye did!")
else:
easygui.msgbox("No more guesses! Better luck next time, matey!")
嗯,还是挺有意思的,是吧,好玩的python,越来越有意思了,呵呵。