![](/img/trans.png)
[英]TKinter tkFileDialog.askopenfilename Always behind other windows
[英]how do I get Tkinter askopenfilename() to open on top of other windows?
我正在运行一个提示用户输入文件的脚本。 除了打开的文件浏览器外,没有 gui。 我有 2 个选项:浏览文件,或使用askdirectory()
选择整个文件夹。 后者在所有其他窗口之上打开,但第一个在所有窗口下打开,我必须最小化其他窗口才能找到它。
这是我用于这些操作的方法
from Tkinter import Tk
from tkFileDialog import askdirectory, askopenfilename
root = Tk()
root.withdraw()
self.inpath = askdirectory() # To open entire folder
Path = askopenfilename() # Open single file
root.destroy() # This is the very last line in my main script.
这是我的代码中与 Tk 相关的所有内容。 askdirectory
在顶部打开, askopenfilename
没有。
有没有办法强制它在顶部打开?
root.wm_attributes('-topmost', 1)
为我做了。 老实说,我在另一个 SO 线程中找到了它:-)。
我有同样的问题。 对我来说,它适用于:
file = filedialog.askopenfilename(parent=root)
因此,文件对话框位于顶层窗口前面,无需取消注释root.attributes("-topmost", True)
我在当前窗口下方打开文件对话框窗口时遇到了同样的问题,但我无法用您的代码重现该问题(在 Python 2 或 3 中)。
这是发生问题的最小示例(上下文是 Windows 10、Python 3,从空闲调用脚本,并注意input
函数:
文件对话框打开如下:
from tkinter import filedialog, Tk
root = Tk()
root.withdraw()
input("\nType anything> ")
file = filedialog.askopenfilename()
要在顶部打开文件对话框, root.lift()
或root.attributes("-topmost", True)
都可以工作(但后者是特定于 Windows 的)
from tkinter import filedialog, Tk
root = Tk()
#root.attributes("-topmost", True) # this also works
root.lift()
root.withdraw()
input("\nType anything> ")
file = filedialog.askopenfilename()
我想分享以下几行在我的情况下非常有效。 但我必须同时使用 window.wm_attributes('-topmost', 1) 和 window=parent 才能完成这项工作,见下文:
import tkinter as tk
from tkinter import filedialog
window = tk.Tk()
window.wm_attributes('-topmost', 1)
window.withdraw() # this supress the tk window
filename = filedialog.askopenfilename(parent=window,
initialdir="",
title="Select A File",
filetypes = (("Text files", "*.txt"), ("All files", "*")))
# Here, window.wm_attributes('-topmost', 1) and "parent=window" argument help open the dialog box on top of other windows
我正在运行 python 3.x,因此代码有所不同,但两者都为我打开了。 试着给它焦点,它应该放在上面。
self.inpath.focus()
我不确定它是否会起作用,因为我无法重现该问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.