GUI——图形用户界面

Python吸引我的地方就是,它不仅可以进行文本编程,还可以建立窗口、按钮之类的图形。

一、下载easygui

在学习GUI之前,先下载一个GUI模块EasyGui戳这里
下载一个压缩包到电脑之后,解压打开找到一个叫“easygui”d的文件夹,需要把这个文件夹放到指定位置:

首先找到Python的安装位置->打开名字为“Lib”的文件夹->再把“easygui”d放到这个文件夹里。

OK,搞定!下边开始建立我们第一个GUI吧。

二、建立GUI

打开IDLE,在交互模式键入以下命令:

>>> import easygui
>>> easygui.msgbox("SurYmy!")

在这里插入图片描述
点击“OK”,交互界面会出现一个‘OK’字符,这是在告诉你:用户点击了OK按钮。
在这里插入图片描述
我们也可以给这个响应起个名字:
在这里插入图片描述

三、有多个按钮的对话框

键入以下命令:

import easygui
fairy = easygui.buttonbox("Who is your little fairy man? ",
                choices = ['L','S','M'])
easygui.msgbox("You picked " + fairy)

出现两个界面:
在这里插入图片描述
在这里插入图片描述
这是怎么做到的呢?用户点击的按钮的标签就是输入。我们为这个输入指定一个变量名,在这里就是fairy。这就像使用raw_input(),只不过用户不是键入,而是点击一个按钮。

四、选择框

建立文件,键入以下命令:

import easygui
fairy = easygui.choicebox("Who is your little fairy man?",
                choices = ['L','S','M'])
easygui.msgbox("You picked " + fairy)

在这里插入图片描述
注意这里除了用鼠标点击选择外,还可以用键盘上的上下箭头选择。点击OK,同样会出现这个界面:
在这里插入图片描述

五、使用输入框

键入:

import easygui
fairy = easygui.enterbox("Who is your little fairy?")
easygui.msgbox("You entered " + fairy)

在这里插入图片描述
在这里插入图片描述

六、建立默认参数

键入:

import easygui
fairy = easygui.enterbox("Who is your little fairy man?",
                         default = 'YMY')
easygui.msgbox("You entered " + fairy)

在这里插入图片描述
输入框中出现一个默认值。如果选项可以,就不用再键入任何内容,只需点击OK。不过,假如不是自己想要的选项,可以把它删掉,再输入想要的内容:
在这里插入图片描述
在这里插入图片描述

七、键入数字

键入:

import easygui
favotite = easygui.integerbox("What is your favorite number?")
easygui.msgbox("You entered " + str(favotite))

在这里插入图片描述
在这里插入图片描述

八、升级猜数游戏

修改后:

import easygui,random
secret = random.randint(1,99)
guess = 0
tries = 0

easygui.msgbox("""AHOY! I'm the Dread Priate 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 is your guess?")
    if not guess: break
    if guess < secret:
        easygui.msgbox(str(guess) + " is too low!")
    elif guess > secret:
        easygui.msgbox(str(guess) + " is too high!")
    tries = tries + 1

if guess == secret:
    easygui.msgbox("Congratulations!You got it!")
else:
    easygui.msgbox("No more guesses! Better luck next time!")

猜你喜欢

转载自blog.csdn.net/qq_37369201/article/details/82818153