【注】
python环境搭建请见:https://want595.blog.csdn.net/article/details/134586653pyinstaller使用教程见:https://want595.blog.csdn.net/article/details/134106807 完整代码 import tkinter as tkimport random as raimport threading as tdimport time as tidef Love():root=tk.Tk()width=200height=50screenwidth=root.winfo_screenwidth()screenheight=root.winfo_screenheight()x=ra.randint(0,screenwidth)y=ra.randint(0,screenheight)root.title("❤")root.geometry("%dx%d+%d+%d"%(width,height,x,y))tk.Label(root,text='I LOVE YOU!',fg='white',bg='pink',font=("Comic Sans MS",15),width=30,height=5).pack()root.mainloop()def Heart():root=tk.Tk()screenwidth=root.winfo_screenwidth()screenheight=root.winfo_screenheight()width=600height=400x=(screenwidth-width)//2y=(screenheight-height)//2root.title("❤")root.geometry("%dx%d+%d+%d"%(screenwidth,screenheight,0,0))tk.Label(root,text='❤',fg='pink',bg='white',font=("Comic Sans MS",500),width=300,height=20).pack()root.mainloop()t=td.Thread(target=Heart)t.setDaemon(True) # 设置守护线程t.start()for i in range(50):t=td.Thread(target=Love)t.setDaemon(True) # 设置守护线程ti.sleep(0.1)t.start() 详细分析这段代码主要实现了在屏幕中央显示一个大红心,并在屏幕上随机显示多个“我爱你”的窗口。
首先导入了 tkinter 用于 GUI 开发,random 用于生成随机数,threading 用于多线程处理,time 用于线程睡眠。
接下来定义了两个函数 Heart 和 Love 分别用于显示大红心和“我爱你”窗口。在 Heart 函数中,通过 root.winfo_screenwidth() 和 root.winfo_screenheight() 获取了屏幕的宽度和高度,然后将窗口设置为全屏状态。在窗口中显示了一个宽度为 300,高度为 20 的红色心形,字体为 “Comic Sans MS”,大小为 500。在 Love 函数中,同样通过 root.winfo_screenwidth() 和 root.winfo_screenheight() 获取了屏幕的宽度和高度,然后通过 random 生成随机的 x 和 y 坐标,创建了一个宽度为 200,高度为 50 的窗口,其中显示了 “I LOVE YOU!” 的字样,字体为 “Comic Sans MS”,大小为 15,字体颜色为白色,背景颜色为粉色。
最后,在主程序中先使用多线程启动了 Heart 函数,将其设置为守护线程;然后循环启动 50 个 Love 线程,将其也设置为守护线程,并在每次启动之间停顿 0.1 秒。整个程序在所有 Love 线程启动后结束运行。
总的来说,这段代码是一段简单的表白程序,通过窗口的显示来表达爱意。代码比较简单易懂,用到了多线程和随机数的知识。
系列文章 Python表白系列文章目录直达链接1无法拒绝的表白界面2满屏表白代码https://want595.blog.csdn.net/article/details/1347447113跳动的爱心https://want595.blog.csdn.net/article/details/1347441914漂浮的爱心5爱心光波6流星雨7玫瑰花