如何判断Tk中是否已有指定标题的窗口打开?

7 投票
2 回答
1633 浏览
提问于 2025-04-11 00:11

我写了一个简单的Python脚本,它会弹出一个消息框,里面显示在命令行中输入的文本。我想让它只在之前的窗口没有打开的时候才弹出来。

from Tkinter import *
import tkMessageBox

root = Tk()
root.withdraw() 

# TODO not if a window with this title exists
tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))

有没有什么办法可以检查这个呢?

2 个回答

0

之前的回答是根据你提供的代码来工作的。你说它不管用,是因为回答者遵循了“要简单和守规矩”的原则,他没有在代码中添加root.mainloop(),而你的问题中也没有提到这点。

如果你加上这行代码,由于事件循环的原因,你应该测试一下确切的字符串“withdrawn”,方法如下:

import tkinter as tk
from tkinter import messagebox
import sys


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

if 'withdrawn' != root.state():
   messagebox.showinfo("Key you!", sys.argv[1:])


root.mainloop()

注意:不要运行这段代码,否则你的终端会卡住。为了避免这种麻烦,你需要重置窗口状态,可以使用root.state("normal"),这样会让消息框消失,就像你点击了确认按钮一样;或者使用root.iconify(),这样你可以通过右键点击出现在操作系统任务栏上的tkinter图标来停止终端卡住的情况。

2

我想你想要的是:

if 'normal' != root.state():
    tkMessageBox.showinfo("Key you!", " ".join(sys.argv[1:]))

撰写回答