2015-09-26 30 views
1

使用python 3tkinter我試圖創建一個文件對話框,讓用戶選擇現有的目錄(exists=True)。如何鉤入tkinters FileDialog?

當他們選擇choose我想檢查目錄也是可讀的,我可以得到一個文件鎖。由於我的程序的其餘部分將依賴對路徑的讀取訪問,並且這個過程需要很長時間。他們選擇cancel

乳清我想對話框關閉。

File Dialogue

如果該目錄不readable我想要的文件的對話顯示askretry消息。點擊Retry將取回他們選擇一個文件。點擊Cancel將關閉對話。

Ask Retry Dialogue

在我第一次嘗試,一個新手tkinter,我創造了這個:

import os 
from tkinter import filedialog 
from tkinter import messagebox 


class OpenDialog(object): 
    def __init__(self): 
     self.directory_path = None 
     self.dialog_title ="Photos Directory Selection" 

    def ask_for_directory(self): 
     while not self.directory_path: 
      self.directory_path = filedialog.askdirectory(mustexist=True, title=self.dialog_title) 
      if not os.access(os.path.dirname(self.directory_path), os.F_OK): 
       self.directory_path = None 
       if not messagebox.askretrycancel(title=self.dialog_title, message="Can't read directory."): 
        break 

雖然它並不完美。它不會讓你cancel文件對話。

但是,唉,我想我可能鉤到文件對話框本身......

我只是不明白我怎麼能幹淨地鉤到FileDialogue類乾淨顯示askretry對話,並重覆上述過程。

filedialogue.py

如果有什麼我失蹤,請分享:-)

+0

爲什麼不等待從對話框返回,檢查路徑(如果用戶沒有取消),那麼只需要再次調用對話框? – jonrsharpe

+0

我認爲這個問題是'filedialog.askdirectory'返回的文件路徑,而不是'bool'。如果我可以單獨獲取'bool'和'file_path',那就可以工作。 – visc

+0

你期待什麼布爾值? – jonrsharpe

回答

-1

這工作,但沒有人看到遞歸調用的問題嗎?

def ask_for_directory(self): 
    self.directory_path = filedialog.askdirectory(mustexist=True, title=self.dialog_title) 
    if self.directory_path: 

     # Check that we have access to the path 
     if not os.access(self.directory_path, os.R_OK): 

      # If we don't have access 
      if messagebox.askretrycancel(title=self.dialog_title, message="Can't read directory."): 
       self.ask_for_directory() 

編輯:

這是我的例子,但修正工作...

def ask_for_directory(self): 
    while not self.directory_path: 
     self.directory_path = filedialog.askdirectory(mustexist=True, title=self.dialog_title) 
     if self.directory_path: 
      if not os.access(self.directory_path, os.R_OK): 
       self.directory_path = None 
       if not messagebox.askretrycancel(title=self.dialog_title, message="Can't read directory."): 
        break 
     else: 
      break