自动增加文本文件的行

时间:2014-01-11 08:11:44

标签: 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 ='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'的值增加..? 在此先感谢。!

2 个答案:

答案 0 :(得分:2)

代码会在每次点击按钮时加载文件,这非常低效。如下所示:

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

答案 1 :(得分:0)

  

每次单击自动填充按钮时,如何使'a'的值增加..?

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

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

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

请参阅What is the Python equivalent of static variables inside a function?