如何用Python在屏幕上层动态叠加、编辑及移除文本
Solution: Dynamic Overlay Text with Real-Time Updates
Tkinter Implementation (Cross-Platform)
Your existing Tkinter code likely failed because you used a blocking while True loop that froze the UI, or created new widgets instead of updating existing ones. Here's a working fix:
1. Setup Transparent, Always-on-Top Window
import tkinter as tk root = tk.Tk() root.attributes('-topmost', True) # Stay above all windows root.attributes('-transparentcolor', root['bg']) # Make background see-through root.overrideredirect(True) # Remove title bar/borders root.geometry("250x60+150+150") # Size and position # Create a single label for dynamic text updates sum_display = tk.Label(root, text="", font=("Segoe UI", 24), fg="#ff0000") sum_display.pack(expand=True)
2. Integrate Non-Blocking Update Logic
Use Tkinter's after() method to run your screen-reading logic without freezing the UI:
def update_total(): # Replace this with your actual screen number detection code detected_numbers = [15, 25, 40] # Example values total = sum(detected_numbers) if detected_numbers else 0 # Update or clear the text if total > 0: sum_display.config(text=f"Total: {total}") else: sum_display.config(text="") # Schedule next update (100ms = 0.1s, adjust for your needs) root.after(100, update_total) # Start the update loop update_total() root.mainloop()
3. Handle Full-Screen Windows (Windows)
If the overlay gets hidden behind full-screen apps on Windows, add these attributes:
root.attributes('-toolwindow', True) root.attributes('-disabled', True)
Win32 API Implementation (Windows Only)
For Windows-specific control, use the Win32 API to create a layered overlay window:
import win32gui import win32api import win32con import time class Overlay: def __init__(self): self.hwnd = self.create_window() def create_window(self): wc = win32gui.WNDCLASS() wc.lpfnWndProc = self.wnd_proc wc.lpszClassName = "ScreenSumOverlay" wc.hInstance = win32api.GetModuleHandle(None) win32gui.RegisterClass(wc) return win32gui.CreateWindowEx( win32con.WS_EX_LAYERED | win32con.WS_EX_TRANSPARENT | win32con.WS_EX_TOPMOST, "ScreenSumOverlay", "", win32con.WS_POPUP, 150, 150, 250, 60, 0, 0, wc.hInstance, None ) def wnd_proc(self, hwnd, msg, wparam, lparam): if msg == win32con.WM_PAINT: hdc = win32gui.GetDC(hwnd) # Replace with your calculated total current_total = 80 if current_total > 0: win32gui.TextOut(hdc, 20, 15, f"Total: {current_total}", len(f"Total: {current_total}")) win32gui.ReleaseDC(hwnd, hdc) return 0 return win32gui.DefWindowProc(hwnd, msg, wparam, lparam) def refresh(self): win32gui.InvalidateRect(self.hwnd, None, True) win32gui.UpdateWindow(self.hwnd) # Run the overlay overlay = Overlay() while True: # Insert your screen number reading logic here overlay.refresh() time.sleep(0.1)
内容的提问来源于stack exchange,提问作者Tobias Christensen
相关产品推荐
相关产品推荐

