【问题标题】:How to give Tkinter file dialog focus如何给 Tkinter 文件对话框焦点
【发布时间】:2011-03-23 11:01:06
【问题描述】:

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

有没有办法抑制终端或确保文件对话框结束?

谢谢, 韦斯

【问题讨论】:

  • 这可能会有所帮助:stackoverflow.com/questions/1810497/…
  • 谢谢,我会考虑长期使用它。现在这个程序非常简单并且迭代很快。我正在寻找一种快速解决这个烦恼的方法。

标签: python tkinter


【解决方案1】:

对于任何通过 Google 来到这里的人(就像我一样),这里有一个我设计的 hack,它适用于 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) 使窗口不可见
【解决方案2】:

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

import os

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

【讨论】:

  • Tk 机制(在根窗口或父窗口上似乎归结为focus_set()focus_force())可能适用于Linux 或其他地方,但它们不适用于Mac OS X。这是我发现的唯一适用于 Mac 的东西。
【解决方案3】:

我在 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。
  • 文件类型。比如 xls 或 txt
  • 这几乎成功了,我必须在“root.overrideredirect(True)”之前添加“root.update_idletasks()”
【解决方案4】:

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

parent=root 足以让tkFileDialog 在上面。这只是意味着您的根不在顶部,尝试使根在顶部并自动tkFileDialog 将占据父级的顶部。

【讨论】:

    【解决方案5】:

    试试 focus_set 方法。有关更多信息,请参阅PythonWare'sAn Introduction to Tkinter 中的Dialog Windows 页面。

    【讨论】:

    • 谢谢。我读了一遍。我不确定如何在内置的 TK 文件对话框窗口中使用 set_focus() 方法?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    相关资源
    最近更新 更多