如何连接到tkinters文件对话框?

2024-06-28 21:00:01 发布

您现在位置:Python中文网/ 问答频道 /正文

使用python 3tkinter我试图创建一个文件对话框,允许用户选择现有目录(exists=True)。你知道吗

当他们选择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

如果我缺少什么,请分享:-)


Tags: 文件pathimportself目录truetitleos
1条回答
网友
1楼 · 发布于 2024-06-28 21:00:01

这是可行的,但是有人看到递归调用有问题吗?你知道吗

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

相关问题 更多 >