用python中的tkinter库实现猜拳游戏
时间: 2024-03-31 10:13:05 浏览: 87
以下是一个基本的猜拳游戏的Python Tkinter GUI应用程序。
```python
import tkinter as tk
import random
class RockPaperScissors:
def __init__(self, master):
self.master = master
master.title("Rock Paper Scissors")
self.result_var = tk.StringVar()
self.result_var.set("Choose rock, paper, or scissors to play.")
self.computer_choice_var = tk.StringVar()
self.computer_choice_var.set("")
self.label = tk.Label(master, textvariable=self.result_var, font=("Helvetica", 16))
self.label.pack()
self.computer_choice_label = tk.Label(master, textvariable=self.computer_choice_var, font=("Helvetica", 12))
self.computer_choice_label.pack()
self.rock_button = tk.Button(master, text="Rock", command=lambda: self.play("rock"))
self.rock_button.pack()
self.paper_button = tk.Button(master, text="Paper", command=lambda: self.play("paper"))
self.paper_button.pack()
self.scissors_button = tk.Button(master, text="Scissors", command=lambda: self.play("scissors"))
self.scissors_button.pack()
self.quit_button = tk.Button(master, text="Quit", command=master.quit)
self.quit_button.pack()
def play(self, player_choice):
choices = ["rock", "paper", "scissors"]
computer_choice = random.choice(choices)
self.computer_choice_var.set("The computer chose " + computer_choice + ".")
if player_choice == computer_choice:
self.result_var.set("It's a tie!")
elif player_choice == "rock" and computer_choice == "scissors":
self.result_var.set("You win!")
elif player_choice == "paper" and computer_choice == "rock":
self.result_var.set("You win!")
elif player_choice == "scissors" and computer_choice == "paper":
self.result_var.set("You win!")
else:
self.result_var.set("You lose!")
root = tk.Tk()
app = RockPaperScissors(root)
root.mainloop()
```
运行上述代码,将弹出一个猜拳游戏窗口。通过点击“Rock”,“Paper”或“Scissors”按钮来进行游戏。游戏结果将显示在窗口顶部,计算机的选择将显示在窗口中间。
阅读全文