0

I'm trying to implement a function that reads an integer from a text file and the contents of a tkinter entry box, combines them, and displays the result of the combination in a tkinter label. Then it should write the result of the combination in a text file. I want this function to be able to be pressed multiple times, and combine the new value in the text file with the entry box value each time. The function writes to a text value so when re-opened it can retain the value of the count. However, I've found that the text file is only written to once I close the application, so if I try to add multiple entry box values they are only ever combined with the original value in the text file. Being able to write to the file before the application closes would solve this issue.

After doing some research supposedly using flush, fsync, and close, as well as setting the buffering to 0 or 1 are supposed to solve this problem, but none of these wrote to the file before the application was closed.

How do I write to a file on button click before the application closes?

Here's a minimal code example in python:

import os
from tkinter import *
class counter():
    def Add(self):
        count = int(self.WCount)
        new_count = count + int(self.Wtxtfld.get())
        self.Wlbl.configure(text="Total WCount: " + str(new_count))
        self.Wtxtfld.delete(0, END)
        with open('WCountSave', 'w') as f:
            f.write(str(new_count))
            f.flush() 
            os.fsync(f)
            f.close()
    def __init__(self):
        self.root = Tk()
        self.root.geometry("450x50")
        with open('WCountSave', 'r') as f:
            gotCount = f.read()
        self.WCount = gotCount
        self.Wlbl = Label(self.root, text="Total WCount: " + self.WCount, fg='light blue', bg='black',font=("Helvetica", 16))
        self.Wbtn = Button(self.root, text="Add", command=self.Add, font=("Arial 12 "), bg=("#5540D7"))
        self.Wtxtfld = Entry(self.root, text="entry 3", bd=5)
        self.Wlbl.place(x=200, y=0)
        self.Wbtn.place(x=150, y=0)
        self.Wtxtfld.place(x=0, y=0)
        self.root.mainloop()
a = counter()

WCountSave is a .txt file with the following contents:

0
  • 1
    You don't need to do anything in the `with open(...` block other than the `.write()` - the file is automatically closed when the block is exited. You're only getting one file update per run of the program because you aren't updating `self.Wcount` - every button click is adding to the value read at the start of the program, rather than the current contents of the file. – jasonharper Apr 13 '22 at 19:54
  • @jasonharper Thanks! Updating self.Wcount instead worked for what I needed. – Bill Bumbleton Apr 13 '22 at 20:30

0 Answers0