如何给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的文件选择对话框也会打开。但问题是,这个文件选择对话框在终端的后面。
有没有办法让终端不显示,或者确保文件选择对话框在最上面呢?
谢谢,
Wes
6 个回答
5
上面其他的回答对我来说并不是每次都有效。最后,我找到的解决办法是添加两个属性:-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()
6
使用AppleEvents来让Python获得焦点。例如:
import os
os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')
16
如果你是通过谷歌找到这里的(就像我一样),那么我这里有一个小技巧,可以在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()