事情的起因是 刷抖音看到有人用python代码写了一个“浪漫便签”的程序。具体就是运行后一个接一个的便签样子的窗口弹出来里面显示的是很治愈有很浪漫的语录。我认为很有意思。这是效果
源代码如下
import tkinter as tk
import random
import threading
import time
import sys
# 全局变量
windows = []
max_windows = 30
stop_program = False # 控制程序停止的标志
def show_warm_tip():
global stop_program
# 如果程序已停止或窗口数量已达上限,则返回
if stop_program or len(windows) >= max_windows:
return
window = tk.Toplevel() # 使用Toplevel而不是Tk
windows.append(window)
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
window_width = 250
window_height = 60
x = random.randrange(0, screen_width - window_width)
y = random.randrange(0, screen_height - window_height)
window.title('温馨提示')
window.geometry(f"{window_width}x{window_height}+{x}+{y}")
tips = [
"多喝水哦~", "保持微笑呀", "每天都要元气清清",
"记得吃水果", "保持好心情", "好好爱自己", "我想你了",
"梦想成真", "期待下一次见面", "金榜题名",
"顺顺利利", "早点休息", "愿所有烦恼都消失",
"别熬夜", "今天过得开心嘛", "天冷了, 多穿衣服"
]
tip = random.choice(tips)
bg_colors = [
'lightpink', 'skyblue', 'lightblue', 'lightsteelblue', 'powderblue',
'lightcyan', 'aliceblue', 'azure', 'lightgreen', 'lavender',
'lightyellow', 'plum', 'coral', 'bisque', 'aquamarine',
'mistyrose', 'honeydew', 'lavenderblush', 'oldlace'
]
bg = random.choice(bg_colors)
label = tk.Label(
window,
text=tip,
bg=bg,
font=('微软雅黑', 16),
width=30,
height=3
)
label.pack()
window.attributes('-topmost', True)
def on_space(event):
global stop_program
stop_program = True
# 关闭所有窗口
for win in windows[:]: # 使用副本遍历
try:
win.destroy()
except:
pass
windows.clear()
# 强制退出程序
import os
os._exit(0)
def on_closing():
if window in windows:
windows.remove(window)
window.destroy()
# 为每个窗口绑定空格键
window.bind('<KeyPress-space>', on_space)
window.focus_set() # 确保窗口能接收键盘事件
label.bind('<KeyPress-space>', on_space)
label.focus_set()
window.protocol("WM_DELETE_WINDOW", on_closing)
# 让窗口能够接收键盘输入
window.grab_set()
def check_and_create_windows():
"""检查并创建新窗口的函数"""
global stop_program
for i in range(1000):
if stop_program:
break
# 等待直到有空间创建新窗口
while len(windows) >= max_windows and not stop_program:
time.sleep(0.1)
if stop_program:
break
# 创建新窗口
show_warm_tip()
time.sleep(0.1) # 每秒创建一个新窗口
def main():
# 创建主窗口(隐藏)用于协调
root = tk.Tk()
root.withdraw() # 隐藏主窗口
# 为主窗口绑定空格键(这样即使没有焦点也能响应)
def on_global_space(event):
global stop_program
stop_program = True
for win in windows[:]:
try:
win.destroy()
except:
pass
windows.clear()
root.quit()
sys.exit()
root.bind('<KeyPress-space>', on_global_space)
# 在新线程中创建窗口
window_thread = threading.Thread(target=check_and_create_windows)
window_thread.daemon = True
window_thread.start()
# 显示使用说明
print("程序已启动!按空格键关闭所有窗口并退出程序。")
try:
root.mainloop()
except:
pass
if __name__ == '__main__':
main()自己可以修改它的窗口数量和时间感觉挺有趣的。
所以我在我的博客也加了一个类似的功能。就在主页最下面!!!