用Python编程使用tkinter实现猜拳小游戏
时间: 2024-05-14 09:14:45 浏览: 185
下面是一个使用Python编程使用tkinter实现猜拳小游戏的示例代码:
```python
import tkinter as tk
import random
# 创建窗口
window = tk.Tk()
window.title('猜拳小游戏')
window.geometry('300x200')
# 定义函数
def start_game():
pc = random.choice(['石头', '剪刀', '布'])
user = user_choice.get()
result = tk.StringVar()
if user == pc:
result.set('平局')
elif (user == '石头' and pc == '剪刀') or (user == '剪刀' and pc == '布') or (user == '布' and pc == '石头'):
result.set('你赢了')
else:
result.set('你输了')
result_label.config(textvariable=result)
# 创建控件
choice_label = tk.Label(window, text='请选择出拳的手势:')
choice_label.pack()
user_choice = tk.StringVar()
rock_radio = tk.Radiobutton(window, text='石头', variable=user_choice, value='石头')
rock_radio.pack()
scissors_radio = tk.Radiobutton(window, text='剪刀', variable=user_choice, value='剪刀')
scissors_radio.pack()
paper_radio = tk.Radiobutton(window, text='布', variable=user_choice, value='布')
paper_radio.pack()
start_button = tk.Button(window, text='开始游戏', command=start_game)
start_button.pack()
result_label = tk.Label(window, text='请开始游戏')
result_label.pack()
# 运行窗口
window.mainloop()
```
运行代码后,可以看到一个简单的窗口,可以选择出拳的手势,并点击开始游戏按钮,程序会随机出拳,并根据猜拳规则判断胜负,将结果显示在窗口中。
阅读全文