Python 入門指南 5.0
exercise3503.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 78 79 80 81 82 83 84 85 86 87 88 89 | # 從標準程式庫引入 Tk from tkinter import * # 從 tkinter 引入 font from tkinter import font # 從 tkinter 引入 ttk from tkinter import ttk # 從 exercise2705 引入 Guess from exercise2705 import Guess # 練習用的視窗類別 class GuessGUI(ttk.Frame): def __init__(self, master): ttk.Frame.__init__(self, master) self.winfo_toplevel().title("猜數字遊戲") self.root = master self.grid() self.label_font = font.Font(master, font="SF 48") self.createWidgets() self.style = ttk.Style() self.style.theme_use("alt") self.guess = Guess(4) self.count = 0 def createWidgets(self): self.entry = Entry(self) self.entry["width"] = 20 self.entry["font"] = self.label_font self.entry.grid(row=0, column=0, columnspan=2, sticky=N+W) self.button1 = Button(self) self.button1["text"] = "猜測" self.button1["font"] = self.label_font self.button1["width"] = 9 self.button1["height"] = 1 self.button1["command"] = self.run_game self.button1.grid(row=1, column=0, sticky=N) self.button2 = Button(self) self.button2["text"] = "重新" self.button2["font"] = self.label_font self.button2["width"] = 9 self.button2["height"] = 1 self.button2["command"] = self.reset self.button2.grid(row=1, column=1, sticky=N) self.result = Label(self) self.result["text"] = "" self.result["width"] = 20 self.result["bg"] = "white" self.result["fg"] = "black" self.result["font"] = self.label_font self.result.grid(row=2, column=0, columnspan=2, sticky=N+W) def run_game(self): user_input = self.entry.get() self.count += 1 if len(user_input) == 4: if self.guess.repeat_test(user_input): result = self.guess.find_AB(user_input) if result == "4A": self.result["text"] = f"恭喜猜對,一共猜了 {self.count} 次" else: self.result["text"] = result else: self.result["text"] = "數字重複" else: self.result["text"] = "輸入長度不符" self.entry.delete(0, 200) def reset(self): self.guess = Guess(4) self.count = 0 self.entry.delete(0, 200) self.result["text"] = "" # 執行部分 if __name__ == '__main__': # 建立 Tk 應用物件 root = Tk() # 建立視窗物件 app = GuessGUI(master=root) # 呼叫維持視窗運作的 mainloop() root.mainloop() # 檔名: exercise3503.py # 說明:《Python入門指南》的練習 # 網站: http://kaiching.org # 作者: 張凱慶 # 時間: 2023 年 11 月 |