小游戏
使用tkinter开发猜数字游戏
import tkinter as tk
import sys
import random
import re
number = random.randint(0,1024)#玩家要猜的数字
running = True
num = 0 #猜的次数
nmaxn = 1024 #提示猜测最大数范围
nminn = 0 #提示猜测最小数范围
def eBtnClose(event): #‘关闭’按钮事件函数
root.destry()
def eBtnGuess(event): #‘猜’按钮事件函数
global nmaxn#全局变量
global nminn
global num
global running
if running:
val_a = int(entry_a.get())
if val_a == number:
labelqval("恭喜你答对了")
num += 1
running = False
numGuess()
elif val_a <number:
if val_a >nminn:
nminn = val_a
num += 1
labelqval("小了哦,请重新输入" + str(nminn)
+"到" +str(nmaxn) +"之间任意整数:")
else:
if val_a < nmaxn:
nmaxn = val_a
num +=1
labelqval("大了哦,请重新输入" +str(nminn)
+"到" +str(nmaxn) +"之间任意整数:")
else:
labelqval('你答对了...')
#显示答的次数
def numGuess():
if num == 1:
labelqval('哇!一次就答对了!')
elif num <10:
labelqval('= = 十次内答对厉害...尝试次数:'+str(num))
else:
labelqval('好吧,有点难...尝试次数:'+str(num))
def labelqval(vText):
label_val_q.config(label_val_q ,text = vText)
root = tk.Tk(className = '猜数字游戏')
root.geometry("300x90+400+400")
label_val_q = tk.Label(root,width ="80")#提示标签
label_val_q.pack(side = "top")
entry_a = tk.Entry(root,width ="40")#单行输入框
btnGuess = tk.Button(root,text = "猜")#‘猜’按钮
entry_a.pack(side = "left")
entry_a.bind('<Return>',eBtnGuess)#绑定事件
btnGuess.bind('<Button - 1>',eBtnGuess)#'猜'按钮
btnGuess.pack(side = "left")
btnClose = tk.Button(root,text = "关闭")#’关闭‘按钮
btnClose.bind('<Button -1>',eBtnClose)
btnClose.pack(side = "left")
labelqval("请输入0 ~ 1024任意整数:")
entry_a.focus_set()
print(number)
root.mainloop()