如何选择目录并将其存储到tkinter中的变量中?

时间:2018-08-16 12:29:29

标签: python user-interface tkinter

我有tkinter GUI。我喜欢有一个文本框和一个按钮。单击该按钮后,将打开文件浏览器,最后可以选择目录。此路径必须显示在文本框中。

代码:

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
gui = Tk()
gui.geometry("400x400")
gui.title("FC")
a = Label(gui ,text="Enter name").grid(row=0,column = 0)
E = Entry(gui).grid(row=0,column=1)
folder_selected = filedialog.askdirectory()
c = ttk.Button(gui ,text="find").grid(row=4,column=0)
gui.mainloop()

1 个答案:

答案 0 :(得分:2)

这样的事情怎么样

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
gui = Tk()
gui.geometry("400x400")
gui.title("FC")

def getFolderPath():
    folder_selected = filedialog.askdirectory()
    folderPath.set(folder_selected)

def doStuff():
    folder = folderPath.get()
    print("Doing stuff with folder", folder)

folderPath = StringVar()
a = Label(gui ,text="Enter name")
a.grid(row=0,column = 0)
E = Entry(gui,textvariable=folderPath)
E.grid(row=0,column=1)
btnFind = ttk.Button(gui, text="Browse Folder",command=getFolderPath)
btnFind.grid(row=0,column=2)

c = ttk.Button(gui ,text="find", command=doStuff)
c.grid(row=4,column=0)
gui.mainloop()

摘要:

  • 您正在创建窗口小部件,并在同一行上使用布局grid。这是一个坏主意。我将其拆分,以便您定义按钮,然后在新行上进行布局
  • 我添加了一个Stringvar,这是一个特殊的tkinter变量,可用于自动更新字段
  • 我添加了两个功能,当您按下新的浏览按钮时会调用一个功能,这将弹出文件夹选择对话框。我为“查找”按钮添加了另一个,可用于您要处理的文件夹路径。

考虑: 更具描述性的命名。请注意,我已经将新按钮称为btnFind,而不是像其他小部件一样为单个字符。当您再次查看代码时,这将使调试/理解代码更加容易。

编辑: 由于您要选择多个文件夹选择项,因此值得创建一个包含所有用于选择文件夹的属性和功能的类。这是一个例子

from tkinter import *
from tkinter import ttk
from tkinter import filedialog
gui = Tk()
gui.geometry("400x400")
gui.title("FC")

class FolderSelect(Frame):
    def __init__(self,parent=None,folderDescription="",**kw):
        Frame.__init__(self,master=parent,**kw)
        self.folderPath = StringVar()
        self.lblName = Label(self, text=folderDescription)
        self.lblName.grid(row=0,column=0)
        self.entPath = Entry(self, textvariable=self.folderPath)
        self.entPath.grid(row=0,column=1)
        self.btnFind = ttk.Button(self, text="Browse Folder",command=self.setFolderPath)
        self.btnFind.grid(row=0,column=2)
    def setFolderPath(self):
        folder_selected = filedialog.askdirectory()
        self.folderPath.set(folder_selected)
    @property
    def folder_path(self):
        return self.folderPath.get()

def doStuff():
    folder1 = directory1Select.folder_path
    folder2 = directory2Select.folder_path
    folder3 = directory3Select.folder_path
    print("Doing stuff with folder", folder1, folder2, folder3)

folderPath = StringVar()

directory1Select = FolderSelect(gui,"Select Folder 1")
directory1Select.grid(row=0)

directory2Select = FolderSelect(gui,"Select Folder 2")
directory2Select.grid(row=1)

directory3Select = FolderSelect(gui,"Select Folder 3")
directory3Select.grid(row=2)


c = ttk.Button(gui, text="find", command=doStuff)
c.grid(row=4,column=0)
gui.mainloop()

您现在可以根据需要选择任意数量的文件夹。