forked from aliya-rahmani/Projects
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Gues_Number_upto100.py
77 lines (60 loc) · 2.53 KB
/
Gues_Number_upto100.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
import random
from tkinter import Tk, Label, Button, Entry, StringVar, DISABLED, NORMAL, END, W, E
class GuessingGame:
def __init__(self, master):
self.master = master
master.title("Guessing Game")
self.secret_number = random.randint(1, 100)
self.guess = None
self.num_guesses = 0
self.message = "Guess a number from 1 to 100"
self.label_text = StringVar()
self.label_text.set(self.message)
self.label = Label(master, textvariable=self.label_text)
vcmd = master.register(self.validate) # we have to wrap the command
self.entry = Entry(master, validate="key", validatecommand=(vcmd, '%P'))
self.guess_button = Button(master, text="Guess", command=self.guess_number)
self.reset_button = Button(master, text="Play again", command=self.reset, state=DISABLED)
self.label.grid(row=0, column=0, columnspan=2, sticky=W+E)
self.entry.grid(row=1, column=0, columnspan=2, sticky=W+E)
self.guess_button.grid(row=2, column=0)
self.reset_button.grid(row=2, column=1)
def validate(self, new_text):
if not new_text: # the field is being cleared
self.guess = None
return True
try:
guess = int(new_text)
if 1 <= guess <= 100:
self.guess = guess
return True
else:
return False
except ValueError:
return False
def guess_number(self):
self.num_guesses += 1
if self.guess is None:
self.message = "Guess a number from 1 to 100"
elif self.guess == self.secret_number:
suffix = '' if self.num_guesses == 1 else 'es'
self.message = "Congratulations! You guessed the number after %d guess%s." % (self.num_guesses, suffix)
self.guess_button.configure(state=DISABLED)
self.reset_button.configure(state=NORMAL)
elif self.guess < self.secret_number:
self.message = "Too low! Guess again!"
else:
self.message = "Too high! Guess again!"
self.label_text.set(self.message)
def reset(self):
self.entry.delete(0, END)
self.secret_number = random.randint(1, 100)
self.guess = 0
self.num_guesses = 0
self.message = "Guess a number from 1 to 100"
self.label_text.set(self.message)
self.guess_button.configure(state=NORMAL)
self.reset_button.configure(state=DISABLED)
root = Tk()
my_gui = GuessingGame(root)
root.mainloop()