请用python程序实现GUI版的简易猜数游戏(给出实现代码)
时间: 2024-02-05 20:02:22 浏览: 75
以下是一个简易的猜数字游戏GUI程序,使用Python的Tkinter模块实现:
```python
import random
import tkinter as tk
class GuessNumberGame(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.master.title("猜数字游戏")
self.pack()
self.create_widgets()
self.number = random.randint(1, 100)
self.guesses_left = 10
def create_widgets(self):
self.label = tk.Label(self, text="我想了一个1到100之间的数字,你猜猜看?")
self.label.pack(side="top")
self.guess_entry = tk.Entry(self)
self.guess_entry.pack(side="top")
self.guess_button = tk.Button(self, text="猜", command=self.make_guess)
self.guess_button.pack(side="top")
self.quit_button = tk.Button(self, text="退出", command=self.master.destroy)
self.quit_button.pack(side="bottom")
def make_guess(self):
guess = int(self.guess_entry.get())
self.guesses_left -= 1
if guess < self.number:
self.label.config(text="猜小了!你还剩下{}次机会。".format(self.guesses_left))
elif guess > self.number:
self.label.config(text="猜大了!你还剩下{}次机会。".format(self.guesses_left))
else:
self.label.config(text="恭喜你猜对了!")
self.guess_entry.config(state="disabled")
self.guess_button.config(state="disabled")
if self.guesses_left == 0:
self.label.config(text="很遗憾,你没有猜中。正确的数字是{}。".format(self.number))
self.guess_entry.config(state="disabled")
self.guess_button.config(state="disabled")
if __name__ == '__main__':
root = tk.Tk()
app = GuessNumberGame(master=root)
app.mainloop()
```
运行程序后,会弹出一个窗口,显示“我想了一个1到100之间的数字,你猜猜看?”和一个文本框和一个“猜”按钮。用户可以在文本框中输入猜测的数字,然后点击“猜”按钮。程序会根据用户的猜测给出提示,如果猜对了,会弹出“恭喜你猜对了!”的提示。如果猜错了,程序会告诉用户猜大了还是猜小了,并告诉用户还剩下多少次机会。如果用户没有在规定的次数内猜对,程序会弹出“很遗憾,你没有猜中。正确的数字是X。”的提示。用户可以点击“退出”按钮退出游戏。
阅读全文
相关推荐


















