使用tkinter 实现一个猜数字游戏
实现效果如下
先导入我们要实现的模块名
import time
import tkinter as tk
import tkinter.font as tkFont
import randomLOG_LINE_NUM = 0
后面我们开始编写实现的类
类名,定位为APP类
类方法里面变量初始化,我们后面要用到的变量
def __init__(self, root):self.initUI(root)self.initGame()self.initData()def initGame(self):self.module = True # 升级模式 True 积分模式 False猜准即升级self.bonus = 10 # 游戏积分,初始为10self.coins = 10 # 猜数字次数,初始为10self.level = 1 # 游戏级别,初始为1self.buycoins_temp = 0 # 额外猜数次数,初始为0,未消耗永久有效self.buycoins_forever = 0 # 额外永久猜数次数,初始为0,永久有效self.status_coinsforever = True # 额外永久猜数次数是否使用过self.status_leveup = False # 升级状态self.burynumber = 0self.helpnumber = [1, 50, 100] # 助猜数字self.status_helpnumber = Falseself.status_hint = Trueself.hintmin = 1self.hintmax = 100self.setDataLabel()self.GButton_submit['state'] = 'disabled'self.GButton_hint['state'] = 'disabled'self.GButton_buycoins_temp['state'] = 'disabled'self.GButton_buycoins_forever['state'] = 'disabled'self.GLineEdit_buycoins_forever['fg'] = "green"self.GLineEdit_buycoins_temp['fg'] = "green"global LOG_LINE_NUMLOG_LINE_NUM = 0self.GLineEdit_log.delete(1.0, 'end')
定义一个函数编写界面的标签
def setDataLabel(self):self.set_bonus_lable(self.GLineEdit_bonus, self.bonus)self.set_bonus_lable(self.GLineEdit_level, self.level)self.set_bonus_lable(self.GLineEdit_coins, self.coins)self.set_bonus_lable(self.GLineEdit_buycoins_forever, self.buycoins_forever)self.set_bonus_lable(self.GLineEdit_buycoins_temp, self.buycoins_temp)if self.status_hint:self.GLabel_numrange['text'] = f'1-{self.level * 100}'else:self.GLabel_numrange['text'] = f'{self.hintmin}-{self.hintmax}'if self.status_helpnumber:self.GLabel_helpnum['text'] = f'健康游戏忠告{self.helpnumber[1]}'else:self.GLabel_helpnum['text'] = f'健康游戏忠告'self.GLabel_burynumber['text'] = f"抵制不良游戏,拒绝盗版游戏。\n注意自我保护,谨防受骗上当。\n" \f"适度游戏益脑,沉迷游戏伤身。\n合理安排时间,享受健康生活。"
初始化界面的编写
def initUI(self, root):# setting titleroot.title("猜数字游戏 dltest@52pojie")# setting window sizewidth = 600height = 500screenwidth = root.winfo_screenwidth()screenheight = root.winfo_screenheight()alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)root.geometry(alignstr)root.resizable(width=False, height=False)ft_entry = tkFont.Font(family='Times', size=12)GLabel_770 = tk.Label(root, text="级别")GLabel_770.place(x=30, y=10, width=32, height=30)GLabel_975 = tk.Label(root, text="积分")GLabel_975.place(x=190, y=10, width=44, height=31)GLabel_917 = tk.Label(root, text="额外次数")GLabel_917.place(x=350, y=10, width=73, height=30)GLabel_30 = tk.Label(root, text="临时次数")GLabel_30.place(x=350, y=50, width=73, height=34)GLabel_37 = tk.Label(root, text="剩余猜测")GLabel_37.place(x=360, y=90, width=55, height=30)self.GButton_buycoins_forever = tk.Button(root, text="10分买一次")self.GButton_buycoins_forever.place(x=510, y=10, width=71, height=30)self.GButton_buycoins_forever["command"] = self.GButton_buycoins_forever_commandself.GButton_buycoins_temp = tk.Button(root, text="2分买一次")self.GButton_buycoins_temp.place(x=510, y=50, width=71, height=30)self.GButton_buycoins_temp["command"] = self.GButton_buycoins_temp_commandself.GLabel_result = tk.Label(root, text="猜测结果")self.GLabel_result.place(x=110, y=50, width=205, height=72)self.GLineEdit_log = tk.Text(root) # "记录"self.GLineEdit_log.place(x=10, y=130, width=408, height=360)self.GLineEdit_numinput = tk.Entry(root, text="输入框", justify="center", font=ft_entry, validate='key',validatecommand=(root.register(self.checkInput), '%P'))self.GLineEdit_numinput.place(x=460, y=240, width=98, height=34)self.GButton_submit = tk.Button(root, text="提交")self.GButton_submit["command"] = self.GButton_submit_commandself.GButton_submit.place(x=460, y=280, width=99, height=30)self.GLabel_helpnum = tk.Label(root, text="健康游戏忠告")self.GLabel_helpnum.bind('<Button-1>', self.changeHelpStatus)self.GLabel_helpnum.place(x=430, y=370, width=160, height=30)self.GLabel_burynumber = tk.Label(root, text="抵制不良游戏,拒绝盗版游戏。\n注意自我保护,谨防受骗上当。\n""适度游戏益脑,沉迷游戏伤身。\n合理安排时间,享受健康生活。")ft = tkFont.Font(family='宋体', size=8)self.GLabel_burynumber["font"] = ftself.GLabel_burynumber["fg"] = "#5fb878"self.GLabel_burynumber.bind('<Button-1>', self.GLabel_getburynumber)self.GLabel_burynumber.place(x=430, y=400, width=171, height=75)self.GButton_star = tk.Button(root, text="开始游戏")self.GButton_star.place(x=510, y=90, width=72, height=30)self.GButton_star["command"] = self.GButton_star_commandGLabel_512 = tk.Label(root, text="本次数字区间")GLabel_512.place(x=450, y=170, width=120, height=30)self.GLabel_numrange = tk.Label(root, text="1-100") # "1-100"self.GLabel_numrange.place(x=450, y=200, width=122, height=30)self.GLineEdit_level = tk.Entry(root, state='readonly', justify="center", font=ft_entry) # "级别"self.GLineEdit_level.place(x=70, y=10, width=90, height=30)self.GLineEdit_bonus = tk.Entry(root, justify="center", font=ft_entry) # "积分"self.GLineEdit_bonus.place(x=240, y=10, width=81, height=30)self.GLineEdit_buycoins_forever = tk.Entry(root, justify="center", font=ft_entry) # 额外self.GLineEdit_buycoins_forever.place(x=420, y=10, width=72, height=30)self.GLineEdit_buycoins_temp = tk.Entry(root, justify="center", font=ft_entry) # 临时self.GLineEdit_buycoins_temp.place(x=420, y=50, width=72, height=30)self.GLineEdit_coins = tk.Entry(root, justify="center", font=ft_entry) # 剩余self.GLineEdit_coins.place(x=420, y=90, width=72, height=30)self.GButton_reset = tk.Button(root, text="重玩")self.GButton_reset.place(x=30, y=70, width=61, height=30)self.GButton_reset["command"] = self.GButton_reset_commandself.GButton_hint = tk.Button(root, text="5积分缩小范围1次")self.GButton_hint.place(x=430, y=130, width=149, height=30)self.GButton_hint["command"] = self.GButton_hint_command
由于代码太多了
只贴上上面的代码
下面是完整代码
# -*- coding:utf-8 -*-
# @FileName :myguestnumberUI.py
# @Time :2022/7/23 12:03
# @AuThor :dltest@52pojie
import time
import tkinter as tk
import tkinter.font as tkFont
import randomLOG_LINE_NUM = 0class App:def __init__(self, root):self.initUI(root)self.initGame()self.initData()def initGame(self):self.module = True # 升级模式 True 积分模式 False猜准即升级self.bonus = 10 # 游戏积分,初始为10self.coins = 10 # 猜数字次数,初始为10self.level = 1 # 游戏级别,初始为1self.buycoins_temp = 0 # 额外猜数次数,初始为0,未消耗永久有效self.buycoins_forever = 0 # 额外永久猜数次数,初始为0,永久有效self.status_coinsforever = True # 额外永久猜数次数是否使用过self.status_leveup = False # 升级状态self.burynumber = 0self.helpnumber = [1, 50, 100] # 助猜数字self.status_helpnumber = Falseself.status_hint = Trueself.hintmin = 1self.hintmax = 100self.setDataLabel()self.GButton_submit['state'] = 'disabled'self.GButton_hint['state'] = 'disabled'self.GButton_buycoins_temp['state'] = 'disabled'self.GButton_buycoins_forever['state'] = 'disabled'self.GLineEdit_buycoins_forever['fg'] = "green"self.GLineEdit_buycoins_temp['fg'] = "green"global LOG_LINE_NUMLOG_LINE_NUM = 0self.GLineEdit_log.delete(1.0, 'end')def setDataLabel(self):self.set_bonus_lable(self.GLineEdit_bonus, self.bonus)self.set_bonus_lable(self.GLineEdit_level, self.level)self.set_bonus_lable(self.GLineEdit_coins, self.coins)self.set_bonus_lable(self.GLineEdit_buycoins_forever, self.buycoins_forever)self.set_bonus_lable(self.GLineEdit_buycoins_temp, self.buycoins_temp)if self.status_hint:self.GLabel_numrange['text'] = f'1-{self.level * 100}'else:self.GLabel_numrange['text'] = f'{self.hintmin}-{self.hintmax}'if self.status_helpnumber:self.GLabel_helpnum['text'] = f'健康游戏忠告{self.helpnumber[1]}'else:self.GLabel_helpnum['text'] = f'健康游戏忠告'self.GLabel_burynumber['text'] = f"抵制不良游戏,拒绝盗版游戏。\n注意自我保护,谨防受骗上当。\n" \f"适度游戏益脑,沉迷游戏伤身。\n合理安排时间,享受健康生活。"def initUI(self, root):# setting titleroot.title("猜数字游戏 dltest@52pojie")# setting window sizewidth = 600height = 500screenwidth = root.winfo_screenwidth()screenheight = root.winfo_screenheight()alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)root.geometry(alignstr)root.resizable(width=False, height=False)ft_entry = tkFont.Font(family='Times', size=12)GLabel_770 = tk.Label(root, text="级别")GLabel_770.place(x=30, y=10, width=32, height=30)GLabel_975 = tk.Label(root, text="积分")GLabel_975.place(x=190, y=10, width=44, height=31)GLabel_917 = tk.Label(root, text="额外次数")GLabel_917.place(x=350, y=10, width=73, height=30)GLabel_30 = tk.Label(root, text="临时次数")GLabel_30.place(x=350, y=50, width=73, height=34)GLabel_37 = tk.Label(root, text="剩余猜测")GLabel_37.place(x=360, y=90, width=55, height=30)self.GButton_buycoins_forever = tk.Button(root, text="10分买一次")self.GButton_buycoins_forever.place(x=510, y=10, width=71, height=30)self.GButton_buycoins_forever["command"] = self.GButton_buycoins_forever_commandself.GButton_buycoins_temp = tk.Button(root, text="2分买一次")self.GButton_buycoins_temp.place(x=510, y=50, width=71, height=30)self.GButton_buycoins_temp["command"] = self.GButton_buycoins_temp_commandself.GLabel_result = tk.Label(root, text="猜测结果")self.GLabel_result.place(x=110, y=50, width=205, height=72)self.GLineEdit_log = tk.Text(root) # "记录"self.GLineEdit_log.place(x=10, y=130, width=408, height=360)self.GLineEdit_numinput = tk.Entry(root, text="输入框", justify="center", font=ft_entry, validate='key',validatecommand=(root.register(self.checkInput), '%P'))self.GLineEdit_numinput.place(x=460, y=240, width=98, height=34)self.GButton_submit = tk.Button(root, text="提交")self.GButton_submit["command"] = self.GButton_submit_commandself.GButton_submit.place(x=460, y=280, width=99, height=30)self.GLabel_helpnum = tk.Label(root, text="健康游戏忠告")self.GLabel_helpnum.bind('<Button-1>', self.changeHelpStatus)self.GLabel_helpnum.place(x=430, y=370, width=160, height=30)self.GLabel_burynumber = tk.Label(root, text="抵制不良游戏,拒绝盗版游戏。\n注意自我保护,谨防受骗上当。\n""适度游戏益脑,沉迷游戏伤身。\n合理安排时间,享受健康生活。")ft = tkFont.Font(family='宋体', size=8)self.GLabel_burynumber["font"] = ftself.GLabel_burynumber["fg"] = "#5fb878"self.GLabel_burynumber.bind('<Button-1>', self.GLabel_getburynumber)self.GLabel_burynumber.place(x=430, y=400, width=171, height=75)self.GButton_star = tk.Button(root, text="开始游戏")self.GButton_star.place(x=510, y=90, width=72, height=30)self.GButton_star["command"] = self.GButton_star_commandGLabel_512 = tk.Label(root, text="本次数字区间")GLabel_512.place(x=450, y=170, width=120, height=30)self.GLabel_numrange = tk.Label(root, text="1-100") # "1-100"self.GLabel_numrange.place(x=450, y=200, width=122, height=30)self.GLineEdit_level = tk.Entry(root, state='readonly', justify="center", font=ft_entry) # "级别"self.GLineEdit_level.place(x=70, y=10, width=90, height=30)self.GLineEdit_bonus = tk.Entry(root, justify="center", font=ft_entry) # "积分"self.GLineEdit_bonus.place(x=240, y=10, width=81, height=30)self.GLineEdit_buycoins_forever = tk.Entry(root, justify="center", font=ft_entry) # 额外self.GLineEdit_buycoins_forever.place(x=420, y=10, width=72, height=30)self.GLineEdit_buycoins_temp = tk.Entry(root, justify="center", font=ft_entry) # 临时self.GLineEdit_buycoins_temp.place(x=420, y=50, width=72, height=30)self.GLineEdit_coins = tk.Entry(root, justify="center", font=ft_entry) # 剩余self.GLineEdit_coins.place(x=420, y=90, width=72, height=30)self.GButton_reset = tk.Button(root, text="重玩")self.GButton_reset.place(x=30, y=70, width=61, height=30)self.GButton_reset["command"] = self.GButton_reset_commandself.GButton_hint = tk.Button(root, text="5积分缩小范围1次")self.GButton_hint.place(x=430, y=130, width=149, height=30)self.GButton_hint["command"] = self.GButton_hint_commanddef initData(self):passdef GButton_buycoins_forever_command(self):if self.bonus >= 20 and self.buycoins_forever < 10:self.bonus -= 10self.buycoins_forever += 1self.write_log_to_Text(f'购买成功,已为您增加永久次数:1')if self.status_coinsforever:self.write_log_to_Text(f'本局可以使用购买得永久次数。')else:self.write_log_to_Text(f'永久次数已部份使用,下局可用新购次数。')else:if self.bonus < 20:self.write_log_to_Text(f'购买失败!请预留至少10点游戏积分!您目前游戏积分:{self.bonus}')elif self.buycoins_forever >= 10:self.write_log_to_Text(f'购买失败!额外猜数次数存储上限为10次!')self.setDataLabel()def GButton_buycoins_temp_command(self):if self.bonus >= 12:self.bonus -= 2self.buycoins_temp += 1self.write_log_to_Text(f'购买成功,已为您增加临时次数:1')else:self.write_log_to_Text(f'购买失败!请预留至少10点游戏积分!您目前游戏积分:{self.bonus}')self.setDataLabel()def changeHelpStatus(self, event):self.status_helpnumber = not self.status_helpnumberself.setDataLabel()def GLabel_getburynumber(self, event):self.GLabel_burynumber['text'] = self.burynumberdef GButton_submit_command(self):if self.bonus <= 0:self.write_log_to_Text(f'您的游戏积分为0,GAME OVER!重玩请点击按钮【重玩】')# self.write_log_to_Text('很遗憾!您没有猜对数字!埋藏的数字为:{input:3}')returninput = self.GLineEdit_numinput.get()self.GLineEdit_numinput.delete(0, 'end')x = 0if input:try:x = int(input)except:self.write_log_to_Text(f'请输入整数')returnelse:self.write_log_to_Text(f'未输入数字')returnif x > self.burynumber:self.GLabel_result['fg'] = "#ff7800"ft = tkFont.Font(family='Times', size=12)self.GLabel_result["font"] = ftself.GLabel_result['text'] = "大了"self.write_log_to_Text(f'您猜的数[{input:>3}]太大了!扣除1点游戏积分,剩余游戏积分:{self.bonus - 1}')self.helpnumber[2] = xself.helpnumber[1] = int((self.helpnumber[0] + self.helpnumber[2]) / 2)elif x < self.burynumber:self.GLabel_result['text'] = "小了"self.write_log_to_Text(f'您猜的数[{input:>3}]太小了!扣除1点游戏积分,剩余游戏积分:{self.bonus - 1}')self.helpnumber[0] = xself.helpnumber[1] = int((self.helpnumber[0] + self.helpnumber[2]) / 2)else:self.status_leveup = Trueprint("神啦!您居然猜对了")self.GLabel_result['text'] = "猜对了"self.write_log_to_Text(f'神啦!您居然猜对了!埋藏的数确实是[{input:>3}]。')self.write_log_to_Text(f'奖励10点游戏积分,剩余游戏积分:{self.bonus + 10}')self.setGameStaus()def setGameStaus(self):self.bonus -= 1if self.status_leveup:self.bonus += 11self.coins = 10self.GLineEdit_buycoins_forever['fg'] = "green"else:self.coins -= 1if self.coins == 0 and self.bonus > 0 and not self.status_leveup:if self.status_coinsforever and self.buycoins_forever > 0:self.status_coinsforever = Falseself.GLineEdit_buycoins_forever['fg'] = "red"self.coins += self.buycoins_foreverself.write_log_to_Text(f'使用道具“主角光环”成功!额外增加[{self.buycoins_forever}]次猜测,请继续加油!')elif self.buycoins_temp > 0:self.coins += 1self.buycoins_temp -= 1self.write_log_to_Text(f'幸运加持!额外增加[{1}]次猜测,请继续加油!')else:self.write_log_to_Text(f'很遗憾!您没有猜对数字!埋藏的数字为:{self.burynumber:>3}')self.write_log_to_Text(f'您的猜测次数为0,GAME OVER!重玩请点击按钮【重玩】')self.GameOver()self.uplevel()if self.status_leveup:self.GButton_star_command()self.setDataLabel() # 刷新显示def GButton_hint_command(self):if self.bonus > 5:self.status_hint = Falseself.bonus -= 5min = random.randint(1, 25)max = random.randint(1, 25)hintmin = 1if self.burynumber - self.hintmin > min:hintmin = self.burynumber - minelse:hintmin = self.burynumber - random.randint(1, (self.burynumber - self.hintmin))hintmax = self.level * 100if self.hintmax - self.burynumber > max:hintmax = self.burynumber + maxelse:hintmax = self.burynumber + random.randint(1, (self.hintmax - self.burynumber))if hintmin < 0:hintmin = random.randint(1, self.burynumber)if hintmax > self.level * 100:hintmax = random.randint(self.burynumber, self.level * 100)self.hintmin = hintminself.hintmax = hintmaxself.write_log_to_Text(f'-----------消耗5点游戏积分获取埋藏数字区间提示 ------')self.write_log_to_Text(f'埋藏的数字在「{self.hintmin}~{self.hintmax}」之间,剩余游戏积分:{self.bonus}')else:self.write_log_to_Text(f'购买失败!请预留至少5点游戏积分!您目前游戏积分:{self.bonus}')self.setDataLabel()def GButton_star_command(self):self.burynumber = self.BuryNumber(self.level)self.GButton_star['state'] = 'disabled'self.GButton_submit['state'] = 'active'self.GButton_hint['state'] = 'active'self.GButton_buycoins_temp['state'] = 'active'self.GButton_buycoins_forever['state'] = 'active'self.status_hint = Trueself.status_leveup = Falseself.status_coinsforever = Trueprint(self.level)self.helpnumber[2] = self.level * 100self.helpnumber[0] = 1self.helpnumber[1] = int((self.helpnumber[0] + self.helpnumber[2]) / 2)print(self.helpnumber)def GButton_reset_command(self):self.bonus = 10self.level = 1self.set_bonus_lable(self.GLineEdit_bonus, self.bonus)self.set_bonus_lable(self.GLineEdit_level, self.level)self.GButton_star['state'] = 'active'self.initGame()self.setDataLabel()# 根据游戏级别埋藏数字def BuryNumber(self, level):return random.randint(1, level * 100)def checkInput(self, char):if (char.isdigit() or char == ""):return Trueelse:return Falsedef write_log_to_Text(self, logmsg):global LOG_LINE_NUMlogmsg_in = str(logmsg) + "\n" # 换行if LOG_LINE_NUM <= 24:self.GLineEdit_log.insert('end', logmsg_in)LOG_LINE_NUM = LOG_LINE_NUM + 1else:self.GLineEdit_log.delete(1.0, 2.0)self.GLineEdit_log.insert('end', logmsg_in)def set_bonus_lable(self, _Edit, value):_Edit.config(state='normal')_Edit.delete(0, 'end')_Edit.insert(0, f"{value}")_Edit.config(state='readonly')def GameOver(self):self.GButton_submit['state'] = 'disabled'# 根据游戏积分提升游戏级别def uplevel(self):level = self.levelif self.status_leveup and not self.module:level += 1else:level = self.bonus // 10 + 1if level > self.level:self.level = levelself.write_log_to_Text(f'-----------游戏难度升级至:{self.level} ------')if __name__ == "__main__":root = tk.Tk()app = App(root)root.mainloop()
上面代码还有部分没有完善功能,
完整功能代码打包成exe上次到我的资源
可以去这个链接下载
https://download.csdn.net/download/Deng872347348/86336872