【问题标题】:How to read variables with tkinter (Python) using a line by line .txt file如何使用 tkinter (Python) 逐行读取变量.txt 文件
【发布时间】:2022-12-15 10:42:29
【问题描述】:

我正在制作用户友好的数据输入窗口,并希望为其提供最后一次输入的记忆。我正在使用 .txt 文件,其中数据应逐行附加并尝试使用 readlines() 将其读取到窗口,但当有多于一行时我仍然收到异常“列表索引超出范围”一个文件。这是我的代码的示例:

class some_class:
    window=Tk()
    variable=StringVar()
    def __init__(self):
    Label(self.window,text="Here is variable place").grid(row=1,column=1,sticky=W)
    Entry(self.window,textvariable=self.variable,justify=RIGHT).grid(row=1,column=2,padx=(0,5))
    if os.path.isfile('save.txt'):
        with open('save.txt','r') as f:
            self.variable.set(f.readlines()[0])
    self.window.mainloop()
incode=some_class()
my_string_variable=str(incode.variable.get())
with open('save.txt','a') as f:
    f.write(my_string_variable+'\n')

我该如何解决?

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    看来您正在尝试访问的第一个元素f.readlines()列表,只有在文件至少有一行时才有效。由于您的文件可能有零行或多行,因此您应该在尝试访问元素之前检查列表的长度。 这应该可以解决您的问题:

    from tkinter import Tk, Label, Entry, StringVar, W
    import os
    
    class some_class:
        def __init__(self):
            self.window = Tk()
            self.variable = StringVar()
    
            # Create label and entry widgets
            Label(self.window, text="Here is variable place").grid(row=1, column=1, sticky=W)
            Entry(self.window, textvariable=self.variable, justify=RIGHT).grid(row=1, column=2, padx=(0, 5))
    
            # If the 'save.txt' file exists, read the first line and set it as the initial value of the entry widget
            if os.path.isfile('save.txt'):
                with open('save.txt', 'r') as f:
                    self.variable.set(f.readlines()[0].strip())
    
            self.window.mainloop()
    
    # Create an instance of the some_class class and get the value of the variable
    incode = some_class()
    my_string_variable = str(incode.variable.get())
    
    # Append the value of the variable to the 'save.txt' file
    with open('save.txt', 'a') as f:
        f.write(my_string_variable + '
    ')

    【讨论】:

    • 嘿,谢谢你的回答,但它不起作用。
    【解决方案2】:

    好的,我终于明白了。如果有人感兴趣,这就是它的完成方式:

    # creating a empty textfile
    if os.path.exists('save.txt'):
        os.utime(1)
    else:
        listc = ['0', '0', '0', '0']
        nfile = open("save.txt", 'w')
        for line, i in enumerate(listc):
            nfile.write(i + '
    ')
        nfile.close()
    
    class some_class:
        window=Tk()
        variable=StringVar()
        variable2=StringVar()
        def __init__(self):
            Label(self.window,text="Here is variable place").grid(row=1,column=1,sticky=W)
            Entry(self.window,textvariable=self.variable,justify=RIGHT).grid(row=1,column=2,padx=(0,5))
            Label(self.window,text="Here is variable2 place").grid(row=2,column=1,sticky=W)
            Entry(self.window,textvariable=self.variable2,justify=RIGHT).grid(row=2,column=2,padx=(0,5))
            if os.path.isfile('save.txt'):
                with open('save.txt','r') as f:
                    lines=f.readlines()
    
                    self.variable.set(lines[0].replace ("
    ",""))
                    self.variable2.set(lines[1].replace ("
    ",""))
    
            self.window.mainloop()
    incode=some_class()
    my_string_variable=str(incode.variable.get())
    my_string_variable2=str(incode.variable2.get())
    open('save.txt', 'w').close()
    with open('save.txt','a') as f:
        f.write(my_string_variable+'
    ')
        f.write(my_string_variable2+'
    ')
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-29
      • 1970-01-01
      • 1970-01-01
      • 2012-09-05
      • 2021-10-18
      • 1970-01-01
      • 1970-01-01
      • 2016-05-12
      相关资源
      最近更新 更多