Tirtha
Tirtha

Reputation: 686

Auto increment line of the text file

I have created normal gui program which reads the lines on the text files and show up in the text tk entry field. I want to auto increase the index of the line when I press the button, I am confused with while loop. The code what I did so far:

def forms(self):

        b = tk.Button(bd ='4', text="Auto Fill", width = 20, command = self.autosave)
        b.place (x=230, y=600)

        c = tk.Button(bd ='4', text="Clear", width = 20, command = self.clear)
        c.place (x=390, y=600)

        d = tk.Button(bd ='4', text="Exit", width = 20, command = self.close)
        d.place (x=550, y=600)

        #Form Feilds Starts from Here:
        self.date = tk.Label(font=('Arial', 13,'bold'), text = "Date: ",bg='white')
        self.date.place(x=10,y=50)

        self.ent_date = tk.Entry(bd='4',width='23')
        self.ent_date.place(x=60, y=50)


def autosave(self):
        a = 0
        fp = open('image.txt')
        s = fp.readlines()
        line = s[a]
        self.ent_date.insert(0, line[0])
        box.showinfo('Success','Saved Successfully')
        while true:
            a += 1

The above code makes my program to freeze. How can I make the value of 'a' increase each time I click the autofill button..? Thanks in advance.!

Upvotes: 0

Views: 913

Answers (2)

mockinterface
mockinterface

Reputation: 14880

The code loads the file on every button click, that's terribly inefficient. How about something along the following lines:

def __init__(self):
    fp = open('image.txt')
    s = fp.readlines()
    self.a = 0
    self.line = s[a]
    self.ent_date.insert(0, line[0])     

def forms(self):
    b = tk.Button(bd ='4', text="Auto Fill", width = 20, command = self.autosave)
    ...

def autosave(self):
    # save the current state, e.g., 
    # self.ent_date.insert(0, line[0]) - we'll leave it to the OP
    box.showinfo('Success','Saved Successfully')
    self.a += 1

Upvotes: 2

starrify
starrify

Reputation: 14761

How can I make the value of 'a' increase each time I click the autofill button..?

I guess you want some kind of static storage of a function. Then you could write like this:

def __init__(self):
    # original initialization of your class
    self.autosave.a = 0

def autosave(self):
    # some other of your code
    autosave.a += 1

See What is the Python equivalent of static variables inside a function?

Upvotes: 0

Related Questions