python编写猜数字小游戏程序
作者:互联网
import tkinter as tk
import tkinter.messagebox
import random
import re
game = tk.Tk()
game.geometry('400x200')
game.title('猜数字小游戏')
a = random.randint(1, 100)
label1 = tk.Label(game, fg ='Teal',text="系统随机生成1到100之间的一个数,请你猜出这个数",
wraplength=250,justify='center',font = ('楷体',10))
label1.grid(row=0,padx=20, pady=8,columnspan=2,rowspan=2)
label2 = tk.Label(game, text='请输入你猜测的数字:',bg='LightSeaGreen',font = ('楷体',10))
label2.grid(row=2,column=0,sticky='w',padx=5)
text = tk.Entry(game, width=20)
text.grid(row=2,column=1,sticky='w')
def hs():
gn = text.get()
if gn =='' :
tk.messagebox.showwarning("警告", "输入不能为空")
else:
if not re.findall('[0-9]+',str(gn)):
tk.messagebox.showwarning("警告", "只能输入数字")
else:
gn = int(float(gn))
if gn not in range(1,100):
tkinter.messagebox.showerror("错误", "你猜的数字超出范围!")
else:
gn = int(float(gn))
if gn > a:
tkinter.messagebox.showerror("错误", "你猜的数字太大!")
if gn < a:
tkinter.messagebox.showerror("错误", "你猜的数字太小!")
if gn == a:
tkinter.messagebox.showinfo("正确", "恭喜你,猜对了!")
def hy():
tkinter.messagebox.showinfo("答案", "答案为:%d"%a)
button2 = tkinter.Button(game, text='确定', command=hs,width=10,bg='SkyBlue',font = ('楷体',10))
button2.grid(row=4,column=0,sticky='s',padx=5, pady=5)
button4 = tkinter.Button(game, text='答案', command=hy,width=10,bg='SkyBlue',font = ('楷体',10))
button4.grid(row=4,column=1,sticky='s',padx=5, pady=5)
button3 = tkinter.Button(game, text='退出', command=quit,width=10,bg='SkyBlue',font = ('楷体',10))
button3.grid(row=4,column=2,sticky='s',padx=5, pady=5)
game.mainloop()
标签:10,messagebox,tkinter,python,text,game,小游戏,gn,编写 来源: https://blog.csdn.net/genuineZ2/article/details/111321611