Python 文本文件的自动增量行

Python 文本文件的自动增量行,python,tkinter,Python,Tkinter,我创建了一个普通的gui程序,它读取文本文件上的行,并显示在文本tk输入字段中。当我按下按钮时,我想自动增加行的索引,我被while循环弄糊涂了。我迄今为止所做的代码如下: 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 ='

我创建了一个普通的gui程序,它读取文本文件上的行,并显示在文本tk输入字段中。当我按下按钮时,我想自动增加行的索引,我被while循环弄糊涂了。我迄今为止所做的代码如下:

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
上面的代码使我的程序冻结。如何使“a”的值在每次单击“自动填充”按钮时增加。。? 提前谢谢

如何使“a”的值在每次单击“自动填充”按钮时增加

我猜你想要函数的某种静态存储。然后你可以这样写:

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

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

请参见

代码在每次单击按钮时都会加载文件,这是非常低效的。以下几点怎么样:

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