首页 > 解决方案 > 有没有办法在操作系统资源管理器中打开文件夹?

问题描述

我想要什么: 打开操作系统(windows)文件夹到一个特定的路径/目录/文件。我不想使用tkinter.filedialog。我正在寻找可以打开本机文件资源管理器的东西。我们用来在驱动器/磁盘上导航的相同。

我尝试了什么: 我在谷歌上搜索了多个关键词,但我找到的只是tkinter.filedialog。我知道这是可能的,因为 Windows 和 Linux 可以展示它。所以我想要的只是将那个用于特定路径。

代码: 代码并不复杂。我在一个项目上编辑一些文件元数据并进行调试,我一一列出了所有文件,如果一个文件出错,我制作一个按钮,它将在控制台上显示文件路径。现在我只需要那个按钮就可以打开该路径上的 OS 文件夹。

# Import
from tkinter import Tk, Button, Frame, filedialog
import os

# Global variables
root = Tk()
frm_status = None

# Main
class main:
    def __init__(self, master):
        global frm_status
        self.master = master

        master.wm_title("Example Code")
        master.wm_geometry("300x150")

        Button(master, text="Select files", command=lambda:Logic.AskPath("files")).pack(expand=False, fill="x", side="top")
        frm_status = Frame(master)
        frm_status.pack(expand=False, fill="x", side="top")

# Logc
class Logic:
    def AskPath(type):
        if type.lower() == "files":
            path = filedialog.askopenfilenames(initialdir="/", title="Select witch files...",
                                               filetypes=(("TEXT", "*.txt"), ("ALL FILES", "*.*")))
        elif type.lower() == "folder":
            # Somethin similar code here
            pass
        Logic.SmartDetect(path)

    def SmartDetect(path):
        # Make shore is not tuple and also a directory
        if isinstance(path, str) and os.path.isdir(path):
            # Some logics here to check compatibility for all files from path
            pass
        else:
            # In case on tuple are more the one files selected
            for f in path:
                # Some logic to check some files compatibility
                # ....
                # At the end is something similar like this
                Logic.StatusUpdate(f)

    def StatusUpdate(path):
        # A small logic to have the ideea how my button will loke and do
        Button(frm_status, text=os.path.basename(path), anchor="w", command=lambda:print(path)
               ).pack(expand=False, fill="x", side="top")

if __name__ == "__main__":
    main(root)
    root.mainloop()

定义的解决方案代码:(感谢@lemon)

    def StatusUpdate(path):
        # A small logic to have the ideea how my button will loke and do
        Button(frm_status, text=os.path.basename(path), anchor="w",
               command=lambda:os.system(f'cmd /c "start {os.path.dirname(path)}"')
               ).pack(expand=False, fill="x", side="top")

标签: python-3.xoperating-system

解决方案


您的意思是仅通过命令行打开文件夹吗?

您可以在 PowerShell 中使用“ii”。


推荐阅读