实现 GUI 版的猜数有一
时间: 2023-06-18 13:05:48 浏览: 77
java编写的猜数游戏
可以使用 Python 的 Tkinter 模块来实现 GUI 版的猜数游戏。以下是一个简单的示例代码:
```python
import random
import tkinter as tk
class GuessNumberGame:
def __init__(self, master):
self.master = master
master.title("Guess Number Game")
self.number = random.randint(1, 100)
self.guesses = 0
self.label = tk.Label(master, text="Guess a number between 1 and 100:")
self.label.pack()
self.entry = tk.Entry(master)
self.entry.pack()
self.submit_button = tk.Button(master, text="Submit", command=self.submit_guess)
self.submit_button.pack()
self.result_label = tk.Label(master, text="")
self.result_label.pack()
def submit_guess(self):
guess = int(self.entry.get())
self.guesses += 1
if guess == self.number:
self.result_label.config(text=f"Congratulations! You guessed the number in {self.guesses} guesses.")
self.submit_button.config(state=tk.DISABLED)
elif guess < self.number:
self.result_label.config(text="Too low, try again.")
else:
self.result_label.config(text="Too high, try again.")
self.entry.delete(0, tk.END)
root = tk.Tk()
game = GuessNumberGame(root)
root.mainloop()
```
该程序会生成一个随机数,然后要求用户在 GUI 界面中输入自己的猜测。如果猜对了,程序会输出猜数的次数;否则,程序会提示用户猜测偏高或偏低,并将猜数次数加1。用户可以一直猜数,直到猜中为止。
阅读全文