赞
踩
学习python的图形界面设计过程中,花了2个多小时写了一个小程序自娱自乐。中间自己调试花了不少时间,主要是单线程跑的话,按钮卡死,后来改用多线程搞定。
话不多说,代码原文奉上
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2020/3/18 15:14 # @Author : Lihua # @Site : # @File : 抽奖小程序.py # @Software: PyCharm import random import time from tkinter import * import threading from tkinter import messagebox as msgbox root = Tk() list_candidate=["张三","李四","王五"] class lottery(): def __init__(self): self.root=root self.msgbox=msgbox self.root.geometry("800x600+280+80") self.root.title("抽奖小程序") self.button_start=Button(self.root,text="开始抽奖",width=6,command=self.start) self.button_stop=Button(self.root,text="结束抽奖",width=6,command=self.stop) self.label_str=StringVar() self.label_str.set("抽奖马上开始了") self.label_winner = Label(self.root, font=("华文行楷", 20), width=20, height=30,fg="pink",textvariable=self.label_str) self.label_winner.pack() self.button_start.place(relx=0.2,rely=0.7) self.button_stop.place(relx=0.7,rely=0.7) self.ready=0 self.root.mainloop() def draw(self): print("开始滚动显示中奖人信息") global list_candidate while self.ready: index_num = random.randint(1, 1000) % len(list_candidate) #print(index_num) winner = list_candidate[index_num] self.label_str.set(winner) print("赢家是" + winner) self.msgbox.showinfo("发红包", "恭喜" + winner + ",您中奖啦!") def start(self): print("开始抽奖") self.ready=1 #此处必须启用新的线程,否则会卡死在开始按钮,且标签的中奖人信息不会刷新 self.thread=threading.Thread(target=self.draw,args=()) self.thread.setDaemon(True) self.thread.start() def stop(self): print("结束抽奖") global winner self.ready=0 if __name__ == '__main__': Lottery=lottery()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。