My python tkinter GUI program is writing a text file after doing some operations. I want to add a an export menu so that user can save this file into usb stick or in another directory. (I know we can do normal copy paste). But I would like to add this export menu. What I am trying to achieve is, When user clicks this export menu, the current directory should open, and the user can choose the file (myData.txt which is already being created and is present inside current directory) and user can now select a new directory and save the myData.txt in the new directory. (it should work in Linux platform as well)
#My gui app creates a text file myData.txt in my current folder when I run the program.
from tkinter import *
from tkinter import messagebox
import sys
def Export_File():
#what do i need here???
windows = Tk()
menubar = Menu(windows)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="Export", command =Export_File )
filemenu.add_command(label="Exit", command=Exit_File)
menubar.add_cascade(label="File", menu=filemenu)
windows.configure(menu=menubar)
windows.mainloop()
First, you need to import 2 more things
import os
from tkinter import filedialog
Next, assign a variable to the directory the user chooses and change to that directory using the os module
def Export_File():
dir_name = filedialog.askdirectory() # asks user to choose a directory
os.chdir(dir_name) # changes your current directory
To check your current directory, you can always
curr_directory = os.getcwd()
print(curr_directory)
Use askdirectory() in tkinter.filedialog. A normal file dialog window is opened and returns the directory of choice as a string.
from tkinter.filedialog import askdirectory
file = askdirectory(initialdir='/', title='Select File')
You should then be able to use the write function to save it somewhere else:
def Export_File():
file = open('myData.txt', 'w')
saveHere = askdirectory(initialdir='/', title='Select File')
file.write(os.path.join(saveHere, 'myData.txt'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With