python用gui做一个剪刀石头布游戏
时间: 2023-06-23 15:57:57 浏览: 104
Python实现简单石头剪刀布游戏
好的,我们可以使用Python自带的GUI库Tkinter来实现这个剪刀石头布小游戏。
首先,我们需要导入Tkinter库和random库:
```python
import tkinter as tk
import random
```
然后,我们需要定义一个函数来处理用户点击按钮的事件,并随机生成电脑的选择:
```python
def play_game(player_choice):
computer_choice = random.choice(["剪刀", "石头", "布"])
```
接下来,我们需要根据用户和电脑的选择来判断胜负,并给出相应的提示:
```python
if player_choice == computer_choice:
result_label.config(text="平局!")
elif player_choice == "剪刀" and computer_choice == "石头":
result_label.config(text="你输了!")
elif player_choice == "石头" and computer_choice == "布":
result_label.config(text="你输了!")
elif player_choice == "布" and computer_choice == "剪刀":
result_label.config(text="你输了!")
else:
result_label.config(text="你赢了!")
```
在主函数中,我们需要创建一个窗口,并添加一些控件,如标签、按钮等:
```python
window = tk.Tk()
window.title("剪刀石头布游戏")
scissors_button = tk.Button(window, text="剪刀", command=lambda: play_game("剪刀"))
scissors_button.pack(side="left")
rock_button = tk.Button(window, text="石头", command=lambda: play_game("石头"))
rock_button.pack(side="left")
paper_button = tk.Button(window, text="布", command=lambda: play_game("布"))
paper_button.pack(side="left")
result_label = tk.Label(window, text="")
result_label.pack()
window.mainloop()
```
完整代码如下:
```python
import tkinter as tk
import random
def play_game(player_choice):
computer_choice = random.choice(["剪刀", "石头", "布"])
if player_choice == computer_choice:
result_label.config(text="平局!")
elif player_choice == "剪刀" and computer_choice == "石头":
result_label.config(text="你输了!")
elif player_choice == "石头" and computer_choice == "布":
result_label.config(text="你输了!")
elif player_choice == "布" and computer_choice == "剪刀":
result_label.config(text="你输了!")
else:
result_label.config(text="你赢了!")
window = tk.Tk()
window.title("剪刀石头布游戏")
scissors_button = tk.Button(window, text="剪刀", command=lambda: play_game("剪刀"))
scissors_button.pack(side="left")
rock_button = tk.Button(window, text="石头", command=lambda: play_game("石头"))
rock_button.pack(side="left")
paper_button = tk.Button(window, text="布", command=lambda: play_game("布"))
paper_button.pack(side="left")
result_label = tk.Label(window, text="")
result_label.pack()
window.mainloop()
```
运行程序,你就可以在窗口中玩剪刀石头布小游戏了。
阅读全文