当前位置:网站首页>Using Tkinter to realize guessing numbers game
Using Tkinter to realize guessing numbers game
2022-06-11 07:47:00 【Keep_ Trying_ Go】
About what is used in this article tkinter Component knowledge and procedures , And the background image source of the program , I have declared the source at the end of the article .






import random
import tkinter
import tkinter.messagebox
import tkinter.simpledialog
import numpy as np
class Guess_Game(object):
def __init__(self):
# Initialize the main window
self.root=tkinter.Tk()
# Set the window title
self.root.title(' Guess the number game ——Keep_Trying_Go')
# Set window size
self.root.geometry('480x180+400+300')
# Set the window to disallow resizing
self.root.resizable(False,False)
try:
# Create a canvas
self.canvas=tkinter.Canvas(self.root,height=400,width=700,borderwidth=2)
# Load picture file
self.image_file=tkinter.PhotoImage(file='Background.gif')
# Place the image on the canvas
self.image=self.canvas.create_image(0,0,anchor='nw',image=self.image_file)
# Place on the top of the canvas , That is, the of the main window “ In front of the ”
self.canvas.pack(side='top')
except:
print(' Unable to load the picture ')
# The number of times the user guessed
self.varNumber=tkinter.StringVar(self.root,value='0')
# The number of times the user is allowed to guess
self.totalTimes=tkinter.IntVar(self.root,value=0)
# The number of times the user has guessed
self.already=tkinter.IntVar(self.root,value=0)
# Record the currently generated random number
self.currentNumber=tkinter.IntVar(self.root,value=0)
# Record the total number of times players play the game
self.times=tkinter.IntVar(self.root,value=0)
# Record the total number of times players guessed right
self.right=tkinter.IntVar(self.root,value=0)
self.lb=tkinter.Label(self.root,text=' Please enter an integer : ')
self.lb.place(x=70,y=50,width=100,height=30)
# The user guesses the number of times and enters the text box
self.entryNumber=tkinter.Entry(self.root,textvariable=self.varNumber)
self.entryNumber.place(x=170,y=50,width=150,height=30)
# You are not allowed to enter numbers until the game starts
self.entryNumber['state']='disabled'
self.button=tkinter.Button(self.root,text='Start Game',command=self.buttonClick)
self.button.place(x=150,y=100,width=80,height=30)
# Button click the event handler
def closeWindows(self):
self.message=' Play games together {0} Time , Guess right {1} Time !\n Welcome to play again next time !'
self.message=self.message.format(self.times.get(),self.right.get())
tkinter.messagebox.showinfo(' record ',self.message)
def buttonClick(self):
if self.button['text']=='Start Game':
# Allow users to customize the range of values for each game
# The player must enter the correct number
while True:
try:
#simpledialog Module parameters :title Specify the title of the dialog ;prompt Displayed text ;initialvalue Specify the initial value of the input box ;
self.start=tkinter.simpledialog.askinteger(' The smallest integer allowed ',' Minimum number ',initialvalue=1)
break
except:
pass
while True:
try:
self.end=tkinter.simpledialog.askinteger(' Maximum integer allowed ',' The maximum number ',initialvalue=10)
break
except:
pass
# Generate random numbers within the range of user-defined values
self.currentNumber.set(random.randint(self.start,self.end))
# The total number of guesses allowed is customized by the user
# The player must enter the correct number
while True:
try:
self.t=tkinter.simpledialog.askinteger(' You are allowed to guess for several times at most ?',' The total number of times ',initialvalue=3)
self.totalTimes.set(self.t)
break
except:
pass
# The number of guesses initialized to 0
self.already.set(0)
self.button['text']=' Remaining times : '+str(self.t)
# Initialize the text box to 0
self.varNumber.set('0')
# Allow the user to start entering numbers
self.entryNumber['state']='normal'
# Add one to the number of games you play
self.times.set(self.times.get()+1)
else:
# The total number of times the user is allowed to guess
self.total=self.totalTimes.get()
# The correct answer to this game
self.current=self.currentNumber.get()
try:
self.x=int(self.varNumber.get())
except:
tkinter.messagebox.showerror(' I'm sorry ',' You must enter an integer ')
return
if self.x==self.current:
tkinter.messagebox.showinfo(' Congratulations ',' Guessed it ')
self.button['text']='Start Game'
# Disable textbox
self.entryNumber['state']='disabled'
self.right.set(self.right.get()+1)
else:
# Add one to the number of guesses
self.already.set(self.already.get()+1)
if self.x>self.current:
tkinter.messagebox.showerror(' I'm sorry ',' Guess too many times ')
else:
tkinter.messagebox.showerror(' I'm sorry ', ' The number of guesses is too small ')
# The number of guesses has run out
if self.already.get()==self.total:
tkinter.messagebox.showerror(' I'm sorry ',' The game is over , The correct number is : '+str(self.currentNumber.get()))
self.button['text']='Start Game'
# Disable textbox
self.entryNumber['state']='disabled'
else:
self.button['text']=' Remaining times : '+str(self.total-self.already.get())
def main():
g=Guess_Game()
# g.root.protocol('WM_DELETE_WINDOW', g.closeWindow())
tkinter.mainloop()
g.closeWindows()
if __name__ == '__main__':
main()
About tkinter You can refer to this blogger for component learning :
https://blog.csdn.net/mingshao104/article/details/79591965
The background image of the above program comes from the blogger :
https://blog.csdn.net/pymonster/article/details/113393829
The program comes from 《python Programming basics 》
边栏推荐
- [atcoder1980] mystious light (mathematical simulation)
- String Simulation Implementation
- [codeforces1019e] raining season
- Introduction to operations research
- 20200802 T3 I always like [generating function exclusion, Lagrangian inversion]
- 【AtCoder1983】BBQ Hard (组合数+巧妙模型转化)
- Sort - merge sort
- Three expressions of integers and their storage in memory
- Remote office experience sharing | community essay solicitation
- Modular linear equations (Chinese remainder theorem + general solution)
猜你喜欢

【IoT】智能硬件:如何获取硬件产品的wifi信号强度

Qunhui ds918 creates m.2 SSD read / write cache

QT picture adaptive display control

How to output the percent sign "%" in printf function in C language

C language - growth diary-04- preliminary exploration of local variables (local variables)

C language lesson 2

如何准备PMP新版大纲考试?

About static keyword

2021-11-05 definition of cache

C language to achieve three piece chess (not artificial mental retardation ha ha ha)
随机推荐
Miscellany C language
Rabin Miller prime test
[atcoder2306] rearranging (topology)
如何准备PMP新版大纲考试?
Ffmpeg extraction package format extracts AAC and customizes adtc header to realize arbitrary frame decoding
零基础自学SQL课程 | UNION 联合查询
Zero foundation self-study SQL course | outer join external connection
C wechat upload form data
C language - Growth Diary -03- function definition and function prototype declaration
Nim product
[atcoder2307] tree game
Simple configuration of vscade
Matrix tree theorem
20200802 T3 I always like [generating function exclusion, Lagrangian inversion]
【AtCoder2304】Cleaning
MFC custom string linked list
【IoT】智能硬件:如何获取硬件产品的wifi信号强度
Tidb cloud launched Google cloud marketplace, empowering global developers with a new stack of real-time HTAP databases
2022.6.6 特长生模拟
C language - Growth Diary -01- count primes and sum