如何给 Tkinter 文件对话框焦点 [英] How to give Tkinter file dialog focus

查看:51
本文介绍了如何给 Tkinter 文件对话框焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 OS X.我双击我的脚本从 Finder 运行它.此脚本导入并运行下面的函数.

I'm using OS X. I'm double clicking my script to run it from Finder. This script imports and runs the function below.

我希望脚本显示 Tkinter 打开文件对话框并返回所选文件的列表.

I'd like the script to present a Tkinter open file dialog and return a list of files selected.

这是我目前所拥有的:

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 文件对话框打开.问题是文件对话框在终端后面.

I double click the script, terminal opens, the Tkinter file dialog opens. The problem is that the file dialog is behind the terminal.

有没有办法抑制终端或确保文件对话框在最上面?

谢谢,韦斯

推荐答案

对于通过 Google 来到这里的任何人(就像我一样),这里是我设计的一个在 Windows 和 Ubuntu 中都适用的 hack.就我而言,我实际上仍然需要终端,但只是希望对话框在显示时位于顶部.

For anybody that ends up here via Google (like I did), here is a hack I've devised that works in both Windows and Ubuntu. In my case, I actually still need the terminal, but just want the dialog to be on top when displayed.

# 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()

这篇关于如何给 Tkinter 文件对话框焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆