number guessing game python gui
# guess the number in a GUI
from tkinter import *
import random
class Application(Frame):
''' GUI guess the number application '''
def __init__(self, master):
'''initialise frame'''
super(Application, self).__init__(master)
self.grid()
self.create_widgets()
def create_widgets(self):
'''create widgets for GUI guess game'''
#Create title label
Label(self, text = 'Guess the number'
).grid(row = 0, column = 1, columnspan = 2, sticky = N)
# create instruction labels
Label(self, text = 'I am thinking of a number between 1 and 100'
).grid(row = 1, column = 0, columnspan = 3, sticky = W)
Label(self, text = 'Try to guess in as few attempts as possible'
).grid(row = 2, column = 0, columnspan = 3, sticky = W)
Label(self, text = 'I will tell you to go higher or lower after each guess'
).grid(row = 3, column = 0, columnspan = 3, sticky = W)
# Create a label and number entry
Label(self, text = 'Your guess: '
).grid(row = 4, column = 0, sticky = W)
self.guess_ent = Entry(self)
self.guess_ent.grid(row = 4, column = 1, sticky = W)
# create label and text box for number of tries
Label(self, text = ' number of tries: '
).grid(row = 5, column = 0, sticky = W)
self.no_tries_txt = Text(self, width = 2, height = 1, wrap = NONE)
self.no_tries_txt.grid(row = 5, column = 1, sticky = W)
# create guess button
Button(self, text = 'Guess', command = self.check_if_correct
).grid(row = 5, column = 2, sticky = W)
self.result_txt = Text(self, width = 80, height = 15, wrap = WORD)
self.result_txt.grid(row = 6, column = 0, columnspan = 4)
# display the results
#self.result_txt.delete(0.0, END)
#self.result_txt.insert(0.0, display_result)
#self.no_tries_txt.delete(0.0, END)
#self.no_tries_txt.insert(0.0, the_number)
def rnumber(self):
self.rnumber = random.randint(1, 100)
def check_if_correct(self):
self.result = ""
gnum = self.guess_ent.get()
gnum = int(gnum)
if gnum == self.rnumber:
gnum = str(gnum)
self.result = gnum + " is the magic number!\n"
elif gnum < self.rnumber:
gnum = str(gnum)
self.result = gnum + " is too low.\n"
elif gnum > self.rnumber:
gnum = str(gnum)
self.result= gnum + " is too high.\n"
def giveResult(self):
return str(self.result)
# display the results
self.result_txt.delete(0.0, END)
self.result_txt.insert(0.0, result)
#self.no_tries_txt.delete(0.0, END)
#self.no_tries_txt.insert(0.0, the_number)
# main
root = Tk()
root.title('Guess the Number')
app = Application(root)
root.mainloop()