0

I am trying to make GUI and would like to have an option to save text file created in this GUI with filename taken from user's input.

Have something like this:

script_name_input_area = Entry(
    width = 30).place(x = 100, y = 60)

Saving function defined like this:

def savef():
    file = filedialog.asksaveasfile(initialdir='/', title="select file", initialfile= ('FIX THIS!!')...

Is there a way to incorporate user's ENTRY into initialfile?

2 Answers2

0

A very simple example of how to do this

import tkinter as tk
from tkinter import filedialog

def savef():
    file = filedialog.asksaveasfile(initialdir='/', title="select file", initialfile= script_name_input_area.get())

root = tk.Tk()
script_name_input_area = tk.Entry(root,width=30)
script_name_input_area.pack()
save_button = tk.Button(root,text="Save",command=savef)
save_button.pack()

root.mainloop()

I suspect your issue may have been to do with doing this

script_name_input_area = Entry(width = 30).place(x = 100, y = 60)

Where you are trying to both create and place the entry widget on the same line. Entry will return a tk.Entry instance but place returns None so script_name_input_area will be equal to None too. Where you need to use a tk widget later, ALWAYS create and pack/grid/place it on a new line.

scotty3785
  • 6,763
  • 1
  • 25
  • 35
0

Here's a code that do what you want, as @scotty3785 said, your issue is because you .place() doesn't return an instance of Entry. You need to create the instance of Entry and after place it.

import tkinter as tk


class mainWindow(tk.Tk) : 
    def __init__(self) :
        super().__init__()
        self.filename = None #if you need to keep the output filename

        self.script_name_input_area = tk.Entry(self,width=30) #your entry
        self.script_name_input_area.pack() #need to place it AFTER creating it

        saveFile = tk.Button(self,text="Save",command=self.saveFile) #button to save that calls saveFile when clicked
        saveFile.pack() #place button

    def saveFile(self):
        if(self.script_name_input_area.get() != "") : #if your entry is not empty
            with open(self.script_name_input_area.get() + ".txt", "w") as file : #open/create a file called (Entry).txt in write mode
                file.write("") #write what ever you want
        else : #else
            print("please provide something in textField") #please provide something

if __name__ == "__main__":
    win = mainWindow() #create instance of MainWindow
    win.mainloop() #create a loop of mainWindow until user close the window

Hope this will help you ! Keep us updated

David01
  • 29
  • 6