From 5368c5023fa4536a0ebfc25e1a131e66adb8f1c5 Mon Sep 17 00:00:00 2001 From: waldek Date: Mon, 2 May 2022 16:49:16 +0200 Subject: [PATCH] adds replay to guess the number gui --- learning_python3_gui.md | 76 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) diff --git a/learning_python3_gui.md b/learning_python3_gui.md index 3b295d8..42bf06b 100644 --- a/learning_python3_gui.md +++ b/learning_python3_gui.md @@ -326,6 +326,82 @@ if __name__ == "__main__": ``` +
+With replay function + +```python +import tkinter as tk +import random + + +class Application(tk.Tk): + def __init__(self): + tk.Tk.__init__(self) + self.title("hello world") + self.geometry("500x400") + self.resizable(0, 0) + + self.header = tk.Label(text="I have a number in mind...") + self.header.grid(column=0, row=0, sticky=tk.W) + + self.question = tk.Label(self, text="What's your guess?") + self.question.grid(column=0, row=1, sticky=tk.W) + + self.input = tk.Entry(self) + self.input.grid(column=1, row=1, sticky=tk.W) + + self.button = tk.Button(self, text="check", command=self.clicked) + self.button.grid(column=0, row=2, sticky=tk.W) + + self.output = tk.Label(self, text="...") + self.output.grid(column=1, row=2, sticky=tk.W) + + self.init_new_game() + + def _is_entry_digit(self): + number = self.input.get() + if number.isdigit(): + number = int(number) + return number + + def compare_numbers(self): + number = self._is_entry_digit() + if not number: + msg = "numbers please..." + else: + if number < self.number: + msg = "my number is bigger" + elif number > self.number: + msg = "my number is smaller" + elif number == self.number: + msg = "bingo!" + self.won = True + self.button.config(text="play again!") + self.output.config(text=msg) + + def init_new_game(self): + self.won = False + self.number = random.randint(0, 100) + print(self.number) + self.button.config(text="check") + self.output.config(text="") + self.input.delete(0, 'end') + + def clicked(self): + if self.won: + self.init_new_game() + else: + self.compare_numbers() + + +if __name__ == "__main__": + app = Application() + app.mainloop() + +``` + + + ## MVC design pattern A simple console only MVC.