0

I am trying to load checkbox values from a text file.

Let me explain..

Here is the screen:

Click here for image

I have a piece of code that saves the results into a .txt file.

Here is the .txt file:

Click here for image

Now, when I close & re-open the .py file, everything resets.

I'd like to implement a button that will load last row from txt file and do the following:

If option1 is 0 and option2 is 1 from text file, when clicked load, the option2 check box will be the only one checked.

Like this:

Intended result when loading the txt file

How can this be achieved?

Here is my current code:

from tkinter import *

master = Tk()
master.minsize(200, 100)

var = IntVar()
var2 = IntVar()

a = Checkbutton(master, text="Option 1", variable=var)
a.pack()

b = Checkbutton(master, text="Option 2", variable=var2)
b.pack()

def save():
    text_file = open("text.txt", "a")
    text_file.write("Option1 %d Option2 %d \n" % (var.get(), var2.get()))
    text_file.close()

Button(master, text = "Save", command = save ).pack()

mainloop()
stovfl
  • 14,998
  • 7
  • 24
  • 51
  • Read about [Tkinter.Checkbutton.select-method](http://effbot.org/tkinterbook/checkbutton.htm#Tkinter.Checkbutton.select-method) – stovfl Sep 25 '19 at 20:29

1 Answers1

0

This is one way to do it like you asked.

from tkinter import *
import os

if os.path.isfile('text.txt'):
    with open("text.txt", "r") as f:
        lineList = f.readlines()
        _, option1, _, option2 = lineList[-1].split()
else:
    option1 = '0'
    option2 = '0'

master = Tk()
master.minsize(200, 100)

var = IntVar()
var2 = IntVar()

a = Checkbutton(master, text="Option 1", variable=var)
if option1 == '1':
    a.select()
a.pack()

b = Checkbutton(master, text="Option 2", variable=var2)
if option2 == '1':
    b.select()
b.pack()

def save():
    text_file = open("text.txt", "a")
    text_file.write("Option1 %d Option2 %d \n" % (var.get(), var2.get()))
    text_file.close()

Button(master, text = "Save", command = save ).pack()

mainloop()

But is there a reason to keep appending to the textfile? If not, then it would be quicker and more efficient to just overwrite the file at each save.

Niels Henkens
  • 2,553
  • 1
  • 12
  • 27
  • Hi Niels, appreciate your time in answering:) reason if I append is to keep the log file, and load up certain data. I will research in how to add data into text file with unique Id numbers. Might have to move onto MySql –  Sep 26 '19 at 04:03