- Python语言讨论与实践
Python tkinter窗口死循环-慎用
- 2024-12-8 17:31:53 @
#下面有下载途径
#按'q'键,停止程序!!!
import tkinter as tk
from tkinter import messagebox
import threading
import string
import random
class InfinitePopups:
def __init__(self, max_popups=100):
self.max_popups = max_popups
self.popup_count = 0
self.windows = []
self.running = True # 控制弹窗线程的运行状态
def get_screen_size(self):
# 获取屏幕的宽度和高度
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
return screen_width, screen_height
def create_popup(self):
if self.popup_count < self.max_popups and self.running:
# 生成随机乱码
length = random.randint(5, 20)
garbage = ''.join(random.choices(string.ascii_letters + string.punctuation, k=length))
# 创建新窗口
window = tk.Toplevel()
window.title("给齐的礼物!")
window.attributes("-topmost", True) # 窗口置顶
# 设置弹窗大小为屏幕分辨率
screen_width, screen_height = self.get_screen_size()
window.geometry(f"{screen_width}x{screen_height}")
# 添加标签显示乱码
label = tk.Label(window, text=garbage, font=("Arial", 12), fg="red")
label.pack(expand=True)
# 存储窗口引用
self.windows.append(window)
# 更新计数器
self.popup_count += 1
def start_popups(self):
while self.running:
self.create_popup()
# 设置弹窗间隔时间(毫秒)
time_between_popups = 10 # 0.1秒
threading.Event().wait(time_between_popups / 1000)
def on_key_press(self, event):
if event.keysym.lower() == 'q':
self.stop()
def start(self):
# 创建主窗口
self.root = tk.Tk()
self.root.title("给齐的礼物")
self.root.geometry("300x100")
self.root.attributes("-topmost", True)
# 添加提示信息
info_label = tk.Label(self.root, text="程序正在运行。按 'q' 键停止。", font=("Arial", 12))
info_label.pack(pady=10)
# 添加停止按钮
stop_button = tk.Button(self.root, text="停止", command=self.stop, font=("Arial", 12))
stop_button.pack(pady=10)
# 绑定键盘事件
self.root.bind('<Key>', self.on_key_press)
# 创建并启动弹窗线程
popup_thread = threading.Thread(target=self.start_popups, daemon=True)
popup_thread.start()
# 运行主循环
self.root.mainloop()
def stop(self):
print("停止程序...")
self.running = False # 停止弹窗线程
for window in self.windows:
window.destroy() # 关闭所有弹窗
self.root.destroy() # 关闭主窗口
if __name__ == "__main__":
app = InfinitePopups(max_popups=99999999999999999999999999999999999999999999999999999999999999999999999999999) # 设置最大弹窗数量
app.start()
更新后的程序↑↑↑卐
- 更新后,程序可以获取本程序所在的U盘盘符,可以后期自行开发自动运行功能。
0 条评论
目前还没有评论...