from tkinter import *
import random
def check(content):
return content.isdigit()
def regulation(event=None):
root = Tk(className="规则")
test = "规则:输入一个1~1000的数字,如果用户输入的数字和计算机从1~1000之内的随机数相符,并且尝试次数要小于20次,则游戏胜利,否则游戏失败。"
Message(root, text=test, font=("微软雅黑", 12)).pack(padx=5, pady=5)
def exit(event=None):
root.destroy()
def num_guess():
if degree <= 5 :
l.config(text="5次以内就答对了!你的运气很高!")
elif degree <= 10:
l.config(text="10次以内就答对了,你的运气较高!")
elif degree <= 15:
l.config(text="15次以内就答对了,你的运气中等!")
elif degree <=20:
l.config(text="20次以内能答对,你的运气较低!")
else:
l.config(text="尝试次数超过20次,游戏结束!")
def yes(event=None):
global degree
error = False
try_number = var2.get()
if int(try_number) == number:
num_guess()
else:
if try_number == "":
l.config(text="提示:输入错误!", font=("微软雅黑", 12))
error = True
elif 0 > int(try_number) or int(try_number) > 1000:
l.config(text="提示:输入的数字必须介于1~1000!", font=("微软雅黑", 10))
guess.delete(0, END)
error = True
elif int(try_number) < number:
l.config(text="提示:您输入的数字小了!", font=("微软雅黑", 12))
var2.set("")
else:
l.config(text="提示:您输入的数字大了!", font=("微软雅黑", 12))
var2.set("")
if not error:
degree += 1
var.set("尝试次数:"+ str(degree))
def play():
global root
global var2
global number
global l
global degree
global var
global test
global guess
root = Tk(className="猜数字游戏")
test = root.register(check)
l = Label(root, text="", font=("微软雅黑", 10))
l.grid(row=1, column=0, sticky=W)
l.config(text="提示:请输入数字", font=("微软雅黑", 12))
number = random.randint(1, 1000)
degree = 0
var = StringVar()
var.set("尝试次数:"+str(degree))
Label(root, text="请输入一个1~1000之内的数字:", font=("微软雅黑", 11)).grid(row=0)
var2 = StringVar()
guess = Entry(root, textvariable=var2, width=20, validate="key", validatecommand=(test, "%P"))
guess.grid(row=0, column=1)
Label(root, textvariable=var, font=("微软雅黑", 11)).grid(row=1, column=1, sticky=E)
Button(root, text="确定", width=10, command=yes).grid(row=2, column=0, sticky=W, columnspan=2)
Button(root, text="规则", width=10, command=regulation).grid(row=2, column=1, columnspan=2)
Button(root, text="退出", width=10, command=exit).grid(row=2, column=3, sticky=E, columnspan=2)
guess.bind("<KeyPress-Return>", yes)
guess.focus_set()
if __name__ == "__main__":
play()
大家也帮我看看......