python tkinter 小游戏代码
时间: 2023-07-10 19:10:29 浏览: 150
以下是一个简单的 Python Tkinter 小游戏代码,名为"Guess the Number",游戏规则是猜一个随机数:
```python
import tkinter as tk
import random
class GuessingGame:
def __init__(self, master):
self.master = master
master.title("Guess the Number")
self.secret_number = random.randint(1, 100)
self.guesses_left = 5
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.result_label = tk.Label(master, text="")
self.result_label.pack()
self.guesses_label = tk.Label(master, text="Guesses left: {}".format(self.guesses_left))
self.guesses_label.pack()
self.check_button = tk.Button(master, text="Check", command=self.check_guess)
self.check_button.pack()
self.quit_button = tk.Button(master, text="Quit", command=master.quit)
self.quit_button.pack()
def check_guess(self):
guess = int(self.entry.get())
self.entry.delete(0, tk.END)
self.guesses_left -= 1
self.guesses_label.config(text="Guesses left: {}".format(self.guesses_left))
if guess == self.secret_number:
self.result_label.config(text="You guessed it!")
self.check_button.config(state=tk.DISABLED)
elif guess < self.secret_number:
self.result_label.config(text="Too low!")
else:
self.result_label.config(text="Too high!")
if self.guesses_left == 0:
self.result_label.config(text="You lose. The secret number was {}.".format(self.secret_number))
self.check_button.config(state=tk.DISABLED)
root = tk.Tk()
game = GuessingGame(root)
root.mainloop()
```
在这个游戏中,我们使用 tkinter 创建了一个窗口,并在窗口中添加了一些组件,如标签、输入框和按钮。在游戏开始时,程序会生成一个 1 到 100 之间的随机数,玩家需要在 5 次内猜中该随机数。每次猜测后,程序会告诉玩家猜测是否正确,如果猜测错误,还会告诉玩家猜测的数值是太高还是太低。如果玩家猜中了,程序会告诉玩家胜利了,如果猜测次数用完了还没有猜中,程序会告诉玩家失败了。
阅读全文