How do I open a file with tkinter and save the data to another variable?

Viewed 307

I am learning to use tkinter and I cannot figure out how to open a text file and save the data so that I can use the data in other calculations. In my code below a button is created that when pressed asks for and opens a file. It then prints the content of the file in the console. If the file contains for example a single number, say 100, I can't figure out how to save that number as a variable like "a."

from tkinter.filedialog import askopenfile

root = Tk()
root.geometry('200x100')
  
# This function will be used to open
# file in read mode and only Python files
# will be opened
def open_file():
    file = askopenfile(parent=root, filetypes =[('Text Files', '*.txt')])
    if file is not None:
        content = file.read()
        print(content)
        a = content

btn = Button(root, text ='Open', command = lambda:open_file())
btn.pack(side = TOP, pady = 10)
1 Answers

You are assigning the contents of the file to a variable declared within the function. It will be destroyed after the function finishes.

Declare the variable before the function

data = []

Append the content of the file to the container value within the function

def open_file(container):
    file = askopenfile(parent=root, filetypes =[('Text Files', '*.txt')])
    if file is not None:
        content = file.read()
        print(content)

        # give the content to the data
        data.append(content)

However if you are going to give the data to another widget using a instance of tk.StringVar() might be better as most widgets have a textvariable option.

data = StringVar()

And instead of appending StringVar uses the set() method.

data.set(content)

Resources for you: https://www.pythontutorial.net/tkinter/tkinterstringvar/ And:https://www.delftstack.com/howto/python-tkinter/how-to-change-the-tkinter-button-text/

Related