python满屏飘字代码
抖音上很火的满屏飘字代码,我进行了优化,效果很好:

需要的朋友自取,你只需要下载一个代码编辑器就能直接运行,可以参考python的相关安装链接。
import tkinter as tk import random import time import threading import math from threading import Lock import sys # List of positive messages (in Chinese) messages = { # 一般关心语句 "一般": [ "梦想成真", "保持好心情", "早点休息", "每天都要元气满满", "多喝水哦~", "金榜题名", "今天过得开心", "记得吃水果", "别熬夜", "天凉了,多穿衣服", "愿所有烦恼都消失", "好好爱自己", "顺顺利利", "期待下一次见面", "想你了", "注意休息", "照顾好自己" ], # 家人关心语句 "家人": [ "爸妈永远爱你", "家里一切都好", "记得常回家看看", "家是永远的港湾", "家人永远支持你", "妈妈做了你爱吃的菜", "家人想念你", "记得打电话给爸妈", "一家人最重要的是健康", "家人的爱是最温暖的" ], # 恋人关心语句 "恋人": [ "你是我最大的幸福", "想你的每一天", "你的笑容真美", "永远爱你", "你是我生命中的阳光", "今天也很想你", "和你在一起的时光最珍贵", "你今天辛苦了", "你是我的全世界", "做个甜甜的梦" ], # 朋友关心语句 "朋友": [ "有空一起喝一杯", "谢谢你一直的陪伴", "朋友一生一起走", "真高兴认识你", "友谊长存", "你的朋友永远支持你", "朋友间无需客气", "你是值得骄傲的人", "为你加油", "你永远不是一个人" ], # 鼓励语句 "鼓励": [ "相信自己,你可以的!", "今天的付出,明天会有收获", "坚持就是胜利", "你比想象中更强大", "困难只是暂时的", "不要放弃,继续努力", "勇敢面对挑战", "每一步都是进步", "你的努力不会白费", "成功就在前方等着你" ] } # Colors for windows - associated with message categories colors = { "一般": ["#FFB6C1", "#E6E6FA", "#FFDAB9"], # Light pink, Lavender, Peach puff "家人": ["#98FB98", "#90EE90", "#7FFFD4"], # Pale green shades "恋人": ["#FFC0CB", "#FFB6C1", "#FF69B4"], # Pink shades "朋友": ["#87CEFA", "#ADD8E6", "#B0E0E6"], # Blue shades "鼓励": ["#FFD700", "#FFFF00", "#FFA07A"] # Gold, Yellow, Light salmon } # Additional decoration characters decorations = ["♥", "♡", "✿", "❀", "✨", "☆", "✺", "❤", "♬", "☀", "☺", "♪"] class MessageApp: def __init__(self): # Main app settings self.windows = [] # Store window references self.windows_lock = Lock() # Add lock for thread safety self.screen_width = 1200 # Default screen width self.screen_height = 800 # Default screen height self.running = True # Flag to control animation threads self.main_window = None # Main window reference # Try to get actual screen dimensions try: temp_root = tk.Tk() self.screen_width = temp_root.winfo_screenwidth() self.screen_height = temp_root.winfo_screenheight() temp_root.destroy() except Exception: pass def create_window(self, row=None, col=None): """Create a new popup window with a message""" if not self.running: return None try: # Create new window window = tk.Toplevel(self.main_window) window.overrideredirect(True) # Remove window decorations # Random width and height - 调整大小以适应更多窗口 width = random.randint(120, 200) height = random.randint(45, 85) # 随机位置 - 总是完全随机 x = random.randint(0, self.screen_width - width) y = random.randint(0, self.screen_height - height) # 偶尔让窗口出现在屏幕边缘以外,确保覆盖整个屏幕 if random.random() < 0.2: # 增加到20%的几率 edge = random.choice(["top", "bottom", "left", "right"]) if edge == "top": y = -20 elif edge == "bottom": y = self.screen_height - height + 20 elif edge == "left": x = -20 elif edge == "right": x = self.screen_width - width + 20 # 有小概率将窗口放在屏幕中间区域 if random.random() < 0.1: # 10%的几率 center_width = self.screen_width // 3 center_height = self.screen_height // 3 x = self.screen_width // 2 - center_width // 2 + random.randint(-50, 50) y = self.screen_height // 2 - center_height // 2 + random.randint(-50, 50) window.geometry(f"{width}x{height}+{x}+{y}") # Random message - select from a random category category = random.choice(list(messages.keys())) message = random.choice(messages[category]) # Select a color that matches the category bg_color = random.choice(colors[category]) window.configure(bg=bg_color) # Add decoration to message if random.random() > 0.5: # 50% chance of having decoration prefix = random.choice(decorations) + " " + random.choice(decorations) decorated_message = prefix + message + suffix else: decorated_message = message # Create label with animation capability label = tk.Label(window, text=decorated_message, font=("SimHei", 14), bg=bg_color) # Store references for animation window.label = label window.message = decorated_message label.pack(expand=True, fill="both") # Add close button close_button = tk.Button(window, text="×", command=self.close_all, font=("Arial", 8), bg=bg_color, bd=0, highlightthickness=0) close_button.place(x=width-20, y=5) # Bind events - clicking anywhere closes all windows window.bind("<Button-1>", lambda e: self.close_all()) # Add labels to handle click events too label.bind("<Button-1>", lambda e: self.close_all()) # Store window reference (thread-safe) with self.windows_lock: self.windows.append(window) return window except Exception as e: print(f"Error creating window: {e}") return None # Removed drag functions since we now close on click def is_window_valid(self, window): """Thread-safe check if window is valid and in our list""" if not self.running: return False try: # Check if window is in our list with self.windows_lock: is_in_list = window in self.windows # Check if window exists and is not destroyed if not is_in_list: return False try: exists = window.winfo_exists() return exists except (tk.TclError, Exception): return False except Exception: return False def close_all(self): """Close all windows and stop the application""" try: # Set flag to stop all animations self.running = False # Copy window list to avoid modification during iteration with self.windows_lock: windows_to_close = self.windows.copy() # Disable all animations first for window in windows_to_close: try: # Remove all scheduled tasks for this window if hasattr(window, 'after_ids'): for after_id in window.after_ids: try: window.after_cancel(after_id) except Exception: pass except Exception: pass # Then destroy all windows for window in windows_to_close: try: window.destroy() except Exception: pass # Clear the windows list with self.windows_lock: self.windows = [] # Exit application if requested if self.main_window and self.main_window.winfo_exists(): self.main_window.quit() except Exception as e: print(f"Error in close_all: {e}") # Force exit as a last resort sys.exit(0) def fade_in(self, window): """Create an ultra-fast fade-in animation effect for windows""" if not self.running or window is None: return try: window.attributes('-alpha', 0.0) # Start completely transparent # 极速淡入效果 - 只用更少的步骤 window.after_ids = [] # Store animation IDs def step_fade(i): if not self.running or not self.is_window_valid(window): return try: # 只用5步完成淡入,而不是10步 alpha = i / 5 window.attributes('-alpha', alpha) if i < 5: # 超快淡入 - 只间隔5ms (原来是15ms) after_id = window.after(5, lambda: step_fade(i+1)) if hasattr(window, 'after_ids'): window.after_ids.append(after_id) else: # 大幅降低动画概率,减少CPU负担 if random.random() > 0.9 and self.running: self.start_pulse_animation(window) if random.random() > 0.9 and self.running: self.start_float_animation(window) except Exception: pass # Start the fade-in animation step_fade(0) except Exception: pass def start_pulse_animation(self, window): """Start pulse animation using after() instead of threading""" if not self.running or window is None: return try: if not hasattr(window, 'after_ids'): window.after_ids = [] # Store animation state window.pulse_data = { 'cycle': 0, 'step': 0, 'max_cycles': 20 # 大幅减少动画周期以降低CPU负担 } def pulse_step(): if not self.running or not self.is_window_valid(window): return try: # Get current state data = window.pulse_data i = data['step'] # Subtle size change animation factor = 1 + 0.03 * math.sin(i / 3) if hasattr(window, 'label') and window.winfo_exists(): try: current_font = window.label.cget("font") if isinstance(current_font, str): font_parts = current_font.split() if len(font_parts) >= 2: font_name = font_parts[0] base_size = 14 new_size = int(base_size * factor) window.label.config(font=(font_name, new_size)) except Exception: pass # Update animation state data['step'] = (i + 1) % 20 if data['step'] == 0: data['cycle'] += 1 # Continue animation if cycles remain if data['cycle'] < data['max_cycles'] and self.running: after_id = window.after(100, pulse_step) window.after_ids.append(after_id) except Exception: pass # Start the animation after_id = window.after(100, pulse_step) window.after_ids.append(after_id) except Exception: pass def start_float_animation(self, window): """Start float animation using after() instead of threading""" if not self.running or window is None: return try: if not hasattr(window, 'after_ids'): window.after_ids = [] # Store animation state and starting position try: start_x = window.winfo_x() start_y = window.winfo_y() window.float_data = { 'start_x': start_x, 'start_y': start_y, 'cycle': 0, 'step': 0, 'max_cycles': 20 # 减少动画周期以降低CPU负担 } except Exception: return def float_step(): if not self.running or not self.is_window_valid(window): return try: # Get current state data = window.float_data i = data['step'] # Subtle position change dx = 5 * math.sin(i / 5) dy = 5 * math.sin(i / 7) try: new_x = int(data['start_x'] + dx) new_y = int(data['start_y'] + dy) window.geometry(f"+{new_x}+{new_y}") except Exception: return # Update animation state data['step'] = (i + 1) % 40 if data['step'] == 0: data['cycle'] += 1 # Continue animation if cycles remain if data['cycle'] < data['max_cycles'] and self.running: after_id = window.after(50, float_step) window.after_ids.append(after_id) except Exception: pass # Start the animation after_id = window.after(50, float_step) window.after_ids.append(after_id) except Exception: pass # Removed delayed_window function as we now use sequential windows def continuous_popup_check(self): """Schedule continuous popup creation using after() instead of threading""" if not self.running: return def create_new_popup(): if not self.running: return # Create a new window if we're under the limit with self.windows_lock: window_count = len(self.windows) # 增加窗口数量上限到1000 if window_count < 1000: # 始终创建新窗口,概率为100% window = self.create_window() if window: self.fade_in(window) # 使用固定的时间间隔,实现匀速弹出效果 delay_ms = 100 # 固定为100ms的间隔,每秒弹出10个窗口 if self.main_window and self.running: self.main_window.after(delay_ms, create_new_popup) # Start the first popup check - initial delay of 3 seconds if self.main_window: self.main_window.after(3000, create_new_popup) def create_random_windows(self): """Initialize windows one by one to fill the screen""" if not self.running: return # Create windows one by one with sequential timing instead of random delays self.create_sequential_windows(0) # 在初始窗口创建的同时立即开始持续创建 # 不等待,立即启动连续弹窗 self.main_window.after(500, self.continuous_popup_check) def create_sequential_windows(self, index): """Create windows one after another in rapid sequence""" if not self.running or index >= 100: # 初始创建100个窗口 return # 完全随机位置 - 不使用网格布局 # 创建新窗口 - 使用完全随机位置 window = self.create_window() # 不传入row和col参数 if window: self.fade_in(window) # 使用匀速间隔创建初始窗口 delay = 50 # 固定50ms的间隔,匀速创建 if self.main_window and self.running: self.main_window.after(delay, lambda: self.create_sequential_windows(index + 1)) def start(self): """Start the application""" try: # Reset the running flag self.running = True # Create the main window self.main_window = tk.Tk() self.main_window.withdraw() # Hide the main window # Add a protocol handler for when the window is closed self.main_window.protocol("WM_DELETE_WINDOW", self.close_all) # Add keyboard shortcuts to exit self.main_window.bind("<Escape>", lambda e: self.close_all()) # ESC to exit self.main_window.bind("<Control-c>", lambda e: self.close_all()) # Ctrl+C to exit # Start creating random windows self.create_random_windows() # Use exception handling for the main loop try: self.main_window.mainloop() except Exception as e: print(f"Error in mainloop: {e}") except Exception as e: print(f"Error starting application: {e}") finally: # Clean up on exit self.running = False self.close_all() print("Application closed") if __name__ == "__main__": app = MessageApp() app.start()