我如何在GUI上显示当前选定的文件夹?

2024-09-22 16:33:02 发布

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

再见

我正在使用tkinter filedialog选择一个文件夹,并在GUI上的条目中显示它?在

以下是我目前为止的代码:

import os
from tkinter import *
from tkinter import filedialog

dir_path = ''

def inPut():
    indir = filedialog.askdirectory(parent=root,initialdir="/",title='Input Folder')
    indir = str(indir)
    dir_path = os.path.dirname(indir)
    entry.delete(0, END)
    entry.insert(0, dir_path)
    return dir_path

root = Tk()
root.geometry("640x240")
root.title("Settings")

frametop = Frame(root)
framebottom = Frame(root)
frameright = Frame(framebottom)

text = Label(frametop, text="Input Folder").grid(row=5, column=2)
entry = Entry(frametop, width=50, text=dir_path)
entry.grid(row=5,column=4,padx=2,pady=2,sticky='we',columnspan=20)

ButtonA = Button(frametop, text="Change", command=inPut).grid(row=5, column=28)
ButtonB = Button(frameright, text="OK").grid(row=5, column=20, padx=10)

frametop.pack(side=TOP, fill=BOTH, expand=1)
framebottom.pack(side=BOTTOM, fill=BOTH, expand=1)
frameright.pack(side=RIGHT)

root.mainloop()

当前,它只返回'D:/'

  1. 如何使它返回条目中的完整路径?

  2. 如何将“/”更改为“\”

  3. 下一次运行应用程序时,如何使应用程序记住文件夹作为初始目录?

请帮忙!在


Tags: pathtextimporttkinterdircolumnrootframe
1条回答
网友
1楼 · 发布于 2024-09-22 16:33:02

要把它写进你的标签上,你需要有它的参考。在

多种可能性:

  1. 为GUI创建一个类,并使用showdir或绑定到它的textvariable作为实例变量
  2. 传递对调用的引用以使showdir可用
  3. 全局showdir

为什么要这么做?最不喜欢。在

如果您不知道如何写入或读取文件,请在开始创建gui之前从python教程开始。如果你不知道你为什么要这样做,那么“把别人写的代码搞混”就没有意义了。这就像在不知道交通状况的情况下开车。在

至于你的编辑:

您的代码现在可以工作了,因为您不再直接访问该属性,所以您不再使用对条目的立即写入访问权限。在

  • return dir_path完全过时了。在
  • 根据父目录路径documentation中的定义,os.path.dirname(indir)返回的文件夹不会得到。如果使用文件而不是目录dirname就可以了,只要使用目录,就使用os.path.abspath。在
os.path.dirname(path)¶

Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().

相关问题 更多 >