python实现滚动抽奖(可加小机关)

python实现滚动抽奖(可加小机关)

实现的功能:

1.peopleList.csv 是参与抽奖名单
2.可以选择重复抽取或不重复抽取
3.可以设置每次抽取人数
4.抽动过程中可以让名单滚动起来
5.可以导出抽奖记录csv格式,默认以导出时间命名
*双击复位可以,指导人员(csv中前5名)*操作非常隐秘…

下面代码介绍:

第一步,自己写csv的读写,有pandas 为什么需要自己写,为了打包成exe更小,启动更快。

# -*- coding: utf-8 -*-

def read_csv(path):
    try:
        keys = []
        list_dict = []
        with open(path,'r',encoding='utf-8') as file:
            for index,line in enumerate(file.readlines()):

                if index == 0:
                    line = line[1:]
                    line = line.strip()
                    row = line.split(',')
                    keys = row
                else:
                    line = line.strip()
                    row = line.split(',')
                    dict1 = {}

                    for index2,key in enumerate(keys):
                        dict1[key] = row[index2]
                    list_dict.append(dict1)

        return list_dict
    except Exception as e:
        return []

def to_csv(name,list_dict):
    # print(list_dict)
    try:
        with open(name, 'w', encoding='utf-8') as file:
            s = ''
            for index,dict1 in enumerate(list_dict):
                for key in dict1:
                    dict1[key] = str(dict1[key])
                if index == 0:
                    line1 = '\ufeff' + ','.join(dict1.keys()) + '\n'
                    s = s + line1
                lineX = ','.join(dict1.values()) + '\n'
                s = s + lineX
            file.write(s)
    except Exception as e:
        print(e)

第二步,使用tkinter完成UI

    window = Tk()
    window.config(background="#134388")
    window.attributes("-fullscreen", False)
    w, h = window.winfo_screenwidth(), window.winfo_screenheight()
    window.geometry("%dx%d" % (w, h))
    window.title('抽奖小程序')

    getPeopleList()

    top2 = Toplevel()
    top2.config(background="#134388")
    top2.geometry('380x230+100+100')
    top2.resizable(0, 0)
    top2.title('抽奖小程序')
    top2.attributes("-topmost", True) #使该窗口保持在所有其他窗口之上

    frame = Frame(window, bg='lightgreen')  # 创建一个框架
    frame.pack(fill=BOTH,expand=YES)

    var_result = StringVar()
    var_result.set('即将开始!')
    resultLable2 = Label(frame,textvariable=var_result,justify='center',bg="#134388",fg='white',wraplength=w-500)
    resultLable2.pack(fill=BOTH, expand=YES)
    resultLable2.config(font='Helvetica -50 bold')

    noteLable = Label(top2,text="请输入抽奖人数:")
    noteLable.place(anchor=NW, x=40, y=30)
    input = Entry(top2, show=None)
    input.place(anchor=NW, x=160, y=30)

    var1 = IntVar()
    Checkbutton = Checkbutton(top2,text="不重复抽取",variable=var1,onvalue=0,
    offvalue=1)
    Checkbutton.place(anchor=NW, x=40, y=60)

    startBt = Button(top2,text="开始抽人", command=lambda: randomRun())
    # startBt.bind("<Button-1>", onLeft)
    # startBt.bind("<Double-Button-1>",Double_click)

    confirmBt = Button(top2,text="确定", command=lambda: finalResult())
    confirmBt['state'] = DISABLED
    resetBt = Button(top2, text="复位", command=lambda: reset())
    resetBt['state'] = DISABLED

    # resetBt.bind("<Button-1>", onLeft)
    resetBt.bind("<Double-Button-1>", Double_click)


    exportBt = Button(top2,text="导出", command=lambda: exportResult())
    exportBt['state'] = DISABLED

    startBt.place(anchor=NW, x=40, y=120)
    confirmBt.place(anchor=NW, x=160, y=120)
    resetBt.place(anchor=NW, x=250, y=120)
    exportBt.place(anchor=NW, x=250, y=150)

    window.mainloop()

获取csv内的人员

def getPeopleList():
    global people_dict
    global people_list,people_list2,people_list3
    global luck_people_list1, luck_people_list2
    people_dict = wb_readcsv.read_csv(os.path.dirname(os.path.realpath(sys.argv[0]))+'/peopleList.csv')
    people_list = [n for n in range(0, len(people_dict))]
    people_list2 = copy.deepcopy(people_list)
    people_list3 = people_list2[:5] #需要内定名单
    people_list2 = people_list2[5:] #正常抽取名单

    luck_people_list1 = []
    luck_people_list2 = []

是否重复抽取

def randomRun():
    global is_run
    global people_list, people_list2
    if is_run:#此部分用于避免多次点击开始造成程序重复执行的错误
        return
    is_run = True
    num = insert_point()
    if num:
        num = int(num)
        if var1.get() == 0:
            randomResult(people_list2,num)
        else:
            randomResult(people_list,num)

        confirmBt['state'] = NORMAL
        startBt['state'] = DISABLED
    else:
        is_run = False
        showinfo('提示', '请输入抽奖人数!')

随机抽奖

def randomResult(list,num):
    global is_run,i
    global luck_people_list1, luck_people_list2

    global people_dict,people_list,people_list2,people_list3
    if len(list) <= num:
        result = list
    else:
        result = random.sample(list, num)
    result_name = []

    for index,data in enumerate(result):
        result_name.append(people_dict[data]['name'])

    result_name_str = ','.join(result_name)
    var_result.set(result_name_str)
    if is_run:
        window.after(10, randomResult, list, num)
    #如果复位按钮被多次点击将会从指定名单中抽取
    else:
        if i > 0 and i < 10:
            try:
                result[0] = people_list3[0]
                print(i)
                i = 0
                people_list3.pop(0)
                result_name = []
                for index, data in enumerate(result):
                    result_name.append(people_dict[data]['name'])
                result_name_str = ','.join(result_name)
                var_result.set(result_name_str)
            except:
                pass
        else:
            i = 0
        print(result_name)
        # print(var_result.get())
        if var1.get() == 0:
            for data in result:
                try:
                    people_list2.remove(data)
                except:
                    pass

            luck_people_list2.append(result)
        else:
            luck_people_list1.append(result)

下面是一些按钮的事件



i = 0
is_run = False
def insert_point():
     var = input.get() #获取输入的信息
     return var
     
def finalResult():
    global is_run
    is_run = False
    startBt['state'] = NORMAL
    exportBt['state'] = NORMAL
    resetBt['state'] = NORMAL
    confirmBt['state'] = DISABLED

def reset():
    result_name = "即将开始!"
    var_result.set(result_name)

def onLeft(event):
    global i
    i=0

def Double_click(envent):

    global i
    i += 1
    result_name = "即将开始!{}".format(i)
    print(result_name)

def exportResult():
    global luck_people_list1, luck_people_list2
    global people_dict

    luck_people_dict1 = []
    luck_people_dict2 = []
    for index,data in enumerate(luck_people_list1):
        for luck in data:
            dict1 = copy.deepcopy(people_dict[luck])
            dict1['luck'] = index+1
            luck_people_dict1.append(dict1)

    for index,data in enumerate(luck_people_list2):
        for luck in data:
            dict1 = copy.deepcopy(people_dict[luck])
            dict1['luck'] = index+1
            luck_people_dict2.append(dict1)

    # 获取今天的字符串
    nowTime = time.strftime("%Y%m%d_%H%M%S", time.localtime(time.time()))
wb_readcsv.to_csv(os.path.dirname(os.path.realpath(sys.argv[0]))+"/可重复_{}.csv".format(nowTime),luck_people_dict1)
    wb_readcsv.to_csv(os.path.dirname(os.path.realpath(sys.argv[0]))+"/不重复_{}.csv".format(nowTime), luck_people_dict2)
    showinfo('提示', '导出完成!')

到这里,就完成了一个滚动抽奖的小程序,团建用起来,可以控制你想要的人唱歌…

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Python实现滚动抽奖功能通常涉及到随机选择和动态展示奖品的过程。这种功能可以通过使用内置的`random`模块来生成随机数,结合`time`模块来控制抽奖的节奏,以及可能的GUI库如`tkinter`或Web框架如Flask来展示抽奖过程。以下是一个简单的滚动抽奖的步骤: 1. 创建奖品列表:首先,你需要定义一个包含所有奖品的列表,奖品可以是字符串、数字或者其他可迭代对象。 ```python prizes = ["一等奖", "二等奖", "三等奖", "谢谢参与"] ``` 2. 抽奖函数:编写一个函数,使用`random.choice()`来随机选取一个奖品。 ```python import random def draw_prize(prizes): return random.choice(prizes) ``` 3. 滚动显示:如果你想模仿滚动的效果,可以在每次抽奖后更新界面或者控制台输出,并稍微延迟一段时间再进行下一次抽奖。这里你可以用`time.sleep()`来模拟延迟。 ```python import time def scrolling_lottery(prizes): for _ in range(len(prizes)): print(f"正在抽奖...{draw_prize(prizes)}") time.sleep(1) # 延迟1秒 ``` 4. GUI支持(如果使用):如果你想要一个更交互式的界面,可以使用`tkinter`库创建一个小窗口,显示滚动的奖品。例如,你可以创建一个Label控件并不断更新它的文本。 ```python import tkinter as tk def draw_in_gui(): prize = draw_prize(prizes) label.config(text=prize) root.after(1000, draw_in_gui) # 每隔1秒执行一次 # 初始化GUI root = tk.Tk() label = tk.Label(root, text="正在抽奖...") label.pack() draw_in_gui() root.mainloop() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时尚IT男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值