python剪刀石头布用tkinter界面化
时间: 2023-07-09 09:52:51 浏览: 111
好的,下面是一个简单的Python剪刀石头布游戏的Tkinter界面代码:
```python
import tkinter as tk
import random
# 定义游戏规则
rules = {'rock': 'scissors', 'scissors': 'paper', 'paper': 'rock'}
# 定义胜负判断函数
def judge(player_choice, computer_choice):
if rules[player_choice] == computer_choice:
return 'You win!'
elif rules[computer_choice] == player_choice:
return 'Computer wins!'
else:
return 'Tie!'
# 定义按钮点击事件函数
def play(player_choice):
computer_choice = random.choice(['rock', 'paper', 'scissors'])
result = judge(player_choice, computer_choice)
result_label.config(text='You chose: {}\nComputer chose: {}\n{}'.format(player_choice, computer_choice, result))
# 创建窗口
window = tk.Tk()
window.title('Rock Paper Scissors')
# 创建按钮
rock_btn = tk.Button(window, text='Rock', command=lambda: play('rock'))
paper_btn = tk.Button(window, text='Paper', command=lambda: play('paper'))
scissors_btn = tk.Button(window, text='Scissors', command=lambda: play('scissors'))
# 创建结果标签
result_label = tk.Label(window, text='Make your choice!')
# 按钮和结果标签布局
rock_btn.pack(side='left', padx=10, pady=20)
paper_btn.pack(side='left', padx=10, pady=20)
scissors_btn.pack(side='left', padx=10, pady=20)
result_label.pack(pady=20)
# 运行窗口
window.mainloop()
```
运行代码后,将会弹出一个窗口,上面有三个按钮和一个用于显示结果的标签。玩家点击按钮后,程序会随机出一个电脑的选择,并计算出胜负结果,并在结果标签上显示。
阅读全文