当前位置:网站首页>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 .
 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here
 Insert picture description here

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 》

原网站

版权声明
本文为[Keep_ Trying_ Go]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020518291815.html