弹窗攻势——使⽤python⼏⾏代码实现弹窗版新年祝福
使⽤python实现弹窗版新年祝福
代码
import tkinter as tk
import random
import threading
import time
wordslist =['万事如意','新年快乐','福星⾼照','年年有余']
random在python中的意思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('祝愿')
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('祝愿')
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()
运⾏结果

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。