Starwarsfan2099
Starwarsfan2099

Reputation: 144

Open file and save it in another function with tkinter

I am working on creating a python Tk program and found that saving files is annoying. I have an open button and a save button. For example I call

file = tkFileDialog.askopenfile(mode='rb',title='Select a file')

from this function

def open_command(self):

In another function

def save_file(self):

I want to save the file. To save the file under the same name I have to call

file = tkFileDialog.asksaveasfile(mode='w')

again and this opens another window, then it asks you to name the file, and finaly prompts you if you want to overwrite the file. Is there a way to save the file without any windows? Is it possible in any way to not close the file in one function and then write to the file and save it in another function?

Upvotes: 0

Views: 1182

Answers (1)

TigerhawkT3
TigerhawkT3

Reputation: 49318

It sounds like you want a silent save/overwrite, so that a user can open a file, modify it, and then hit Save to update the saved file. I would recommend asking for a file name, as askopenfile asks for the name and then immediately gives you the file object by that name.

self.save_name = tkFileDialog.askopenfilename(title='Select a file')
with open(self.save_name, 'rb') as f:
    self.the_data = f.read() # insert processing here

If you ask for just the name, you can save that name and then later use it directly in your save function:

with open(self.save_name, 'wb') as output:
    output.write(self.the_data) # insert processing here

Upvotes: 1

Related Questions