• 30行代码做一个简易的抽奖系统(一)


    通过tkinter做一个简易的抽奖系统。

    思路:通过button按钮text属性展示信息,按开始按钮,在button中随机不断展示信息,按结束按钮则完成抽奖。代码如下:

    1. import tkinter as tk
    2. import random
    3. from tkinter import messagebox
    4. class Cj:
    5. def __init__(self,master):
    6. self.master = master
    7. self.var = tk.StringVar()
    8. l = tk.Label(master,text='简易抽奖系统',font=('方正舒体',16),bg='red',fg='blue')
    9. l.pack()
    10. button1 = tk.Button(root,textvariable=self.var,font=('方正舒体',20),width=16,height=3,fg='red')
    11. button1.pack(pady=30)
    12. button2 = tk.Button(root, text='开始', font=('方正舒体', 15), width=10,command=self.start)
    13. button2.pack(pady=10,padx=10,side="left")
    14. button3 = tk.Button(root, text='结束', font=('方正舒体', 15), width=10,command=self.end)
    15. button3.pack(pady=10, padx=10, side="right")
    16. self.lists = ['张三', '李四', '王五', '李飞', '李伟', '黄骅']
    17. self.var.set('准备好了吗?')
    18. def start(self):
    19. self.var.set(random.choice(self.lists))
    20. self.s = self.master.after(100,self.start)
    21. def end(self):
    22. try:
    23. self.master.after_cancel(self.s)
    24. self.var.set(random.choice(self.lists))
    25. except Exception:
    26. messagebox.showerror(title = '错误信息',message = '请先按开始按钮!')
    27. root = tk.Tk()
    28. root.title('抽奖系统')
    29. root.geometry('440x300+200+100')
    30. root.resizable(0, 0) #设置窗口不可变
    31. Cj(root)
    32. root.mainloop()

    效果如下:

     本来刚开始想用while True显示信息,这样不行,后面用了tkinter中的after方法,用于显示;

    重点:

    1、self.master.after(100,self.start)是指每隔100ms用于显示姓名在button上;

    2、当点击结束时,需要停止after方法,这时候需要用到after_cancel的方法,self.master.after_cancel(self.s)是停止after方法。

  • 相关阅读:
    linkagemapping中Failed to execute (RasterToPolyline)
    Java中关键字final的用法细节详解
    Vue2和Vue3的区别
    运筹说 第82期 | 算法介绍之图与网络分析(二)
    数据挖掘与分析课程笔记(Chapter 2)
    UE5C++学习(二)--- 角色简单连击
    详解容灾恢复过程中跨数据中心级的关键故障切换
    泰山OFFICE技术讲座:文字边框高度研究
    测试报告 拍卖系统
    每日一题day15
  • 原文地址:https://blog.csdn.net/qq_33267306/article/details/126408655