编写一个程序,实现图形界面的猜数字的游戏
时间: 2024-05-07 14:19:55 浏览: 18
下面是一个简单的基于 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.answer = random.randint(1, 100)
self.num_guesses = 0
# 创建 UI 组件
self.label = tk.Label(self.master, text="Guess a number between 1 and 100")
self.label.pack()
self.entry = tk.Entry(self.master)
self.entry.pack()
self.button = tk.Button(self.master, text="Guess", command=self.check_guess)
self.button.pack()
def check_guess(self):
guess = int(self.entry.get())
self.num_guesses += 1
if guess == self.answer:
self.label.config(text=f"Congratulations! You guessed the number in {self.num_guesses} guesses.")
self.button.config(state="disabled")
elif guess < self.answer:
self.label.config(text="Too low, try again.")
else:
self.label.config(text="Too high, try again.")
# 创建主窗口
root = tk.Tk()
# 启动游戏
game = GuessNumberGame(root)
# 进入主事件循环
root.mainloop()
```
在上面的程序中,我们首先在 `__init__()` 方法中生成一个随机数字并记录猜测次数。然后创建了 Label、Entry 和 Button 三个 UI 组件,用户通过 Entry 组件输入数字,点击 Button 按钮检查输入的数字是否正确。如果猜测正确,则显示“恭喜你猜对了”的消息,如果猜测错误,则显示“太高了”或“太低了”的消息。当用户猜对数字后,Button 按钮将被禁用。
在主函数中,我们创建了主窗口,并将其传递给 `GuessNumberGame` 类,以启动游戏。最后,我们进入主事件循环,等待用户与 UI 交互。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)