如何给Tkinter文件对话框重点

时间:2010-07-30 20:43:30

标签: python tkinter

我正在使用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文件对话框打开。 问题是文件对话框在终端后面。

有没有办法压制终端或确保文件对话框最终显示?

谢谢, 韦斯

5 个答案:

答案 0 :(得分:11)

对于任何通过谷歌来到这里的人(就像我一样),这里有一个我设计的黑客,它适用于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()

答案 1 :(得分:5)

使用AppleEvents将重点放在Python上。例如:

import os

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

答案 2 :(得分:1)

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

parent=root就足以让tkFileDialog位于最前面。它只是意味着你的root不在最顶层,尝试在root上创建root并自动tkFileDialog将占据父级的顶部。

答案 3 :(得分:1)

我在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()

答案 4 :(得分:0)

尝试使用focus_set方法。有关更多信息,请参阅Dialog Windows PythonWare's中的An Introduction to Tkinter页。

相关问题