Search code examples
pythonuser-interfaceeventstkintervolatile

getting directory where file has been saved (tkinter filesave prompt)


I'm using tkinter to make a small GUI in python, part of which is to ask user where to save a file. Here is my code

from tkinter import *
import tkinter.filedialog as tf
import tkinter
import time

fileName = ""
def save():
    myFormats = [
    ('Text File','*.txt')
    ]
    root = tkinter.Tk()
    q = tf.asksaveasfilename(parent=root,filetypes=myFormats ,title="Save the image as...")
    print(type(q))
    fileName = q
    print(fileName)
    if len(fileName ) > 0:
        print ("Now saving under %s" % fileName)


master = Tk()
Button(master, text='Save file', command=save).grid(row=3, column=1, sticky=W, pady=4)
print(fileName)

mainloop( )
print(fileName)

the print(fileName) inside save(), prints the proper path, but, the same statement at the end of the code just gives a , which it was initialized to in the beginning. I've been breaking my head trying to figure out why this is happening and finding a way to fix it. Any help would be wonderful!

Was wondering if it's something to do with volatile variables

Thanks in advance!


Solution

  • The fileName variable inside of save is different than the variable fileName in the global namespace due to scoping rules. If you want to reference the global variable use the global keyword:

    def save():
        myFormats = [('Text File','*.txt')]
        root = tkinter.Tk()
        q = tf.asksaveasfilename(parent=root,
                filetypes=myFormats,
                title="Save the image as...")
        global fileName
        fileName = q