import tkinter as tk
import random
from tkinter import messagebox
root = tk.Tk()
left = tk.LabelFrame(root, text='抽奖列表', font=("微软雅黑", 13))
left.pack(side=tk.LEFT, padx=10, pady=10)
right = tk.LabelFrame(root, text='列表选项', font=("微软雅黑", 13))
right.pack(side=tk.RIGHT, padx=10, pady=10)
# 抽取函数
def choice():
lists = choice_list.get(0, tk.END)
if len(lists) != 0:
text.config(state=tk.NORMAL)
text.delete(1.0, tk.END)
text.insert(tk.END, str(random.choice(lists)))
text.config(state=tk.DISABLED)
# 添加函数
def add(event=None):
if add_text.get() != '':
choice_list.insert(tk.END, add_text.get())
else:
messagebox.showwarning(title='错误', message="添加失败:输入栏为空!")
# 删除函数
def delete_to_index(event=None):
try:
if delete_index.get() < 1 or delete_index.get() > choice_list.size() - 1:
choice_list.delete(delete_index.get() - 1)
else:
messagebox.showerror(title='错误', message="删除失败:超出索引范围!")
except tk.TclError:
messagebox.showerror(title='错误', message="删除失败:类型错误!")
def delete_insert(event=None):
if len(choice_list.curselection()) == 0:
messagebox.showerror(title='错误', message="删除失败:没有选中项!")
else:
for i in choice_list.curselection():
choice_list.delete(i)
# 左边
# 滚动条
scroll = tk.Scrollbar(left)
scroll.pack(side=tk.RIGHT, fill=tk.Y)
# 列表框
choice_list = tk.Listbox(left, yscrollcommand=scroll.set, selectmode=tk.MULTIPLE)
choice_list.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
choice_list.bind("<<ListboxSelect>>", delete_insert) # 绑定事件
# 同步滚动条
scroll.config(command=choice_list.yview)
# 右边
add_text = tk.StringVar()
delete_index = tk.IntVar()
# 添加按钮
tk.Button(right, text='添加', command=add, font=("微软雅黑", 13)).grid(row=0, padx=10, pady=5)
# 添加输入框
e1 = tk.Entry(right, textvariable=add_text, font=("微软雅黑", 13))
e1.grid(row=0, column=1, padx=10, pady=5)
e1.bind("<Return>", add) # 绑定回车事件
# 删除按钮
tk.Button(right, text='删除', command=delete_to_index, font=("微软雅黑", 13)).grid(row=1, padx=10, pady=5)
# 删除输入框
e2 = tk.Entry(right, textvariable=delete_index, font=("微软雅黑", 13))
e2.grid(row=1, column=1, padx=10, pady=5)
e2.bind("<Return>", delete_insert) # 绑定回车事件
# 抽取按钮
tk.Button(right, text='抽奖', command=choice, font=("微软雅黑", 13)).grid(row=2, padx=10, pady=5)
# 显示抽奖结果
tk.Label(right, text='你抽到了', font=("微软雅黑", 13)).grid(row=3, padx=10, pady=5)
text = tk.Text(right, font=("微软雅黑", 13), state=tk.DISABLED, width=20, height=1.3)
text.grid(row=3, column=1, padx=10, pady=5)
root.mainloop()