繁体   English   中英

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

[英]How to save text from textbox to file (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)

...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM