弹窗攻势——使用python几行代码实现弹窗版新年祝福

使用python实现弹窗版新年祝福

  • 代码
  • 代码解释
  • 改进版代码
  • 运行结果

代码

import tkinter as tk
import random
import threading
import time

wordslist = ['万事如意', '新年快乐', '福星高照', '年年有余']
x = 0

def dow():
    window = tk.Tk()
    width=window.winfo_screenwidth()
    height=window.winfo_screenheight()
    a=random.randrange(0,width)
    b=random.randrange(0,height)
    window.title('祝愿')
    window.geometry("200x50"+"+"+str(a)+"+"+str(b))
    global x
    text1 = wordslist[x]
    x += 1
    if x == len(wordslist):
        x=0
    tk.Label(window,
        text= text1,
        bg='Red',     
        font=('楷体', 17),    
        width=15, height=2 
        ).pack()  
    window.mainloop()
 
threads = []
for i in range(50):
    t = threading.Thread(target=dow)
    threads.append(t)
    time.sleep(0.1)
    threads[i].start()

代码解释

其基本原理是运用了python中线程的操作,对tkinter构建的只含标签的窗口进行进程的创建。同时将标签的颜色设置为红色以及不同的祝福语,要注意的是这里线程数和祝福语的个数相乘也要控制好数量,太少布局不会很好看,太多又容易让人心烦,同时我们可以引入随机数随机弹出祝福语,下面给出利用随机数的改进版本

改进版代码

import tkinter as tk
import random
import threading
import time

def dow():
    window = tk.Tk()
    width=window.winfo_screenwidth()
    height=window.winfo_screenheight()
    a=random.randrange(0,width)
    b=random.randrange(0,height)
    window.title('祝愿')
    window.geometry("200x50"+"+"+str(a)+"+"+str(b))
    wordslist = ['万事如意', '新年快乐', '福星高照', '年年有余']
    text1 = wordslist[random.randint(0, len(wordslist)-1)]
    tk.Label(window,
        text= text1,  
        bg='Red',    
        font=('楷体', 17),     
        width=15, height=2  
        ).pack()   
    window.mainloop()
 
threads = []
for i in range(50):
    t = threading.Thread(target=dow)
    threads.append(t)
    time.sleep(0.1)
    threads[i].start()

运行结果

弹窗攻势——使用python几行代码实现弹窗版新年祝福_第1张图片

你可能感兴趣的:(趣味python,python,开发语言)