写一个gui的猜数字游戏
时间: 2023-09-20 14:10:25 浏览: 86
好的,以下是一个简单的GUI猜数字游戏,使用Python的Tkinter模块实现:
```python
import random
import tkinter as tk
class GuessNumberGame:
def __init__(self, master):
self.master = master
self.master.title("Guess Number Game")
self.master.geometry("300x200")
self.number = random.randint(1, 100)
self.attempts = 0
self.label = tk.Label(master, text="Guess a number between 1 and 100:")
self.label.pack()
self.guess_entry = tk.Entry(master)
self.guess_entry.pack()
self.guess_button = tk.Button(master, text="Guess", command=self.check_guess)
self.guess_button.pack()
self.reset_button = tk.Button(master, text="Reset", command=self.reset_game)
self.reset_button.pack()
self.result_label = tk.Label(master, text="")
self.result_label.pack()
def check_guess(self):
self.attempts += 1
guess = int(self.guess_entry.get())
if guess == self.number:
self.result_label.config(text=f"Congratulations! You guessed the number in {self.attempts} attempts.")
self.guess_button.config(state="disabled")
elif guess < self.number:
self.result_label.config(text="Try a higher number.")
else:
self.result_label.config(text="Try a lower number.")
self.guess_entry.delete(0, "end")
def reset_game(self):
self.number = random.randint(1, 100)
self.attempts = 0
self.result_label.config(text="")
self.guess_button.config(state="normal")
if __name__ == "__main__":
root = tk.Tk()
app = GuessNumberGame(root)
root.mainloop()
```
运行该程序,即可启动一个简单的GUI猜数字游戏。玩家需要在文本框内输入一个数字,点击“Guess”按钮进行猜测,程序会根据玩家的猜测给出提示(猜得太大或太小),直到玩家猜中为止。游戏结束后,玩家可以点击“Reset”按钮重新开始游戏。
阅读全文