使用python打开目录对话框

时间:2014-07-27 02:17:17

标签: python multithreading tkinter multiprocessing

我正在尝试创建一个简单的文件对话框(最好是系统对话框),以便与本地服务器一起使用。

我无法使用Tkinter,因为它必须在子进程中运行,并且对话框在子进程中不会在Mac上保持打开状态。我不能使用线程,因为它最终会锁定。

有没有办法打开系统文件对话框而不使用Tkinter。

这个第一个文件是我想要的行为的自给自足的版本(在最后忽略无类型错误)

import Tkinter as tk
import threading
from tkFileDialog import askdirectory

def createDialog(communicationQueue):
    dia = Dialog(communicationQueue)
    dia.show()

class Dialog():

    def __init__(self, communicationQueue):
        self.communicationQueue = communicationQueue

        self.root = tk.Tk()
        self.root.overrideredirect(True)
        self.root.geometry("0x0+%d+%d" % (0, 0))
        self.root.withdraw()

        print 'creating root'
        print 'Root Created'

        self.root.update()
        self.root.deiconify()

        print 'asking directory'

        t = threading.Thread(target = self.show)
        t.daemon = True
        t.start()

        self.root.mainloop()
        print 'Directory found!'

    def show(self):
        print "show dialog"

        self.root.lift()
        name = askdirectory()
        print name
        self.communicationQueue.put(name)

if __name__ == '__main__':
    createDialog(None)
    print "Blocking!"

此文件与第一个文件组合尝试在子进程中使用Tkinter

import time

from multiprocessing import Process, Queue

def _createDialog(communicationQueue):
    from src.utilities import fileDialog
    fileDialog.createDialog(communicationQueue)
    print 'method!'

def showDirectoryDialog():
    """A blocking method that returns the directory path to a selected directory"""
    communicationQueue = Queue()
    p = Process(target = _createDialog, args = (communicationQueue,))
    p.start()

    count = 0
    while (communicationQueue.empty() and count <= 5):
        print "waiting"
        time.sleep(5)
        count = count + 1
    print 'Process should start'
    time.sleep(1)
    print 'Thread should have slept for 1 second'
    return name

if __name__ == '__main__':
    name = showDirectoryDialog()
    print name

如果有人可以在mac上工作或者至少弄清楚为什么根窗口保持打开状态,直到调用askDirectory(),我会非常感激

1 个答案:

答案 0 :(得分:0)

对于任何想要解决这个问题的人来说......

我最终使用了java。 Python文件对话框最终很难玩。它有一些非常奇怪的要求,并且要求您创建第二个窗口,然后必须隐藏它,以便它不会以对用户直观的方式满足我的需要。 (甚至对程序员来说也很直观)

Java具有易于使用的内置文件对话框系统。 http://docs.oracle.com/javase/7/docs/api/javax/swing/JFileChooser.html

但无论语言是什么,似乎mac都有问题从同一程序多次弹出文件对话框。这些问题不会出现在Windows上。

如果您的解决方案是跨平台的,那么这也是值得关注的。