如何让Tkinter文件对话框获得焦点

15

我使用的是 OS X 操作系统。我在 Finder 中双击我的脚本以运行它。这个脚本导入并运行下面的函数。

我想让脚本呈现一个 Tkinter 打开文件对话框,并返回选择的文件列表。

这是我目前的代码:

def open_files(starting_dir):
    """Returns list of filenames+paths given starting dir"""
    import Tkinter
    import tkFileDialog

    root = Tkinter.Tk()
    root.withdraw()  # Hide root window
    filenames = tkFileDialog.askopenfilenames(parent=root,initialdir=starting_dir)
    return list(filenames)

我双击脚本后,终端打开,然后Tkinter文件对话框就出现了。 问题在于文件对话框在终端的后面。

有没有办法隐藏终端或确保文件对话框显示在最上面?

谢谢, Wes


这可能会有所帮助:https://dev59.com/iErSa4cB1Zd3GeqPXIu1 - Gary Kerr
谢谢,我会在长期使用中考虑使用。现在这个程序非常简单,迭代速度很快。我想找到一个快速解决这个问题的方法。 - Wes
6个回答

15

对于通过谷歌(如我所做的)来到这里的任何人,这是一个我想出的方法,可以在Windows和Ubuntu中使用。在我的情况下,我仍然需要终端,但只是希望显示对话框时它在顶部。

# Make a top-level instance and hide since it is ugly and big.
root = Tkinter.Tk()
root.withdraw()

# Make it almost invisible - no decorations, 0 size, top left corner.
root.overrideredirect(True)
root.geometry('0x0+0+0')

# Show window again and lift it to top so it can get focus,
# otherwise dialogs will end up behind the terminal.
root.deiconify()
root.lift()
root.focus_force()

filenames = tkFileDialog.askopenfilenames(parent=root) # Or some other dialog

# Get rid of the top-level instance once to make it actually invisible.
root.destroy()

使用以下代码:root.attributes('-alpha', 0.3) 可以使窗口变为透明。 - Tom Fuller

6
使用AppleEvents将焦点放在Python上。例如:
import os

    os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')

1
Tk机制(似乎归结为在根或父窗口上使用focus_set()focus_force())可能适用于Linux或其他地方,但它们在Mac OS X上不起作用。这是我发现在Mac上可行的唯一方法。 - Jonathan Eunice

5

以上其他答案对我来说并不总是100%有效。最终,对我有效的方法是添加2个属性:-alpha和-topmost。这将强制窗口始终保持在顶部,这正是我想要的。

import tkinter as tk

root = tk.Tk()
# Hide the window
root.attributes('-alpha', 0.0)
# Always have it on top
root.attributes('-topmost', True)
file_name = tk.filedialog.askopenfilename(  parent=root, 
                                            title='Open file',
                                            initialdir=starting_dir,
                                            filetypes=[("text files", "*.txt")])
# Destroy the window when the file dialog is finished
root.destroy()

4

我有一个问题,就是Spyder后面的窗口问题:

root = tk.Tk()
root.overrideredirect(True)
root.geometry('0x0+0+0')
root.focus_force()
FT = [("%s files" % ftype, "*.%s" % ftype), ('All Files', '*.*')]
ttl = 'Select File'
File = filedialog.askopenfilename(parent=root, title=ttl, filetypes=FT)
root.withdraw()

什么是 ftype?我得到了未定义的名称 ftype。 - Joshua Stafford
文件类型。例如 xls 或 txt - user1889297
这几乎可以工作,但在“root.overrideredirect(True)”之前必须添加“root.update_idletasks()”。 - Ta946

1

filenames = tkFileDialog.askopenfilenames(parent=root,initialdir=starting_dir)

这段代码用于打开文件选择器,parent=root 表示把文件选择器放在 root 窗口的最上层。如果 root 窗口已经在最上层,则文件选择器会自动置于其上方。initialdir=starting_dir 则表示文件选择器默认打开的文件夹路径为 starting_dir。请注意保留代码中的 HTML 标签。

0

谢谢。我已经阅读了它。我不确定如何在内置的TK文件对话框窗口上使用set_focus()方法? - Wes

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接