How can i save a text input from a tab getting diferent tabs?

  python

"""
def OpenVFile() :

openfile = filedialog.askopenfile(initialdir="/", title="Select File",filetypes=(("Text Files",
"*.txt"), ("HTML", "*.html*"), ("Phyton Files", "*.py"), ("All files", "*.*"))).read()

tab2 = ttk.Frame(tab_control)

tab_control.pack(expand=1, fill='both')

tab_control.add(tab2, text="Untitled Vertical File")

my_frame = Frame(tab2, bg="black")
my_frame.place(relwidth= 0.81, relheight= 0.8, relx=0.1, rely=0.1,)

text_scroll = Scrollbar(my_frame)
text_scroll.pack(side=RIGHT, fill=Y)

textbox = Text(my_frame,undo=True, yscrollcommand=text_scroll.set)
textbox.place(relwidth= 0.8, relheight= 1, relx=0.1, rely=0)

text_scroll.config(command=textbox.yview)

textbox.insert(0.0, openfile) 

def SaveFile() :

file = filedialog.asksaveasfile()
filetext = str(textbox.get(1.0,END))
file.write(filetext)
file.close()

"""

so i want to save the file but it gives me an error textng me that textbox is not defined and i tried global variables too but doesn’t work neither pls help. TY

Source: Python Questions

One Reply to “How can i save a text input from a tab getting diferent tabs?”

  • There are two problems

    1. you have to keep in global variable – so you should use `global variable_name` inside `OpenVFile`

    2. if you use `global textbox` to keep text then `object `Text` will created only when you run `OpenVFile` first. If you run `SaveFile` without running `OpenVFile` then object `Text` will not exists and again you will get error. Better create object `Text` at start and inside `OpenVFile` use it with `place`. OR create global/external variable with default value `textbox = None` and then check it in `SaveFIle` – if textbox is not None: ….`

    “`

    # global variables

    textbox = None

    def OpenVFile() :
    global textbox

    # … code …

    textbox = Text(my_frame,undo=True, yscrollcommand=text_scroll.set)
    textbox.place(relwidth= 0.8, relheight= 1, relx=0.1, rely=0)

    # … code …

    def SaveFile() :

    file = filedialog.asksaveasfile()

    if file: # check if not pressed `Cancel`
    if textbox is not None:
    filetext = textbox.get(1.0, END) # no need `str()`
    else:
    filetext = “”
    file.write(filetext)

    file.close()

    “`

LEAVE A COMMENT