如何将文本从文本框保存到文件 (Tkinter)



每当函数save()运行时,我都会收到一个错误,指出保存Text()函数的变量不存在。我希望 GUI 在按下激活按钮时保存输入的任何内容。

from tkinter.ttk import *
class Example(Frame):
    def __init__(self, parent= None):
        Frame.__init__(self, parent)   
        self.parent = parent
        self.initUI()
    def initUI(self):
        self.parent.title("TL;DR")
        self.style = Style() 
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)
        lbl = Label(self, text="Enter Text")
        lbl.grid(sticky=W, pady=4, padx=5)

        area = Text(self)
        area.grid(row=1, column=0, columnspan=2, rowspan=4, 
            padx=5, sticky=E+W+S+N)
        abtn = Button(self, text="Activate", command= self.save)
        abtn.grid(row=1, column=3)

        cbtn = Button(self, text="Close", command = self.client_exit)
        cbtn.grid(row=2, column=3, pady=4)
        hbtn = Button(self, text="Help", command= self.help1)
        hbtn.grid(row=5, column=0, padx=5)

    def save(self):
        text = self.area.get("1.0",'end-1c')
        with open("filepy.txt", "a") as outf:
            outf.write(text)
    def help1(self):
        messagebox.showinfo('Help')

    def client_exit(self):              
        exit()
def main():
    root = Tk()
    root.geometry("400x300+300+300")
    app = Example(root)

if __name__ == '__main__':
    main()

我的问题是:按下激活按钮时如何在文本框中保存任何文本?

save()方法中,您正在尝试访问self.area但您没有创建它。

area = Text(self) # class variable
self.area = Text(self)# instance variable

为了能够使用 self 访问area您应该更改代码:

...
self.area = Text(self)
self.area.grid(row=1, column=0, columnspan=2, rowspan=4, 
        padx=5, sticky=E+W+S+N)
...

最新更新