tkinter小游戏
时间: 2023-11-27 17:47:45 浏览: 133
用python的tkinter制作的猜拳游戏
以下是一个使用tkinter制作的猜数字小游戏的例子:
```python
import tkinter as tk
import random
class GuessNumber:
def __init__(self, master):
self.master = master
master.title("Guess Number")
self.secret_number = random.randint(1, 100)
self.guesses_left = 10
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.button = tk.Button(master, text="Guess", command=self.guess)
self.button.pack()
self.result = tk.Label(master, text="")
self.result.pack()
def guess(self):
guess = int(self.entry.get())
self.guesses_left -= 1
if guess == self.secret_number:
self.result.config(text="Congratulations! You guessed the number in {} guesses.".format(10 - self.guesses_left))
self.button.config(state="disabled")
self.entry.config(state="disabled")
elif self.guesses_left == 0:
self.result.config(text="Game over. The secret number was {}.".format(self.secret_number))
self.button.config(state="disabled")
self.entry.config(state="disabled")
elif guess < self.secret_number:
self.result.config(text="Too low. You have {} guesses left.".format(self.guesses_left))
else:
self.result.config(text="Too high. You have {} guesses left.".format(self.guesses_left))
root = tk.Tk()
game = GuessNumber(root)
root.mainloop()
```
这个小游戏会在窗口中显示一个文本框和一个按钮,玩家需要在文本框中输入一个数字并点击按钮来猜测这个数字。游戏会告诉玩家猜的数字是太高还是太低,直到玩家猜中这个数字或者用完了所有的猜测次数。
阅读全文