我正在使用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)
Run Code Online (Sandbox Code Playgroud)
我双击脚本,终端打开,打开Tkinter文件对话框. 问题是文件对话框在终端后面.
有没有办法抑制终端或确保文件对话框最终?
谢谢,韦斯
小智 12
对于任何通过谷歌来到这里的人(就像我一样),这里有一个我设计的黑客,它可以在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()
Run Code Online (Sandbox Code Playgroud)
使用AppleEvents将重点放在Python上.例如:
import os
os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')
Run Code Online (Sandbox Code Playgroud)
小智 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()
Run Code Online (Sandbox Code Playgroud)