前言
游戏叫做猜数字,每输入一个数字,系统会给你反馈这数字是太小还是太大,然后根据反馈再次输入数字,直到回答正确为止。其中涉及到几个关键点:目标数字不能是固定的,必须每次游戏开始随机生成一个数字。我们可以用random()来实现,这个函数就是随机生成一个数。我们的游戏需要生成1到100之间,而且是整数。
基本开发环境
pycharm
Python 3.8
主要相关模块tkinter(Python内置库,直接导入即可)
实现需求
1、程序随机生成一个100以内(含100)的正整数。
2、将用户输入的答案与随机生成的整数进行比较,给出提示“猜大了”、“猜小了”或者“猜对了”。
3、用户可重复输入,直到猜对为止。
4、猜数功能实现后对代码进行封装tkinter(GUI界面美化设置)。
运行结果
以下是全部代码
# @Author : 王同学
import random
import tkinter as tk
def action():
# 用户输入
user = int(var.get())
# 随机生成
windoms = random.randint(1, 101)
if user == windoms:
print('恭喜你猜对数字了','本次数字是',windoms)
text.insert(tk.INSERT,f'猜数结果========》:恭喜你猜对数字了{windoms}' + '\n')
text.yview_moveto(1)
text.update()
elif user > windoms:
print('你猜的数字大了,往小点猜。')
text.insert(tk.INSERT,'猜数结果========》:你猜的数字大了,往小点猜。'+ '\n')
text.yview_moveto(1)
text.update()
elif user < windoms:
print('你猜的数字小了了,往大点猜。')
text.insert(tk.INSERT,'猜数结果========》:你猜的数字小了,往大点猜。'+ '\n')
text.yview_moveto(1)
text.update()
# 清空文本
def exit_games():
text.delete(1.0,tk.END)
if __name__ == '__main__':
root = tk.Tk()
# 窗口设置标题
root.title('猜数字小游戏')
# 窗口大小
root.geometry('600x600+700+200')
# 输入框
var = tk.StringVar()
entry = tk.Entry(root,textvariable=var,font=('微软雅黑',20),bg='light cyan')
entry.place(x=260,y=200,height=70,width=330)
# lable
tk.Label(root,text='猜数字游戏',font=('微软雅黑',30)).place(x=200,y=0)
# lable
labee = tk.Label(root,text='请输入你要猜的数字:',font=('微软雅黑',20))
labee.place(x=0,y=210)
# 文本框
text = tk.Text(root,width=85,fg='DeepPink',bg='light cyan')
text.place(x=0,y=280)
# Button
tk.Button(root,text='开始猜数字',height=4,width=20,bg='pink',command=action).place(x=240,y=100)
# 退出
tk.Button(root,text='退出程序',height=4,width=20,bg='pink',command=root.quit).place(x=50,y=100)
# 清空文本
tk.Button(root,text='清空文本',height=4,width=20,bg='pink',command=exit_games).place(x=420,y=100)
# 窗口生成
root.mainloop()