环境:Ubuntu 14.04 LTS , pyhton3.4
Tkinter模块是Python的标准GUI库。
在学习tkinter模块时,做一个小游戏,学以致用,同时方便自己理解。
1.首先看整体界面
代码语言:javascript复制import tkinter
import tkinter.messagebox
import random
root =tkinter.Tk()
root.minsize(350,260)
root.title('猜数字游戏')
导入tkinter模块及其他模块。
建一个界面,确定大小,名字。
2.Label 用以显示文字和图片。
Entry文本框,显示单行。Text 文本框,显示多行。
3.使用messageBox发送弹窗
在文本框里输入自己的名字后,点击确定,跳出如图所示弹窗。
4. 在文本框中输入所要猜的数字,点击"Guess"检验所猜的数字是否正确。
代码语言:javascript复制def check_num():
guess=text_guess.get()
guess=int(guess)
if guess>number:
tkinter.messagebox.showinfo("height","Your guess is too height.")
if guess < number:
tkinter.messagebox.showinfo("low","Your guess is too low.")
if guess == number:
tkinter.messagebox.showinfo("good","Good job!")
依据判断会有三种不同结果,如上图所示。
完整代码:
代码语言:javascript复制#!/usr/bin/env python3
import tkinter
import math
import tkinter.messagebox
import random
root =tkinter.Tk()
root.minsize(350,260)
root.title('猜数字游戏')
number=random.randint(1,20)
def say_hello():
print('hello,world!')
def send_low():
tkinter.messagebox.showinfo("messagebox","Your guess is too low.")
def check_num():
guess=text_guess.get()
guess=int(guess)
if guess>number:
tkinter.messagebox.showinfo("height","Your guess is too height.")
if guess < number:
tkinter.messagebox.showinfo("low","Your guess is too low.")
if guess == number:
tkinter.messagebox.showinfo("good","Good job!")
def btn_confirm():
myName=text_name.get()
tkinter.messagebox.showinfo("name",'Well,' myName ',I am thinking of a number between 1 and 20.')
#name
label=tkinter.Label(root,text="Wellcome to our game!")
label.pack()
label_name=tkinter.Label(root,text="What's your name?")
label_name.place(x=10,y=60)
text_name=tkinter.Entry(root,width=20)
text_name.place(x=10,y=90)
btnOK=tkinter.Button(root,text="OK",command=btn_confirm)
btnOK.place(x=200,y=90,height=28)
#input
label_guess=tkinter.Label(root,text='Take a guess:')
label_guess.place(x=10,y=150)
text_guess=tkinter.Entry(root,width=10)
text_guess.place(x=90,y=150)
btnCheck=tkinter.Button(root,text='Guess',command=check_num)
btnCheck.place(x=200,y=150,width=45,height=28)
root.mainloop()
一些常用的tkinter模块参数见这里:https://www.cnblogs.com/aland-1415/p/6849193.html