TheHero2805
TheHero2805

Reputation: 5

Problems with tkinter textbox output into a .txt file

I'm trying to create a program that opens a tkinter window with 4 entries. When I press a button, it's supposed to write everything from the entries into a .txt file from top to bottom. I've managed to make it work like I wanted to, but my only problem is that it only writes the last line into the created .txt file instead of all four. I am still kind of new to working with tkinter and dont really know how to fix this.

This is my code so far:

import os

from tkinter import *
fields = "Vorname", "Nachname", "Beruf", "Wohnort"

def fetch(entries):
   for entry in entries:
      field = entry[0]
      text  = entry[1].get()
      textfile = open("test2.txt", "w")
      textfile.write('%s: "%s"' % (field, text)) 

def makeform(root, fields):
   entries = []
   for field in fields:
      row = Frame(root)
      lab = Label(row, width=15, text=field, anchor='w')
      ent = Entry(row)
      row.pack(side=TOP, fill=X, padx=5, pady=5)
      lab.pack(side=LEFT)
      ent.pack(side=RIGHT, expand=YES, fill=X)
      entries.append((field, ent))
   return entries

if __name__ == "__main__":
   root = Tk()
   ents = makeform(root, fields)
   root.bind("<Return>", (lambda event, e=ents: fetch(e)))   
   b1 = Button(root, text="Drucken",
          command=(lambda e=ents: fetch(e)))
   b1.pack(side=LEFT, padx=5, pady=5)
   b2 = Button(root, text="Abbrechen", command=root.destroy)
   b2.pack(side=LEFT, padx=5, pady=5)
   root.mainloop()

Upvotes: 0

Views: 918

Answers (1)

Mixone
Mixone

Reputation: 1336

The issue you have is that you are opening the file at each iteration of the loop and the info is being overwritten.

You have two options:

  • Use with to open the file in fetch which closes the file on exit of block:

    def fetch(entries):
        with open("test2.txt", "w") as textfile:
            for entry in entries:
                field = entry[0]
                text  = entry[1].get()
                textfile.write('%s: "%s"\n' % (field, text))
    
  • Use close or flush to write to the file in fetch:

    def fetch(entries):
        textfile = open("test2.txt", "w")
        for entry in entries:
            field = entry[0]
            text  = entry[1].get()
            textfile.write('%s: "%s"\n' % (field, text))
        textfile.close()
    

There is a third option which involves saving the pointer to the location in the file which you ended write at and restart at that point but that would overcomplicate it since it can easily be solved with a simpler method.

Upvotes: 1

Related Questions