如何获取使用Tkinter 8.5从文件对话框返回所选文件的函数

时间:2014-06-18 17:28:39

标签: tkinter

我希望fileName中的vendorFunction()在用户点击格式按钮后在条目框中获取用户的输入。我是新手,无法弄清楚如何做到这一点。以下是我的代码:

from tkinter import *
from tkinter import ttk

def createVendorWindow():
    def browse():
        fileSelected = filedialog.askopenfilename()
        guiInputFileEntry.insert(0, fileSelected)

    def format(file):
        return file

    vendorWindow = Tk()
    vendorWindow.title("Cost Load Converter")

    vendorWindowFrame = ttk.Frame(vendorWindow, padding="12 12 7 7")
    vendorWindowFrame.grid(column=0, row=0, sticky=(N,W,E,S))
    vendorWindowFrame.columnconfigure(0, weight=1)
    vendorWindowFrame.rowconfigure(0, weight=1)

    guiInputFile = StringVar()

    guiInputFileEntry = ttk.Entry(vendorWindowFrame, width=100, textvariable=guiInputFile)
    guiInputFileEntry.grid(column=1, row=1, stick=(W,E))

    ttk.Label(vendorWindowFrame, text="\nPlease enter the full filepath of the file you wish to format:").grid(column=1, row=0)

    browseButton = ttk.Button(vendorWindowFrame, text="Browse...", underline=0, command=browse)
    browseButton.grid(column=2, row=1, padx=5)

    formatButton = ttk.Button(vendorWindowFrame, text="Format", underline=0, command= lambda: format(guiInputFileEntry.get()))
    formatButton.grid(column=1, row=2, pady=5)

    vendorWindow.mainloop()    

def vendorFunction():
    fileName = createVendorWindow()
    print("fileName: ", fileName)
    #then, do stuff with fileName

vendorFunction()

提前致谢!

1 个答案:

答案 0 :(得分:0)

现在,您的format函数返回文件名,但您希望createVendorWindow函数返回文件名。因此,您应该将return guiInputFile.get()放在vendorWindow.mainloop()后面。然后,所有格式按钮需要关闭窗口:command=lambda: vendorWindow.destroy()。这将停止mainloop并开始执行mainloop后面的所有内容。