猜数字游戏(Tkinter)
Posted wfsh-hebau
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了猜数字游戏(Tkinter)相关的知识,希望对你有一定的参考价值。
通过做一个猜数字的小游戏来学习tkinter模块,3次机会
功能:
1. 界面
2. 运行结果
知识点:
1. tkinter中的Lable,Entry,Button, Text组件
2. from tkinter import messagebox
程序代码:
‘‘‘ GussNumberGame ‘‘‘ import tkinter as tk import tkinter.messagebox #s1: creat window GussNum = tk.Tk() GussNum.minsize(400,300) GussNum.title(‘MyGameGussNumber‘) #s2: creat components and #s3: distribute components lableShow = tk.Label(GussNum,text=‘Wellcome to our game! please input yourNumber‘,height =2) lableShow.place(x=50,y=10) entryIn = tk.Entry(GussNum) entryIn.place(x=50,y=70) cmdGuss = tk.Button(GussNum,text=‘Guess‘) cmdGuss.place(x=230,y=70) txtOut = tk.Text(GussNum) txtOut.place(x=10,y=100) #s4:events from random import randint targetNum = randint(1,11) count = 0 flagOver = False def checkNum(): global targetNum global count global flagOver yourNum = eval(entryIn.get()) txt = ‘‘ txt1 = ‘‘ if yourNum == targetNum: flagOver = True txt = "Congratulations! good job!" tk.messagebox.showinfo(‘Good‘,txt) elif yourNum < targetNum: txt = ‘too low!‘ txt1 = ‘You Can try‘+ str(2-count)+‘times‘ tk.messagebox.showinfo("low",txt) else: txt = ‘too height!‘ txt1 = ‘You Can try‘+ str(2-count)+‘times‘ tk.messagebox.showinfo("height",txt) txtOut.insert(tk.END,"yourNum is "+str(yourNum)+‘ ‘+ txt+txt1+‘ ‘) count += 1 if count >=3: flagOver = True def guessClick(): global flagOver if not flagOver: checkNum() cmdGuss[‘command‘]=guessClick GussNum.mainloop()
后续问题:
1. 游戏结束后(flagOver==TRUE),再点击Guess按钮,应该有提示
2. 可以显示图片来对应相应的结果:哭脸,笑脸
4. 界面添加,猜数范围设定,和 猜测次数设定
5. 界面需美化
6. ....
以上是关于猜数字游戏(Tkinter)的主要内容,如果未能解决你的问题,请参考以下文章