用python中的tkinter写一个剪刀石头布游戏
时间: 2024-03-25 13:15:01 浏览: 92
好的,以下是一个简单的剪刀石头布游戏的Python Tkinter GUI实现:
```python
from tkinter import *
from random import randint
# 创建根窗口
root = Tk()
root.title("剪刀石头布游戏")
# 定义变量
options = ["剪刀", "石头", "布"]
player_choice = StringVar()
computer_choice = StringVar()
result = StringVar()
# 定义函数
def play():
# 玩家选择
player = player_choice.get()
# 计算机随机选择
computer = options[randint(0, 2)]
computer_choice.set(computer)
# 判断胜负
if player == computer:
result.set("平局!")
elif (player == "剪刀" and computer == "布") or \
(player == "石头" and computer == "剪刀") or \
(player == "布" and computer == "石头"):
result.set("你获胜了!")
else:
result.set("计算机获胜了!")
# 创建界面
Label(root, text="请选择:").grid(row=0, column=0, padx=10, pady=10)
Radiobutton(root, text="剪刀", variable=player_choice, value="剪刀").grid(row=1, column=0)
Radiobutton(root, text="石头", variable=player_choice, value="石头").grid(row=2, column=0)
Radiobutton(root, text="布", variable=player_choice, value="布").grid(row=3, column=0)
Label(root, text="计算机选择:").grid(row=0, column=1, padx=10, pady=10)
Label(root, textvariable=computer_choice).grid(row=1, column=1)
Button(root, text="出拳", command=play).grid(row=4, column=0, pady=10)
Label(root, text="结果:").grid(row=2, column=1, padx=10, pady=10)
Label(root, textvariable=result).grid(row=3, column=1)
# 进入消息循环
root.mainloop()
```
该程序使用了`Radiobutton`组件来让用户选择剪刀、石头或布。当用户点击“出拳”按钮时,程序会计算出计算机的随机选择,并判断胜负。最后,程序会将计算机的选择和胜负结果显示在界面上。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)