Tkinter在几秒钟后销毁窗口,除非检测到特定事件

2024-04-25 06:42:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个python脚本,使用Tkinter和i3ipc在i3窗口管理器中更改不同窗口之间的焦点时显示一个窗口。对于那些不知道这是什么的人,忽略这一部分,我只使用一个函数来获得聚焦窗口的名称,我确信这是有效的。我会在下面发布代码。在

#/usr/bin/env python

import i3ipc
import tkinter as tk

window_width = 150
window_height = 50

i3 = i3ipc.Connection()

root = tk.Tk()
root.withdraw()

current_window = None


# This function gets the name of the focused window.
def find_focused():
    focused = i3.get_tree().find_focused()
    window_name = focused.window_class
    return window_name


def create_new(root):
    global current_window
    if current_window is not None:
        current_window.destroy()
    current_window = tk.Toplevel(root)
    return current_window


def kill(root, window):
    root.quit()
    window.after(450, window.destroy())
    window.update()


"""
This is the closests I came to a solution (in my mind)

def eliminate(root, window):
    window.destroy()
    root.update()

def alternative_kill(root, window):
    window.after(450, lambda: eliminate(root, window))
    root.quit()
"""


def show_window(i3, e):

    print("ciclo")

    window_name = find_focused()

    window = create_new(root)
    window.overrideredirect(True)

    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()
    x = (screen_width/2) - (window_width/2)
    y = (screen_height/2) - (window_height/2)

    window.geometry("%dx%d+%d+%d" % (window_width, window_height, x, y))

    canvas = tk.Canvas(window)
    canvas.pack()
    canvas.create_text(window_width/2, window_height/2, text=window_name)

    window.after(50, lambda: kill(root, window))
    # alternatively, I'd call alternative_kill instead of this
    root.mainloop()


i3.on("window::focus", show_window)

i3.main()

这是我的问题。在当前代码的实现中,当我切换焦点时,一个名为的窗口会在450毫秒后出现和消失。但是,如果我多次快速更改焦点(速度超过450毫秒),因为每个窗口需要450毫秒才能被销毁并创建一个新窗口,那么它们的名称显示就会滞后。因此,我需要一些东西来破坏窗口,并在焦点事件发生时立即显示新窗口,否则在450毫秒后将其销毁。

我尝试过用可选的\u kill切换kill函数(参见代码)。我想我可以用根。退出()退出主循环,使其准备好接收更多事件,同时调用消除销毁窗口并根目录更新()来展示它。显然,这不起作用,当运行该代码时,窗口只在第一次焦点改变后显示,并且它停止工作(如中所示,程序继续运行,但显然没有收到进一步的事件)。在

编辑:重申一下,我的目标是:在窗口出现450毫秒后将其销毁,除非同时发生事件(焦点改变),在这种情况下,窗口应立即销毁,并应出现一个新窗口。在


Tags: 代码namedef事件rootcurrentwindowwidth