编写 GUI 界面,模拟抢红包游戏,在界面输入红包大小和抢红包人姓名(用逗号隔开),输出系统当前时间以及每个人抢的红包大小,要求每个人抢的红包最少不能少于0.01元。
时间: 2024-04-04 18:31:29 浏览: 16
好的,这是一个简单的GUI界面,你可以参考这个代码实现:
```python
import tkinter as tk
import time
class RedPacketGame:
def __init__(self, master):
self.master = master
master.title("抢红包游戏")
# 创建输入红包大小的Label和Entry
self.label_amount = tk.Label(master, text="红包大小:")
self.label_amount.grid(row=0, column=0)
self.entry_amount = tk.Entry(master)
self.entry_amount.grid(row=0, column=1)
# 创建输入抢红包人姓名的Label和Entry
self.label_name = tk.Label(master, text="抢红包人姓名:")
self.label_name.grid(row=1, column=0)
self.entry_name = tk.Entry(master)
self.entry_name.grid(row=1, column=1)
# 创建"开始"按钮
self.button_start = tk.Button(master, text="开始", command=self.start_game)
self.button_start.grid(row=2, column=0)
# 创建输出信息的Text
self.text_output = tk.Text(master, height=10, width=50)
self.text_output.grid(row=3, column=0, columnspan=2)
def start_game(self):
# 获取输入的红包大小和抢红包人姓名
amount = float(self.entry_amount.get())
names = self.entry_name.get().split(",")
# 判断红包大小是否足够
if amount < len(names) * 0.01:
self.text_output.insert(tk.END, "红包大小不足!\n")
return
# 计算每个人抢到的红包大小
red_packets = []
for i in range(len(names)):
if i == len(names) - 1:
red_packets.append(amount - sum(red_packets))
else:
red_packets.append(round((amount / len(names)) * 100) / 100)
# 输出系统当前时间
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
self.text_output.insert(tk.END, "系统当前时间:" + current_time + "\n")
# 输出每个人抢到的红包大小
for i in range(len(names)):
self.text_output.insert(tk.END, "{} 抢到了 {:.2f} 元。\n".format(names[i], red_packets[i]))
root = tk.Tk()
red_packet_game = RedPacketGame(root)
root.mainloop()
```
在运行这个代码之前,你需要安装 tkinter 模块。
这个界面有两个输入框,一个是红包大小,一个是抢红包人姓名,用逗号隔开。当你点击"开始"按钮之后,程序会输出系统当前时间以及每个人抢到的红包大小。注意,每个人抢到的红包大小最少不能少于0.01元。
相关推荐
![tar](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)