1

I want to save information in a text file from a Tkinter-based app.

def SaveInfo():
    NameInfo = NameVar.get()
    SurnameInfo = SurnameVar.get()
    f = open('cv.txt', 'w')
    print (NameVar.get(), SurnameInfo)
    f.write(f'name - {NameInfo}')
    f.close()


NameVar = StringVar()
Label(MainInfo, text='Name ', padx=5, pady=5).grid(row=1, column=1)
Name = Entry(MainInfo, textvariable=NameVar).grid(row=1, columnspan=3,
        column=2)
SurnameVar = StringVar()
Label(MainInfo, text='Surname ', padx=5, pady=5).grid(row=2, column=1)
Surname = Entry(MainInfo, textvariable=SurnameVar).grid(row=2,
        columnspan=3, column=2)

Submit1 = Button(MainInfo, text='Submit',
                 command=SaveInfo()).grid(row=10, column=3)

It neither prints anything nor saves any information when I enter something in the Entry.

Demian Wolf
  • 1,698
  • 2
  • 14
  • 34
BERO
  • 33
  • 6

2 Answers2

5

The problem is that you are running the function on Button creation. Remove the parenthesis:

Submit1 = Button(MainInfo, text = "Submit", command = SaveInfo).grid(row = 10, column = 3)

Hope that's helpful!

Wolf
  • 9,679
  • 7
  • 62
  • 108
rizerphe
  • 1,340
  • 1
  • 14
  • 24
4

The problem is you're calling SaveInfo immediately in

..., command = SaveInfo())...

As functions implicitly return None unless otherwise directed, that's the equivalent of setting command=None, which does nothing.

You'll just want to reference the handler function, e.g.

..., command = SaveInfo)...

so Tk will call it when the user clicks the button.

As an aside, you may want to use the a (append) mode for writing instead of w (overwrite):

def SaveInfo():
    name = NameVar.get()
    surname = SurnameVar.get()
    with open('cv.txt', 'a') as f:
      print(f'name: {name} {surname}', file=f)
AKX
  • 152,115
  • 15
  • 115
  • 172