Python:如何将额外的输入保存到我的数据列表中?

时间:2016-03-31 18:48:15

标签: python

如何将新输入保存到数据列表中?

目前,当我在输入框中输入文字时,它会显示在我的列表中:数据。但是,当我清除输入框并添加新值时,此值将添加到数据列表中,而先前输入的值似乎消失。我希望每个添加的值都保留在列表中。我是python和编码的新手。非常感谢所有帮助! (代码如下所示)

import Tkinter as tk

class Example(tk.Frame):
    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        # create a prompt, an input box, an output label,
        # and a button to do the saving
        self.prompt = tk.Label(self, text="Enter your Filepath:", anchor="w")
        self.entry = tk.Entry(self)
        self.submit = tk.Button(self, text="Save", command = self.save)
        self.output = tk.Label(self, text="")
        self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text)

        # lay the widgets out on the screen. 
        self.prompt.pack(side="top", fill="x")
        self.entry.pack(side="top", fill="x", padx=20)
        self.output.pack(side="top", fill="x", expand=True)
        self.submit.pack(side="bottom")
        self.clear_button.pack(side="bottom")


    def clear_text(self):
        self.entry.delete(0, 'end')

    def save(self):
        # get the value from the input widget, save
        # it to list data
        data = []

        try:
            a = self.entry.get()
            result = data.append(a)

        except ValueError:
            result = "Please enter filepaths only"

        # set the output widget to have our result
        self.output.configure(text=result)
        print (data)

if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()

1 个答案:

答案 0 :(得分:0)

...解

import Tkinter as tk
data = []
class Example(tk.Frame):


def __init__(self, parent):
    tk.Frame.__init__(self, parent)

    # create a prompt, an input box, an output label,
    # and a button to do the computation
    self.prompt = tk.Label(self, text="Enter your Filepath:", anchor="w")
    self.entry = tk.Entry(self)
    self.submit = tk.Button(self, text="Save", command = self.save)
    self.output = tk.Label(self, text="")
    self.clear_button = tk.Button(self, text="Clear text", command=self.clear_text)

    # lay the widgets out on the screen. 
    self.prompt.pack(side="top", fill="x")
    self.entry.pack(side="top", fill="x", padx=20)
    self.output.pack(side="top", fill="x", expand=True)
    self.submit.pack(side="bottom")
    self.clear_button.pack(side="bottom")


def clear_text(self):
    self.entry.delete(0, 'end')


def save(self):
    # get the value from the input widget, convert
    # it to an int, and do a calculation

    try:
        a = self.entry.get()
        result = data.append(self.entry.get())

    except ValueError:
        result = "Please enter filepaths only"


    # set the output widget to have our result
    self.output.configure(text=result)
    print (data)


if __name__ == "__main__":
    root = tk.Tk()
    Example(root).pack(fill="both", expand=True)
    root.mainloop()