如何在Tkinter中保存文本框的内容?
要保存Tkinter中文本框的内容,我们可以采取以下步骤:
创建一个Tkinter框架实例。
使用**win.geometry**方法设置框架的大小。
定义一个用户自定义方法**“open_text”**,以**“读取”**模式打开一个文本文件。读取文本文件的内容并将其保存在名为**“content”**的变量中。然后,使用**“insert”**方法将**content**插入文本框。
接下来,定义另一个名为**“save_text”**的用户自定义方法,并在其中使用**“write”**方法将文本框的内容保存到文本文件中。
使用Text方法创建一个文本小部件,并指定其**高度**和**宽度**。
创建一个按钮来调用open_text方法。
创建一个按钮来调用open_text方法。
最后,运行应用程序窗口的mainloop。
示例
# Import tkinter library
from tkinter import *
# Create an instance of tkinter window
win = Tk()
win.geometry("700x250")
def open_text():
text_file = open("test.txt", "r")
content = text_file.read()
my_text_box.insert(END, content)
text_file.close()
def save_text():
text_file = open("test.txt", "w")
text_file.write(my_text_box.get(1.0, END))
text_file.close()
# Creating a text box widget
my_text_box = Text(win, height=10, width=40)
my_text_box.pack()
open_btn = Button(win, text="Open Text File", command=open_text)
open_btn.pack()
# Create a button to save the text
save = Button(win, text="Save File", command=save_text)
save.pack()
win.mainloop()输出
执行代码后,将显示以下屏幕:
现在,单击**“打开文本文件”**按钮打开文本文件**“test.txt”**。它将显示文件的内容在文本框中。
接下来,在文本框中输入新的一行,然后单击**“保存文件”**将内容保存到**“test.txt”**中。
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP