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,488
  • 2
  • 11
  • 28
BERO
  • 23
  • 5

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,246
  • 7
  • 59
  • 101
rizerphe
  • 1,319
  • 1
  • 13
  • 23
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
  • 123,782
  • 12
  • 99
  • 138