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()