from tkinter import * # 导入tkinter库
def do_build(): # 新建文件
text.delete(0.0, ‘end’) # 清空文本框内容
def do_open(): # 打开文件
file_path = entry_file.get() # 获取输入的文件名
with open(file_path, encoding=‘utf-8’) as fread: # 打开文件,此段代码结束后自动关闭
content = fread.read() # 读取文件内容
text.delete(0.0, ‘end’) # 清空文本框内容
text.insert(‘end’, content) # 在光标后插入文件内容
def do_save(): # 保存文件
content = text.get(0.0, ‘end’) # 获取文本框内容
file_path = entry_file.get() # 文件路径
with open(file_path, ‘w+’, encoding=‘utf-8’) as fwrite:
fwrite.write(content)
def do_find(): # 查找文字
search_str = tk.simpledialog.askstring(“查找”, “请输入要查找的内容:”)
if search_str:
start_pos = self.text_area.search(search_str, 1.0, stopindex=tk.END)
while start_pos:
end_pos = f"{start_pos}+{len(search_str)}c"
self.text_area.tag_add(“match”, start_pos, end_pos)
self.text_area.tag_config(“match”, background=“yellow”, foreground=“black”)
start_pos = self.text_area.search(search_str, end_pos, stopindex=tk.END)
def do_replace(): # 替换文字
old_string = tk.simpledialog.askstring(“替换”, “请输入需要替换的文字:”)
new_string = tk.simpledialog.askstring(“替换”, f"将 ‘{old_string}’ 替换为?")
if old_string and new_string:
all_content = self.text_area.get(1.0, tk.END)
updated_content = all_content.replace(old_string, new_string)
self.text_area.delete(1.0, tk.END)
self.text_area.insert(tk.END, updated_content)
win = Tk() # 创建窗口
win.title(‘文本编辑器’) # 设置标题
win.geometry(‘860x600’)
entry_file = Entry(win) # 创建一个文本输入框
btn_build = Button(win, text=‘新建’, command=do_build) # 创建按钮用于新建文件
btn_open = Button(win, text=‘打开’, command=do_open) # 创建按钮用于打开文件
btn_save = Button(win, text=‘保存’, command=do_save) # 创建按钮用于保存文件
btn_find = Button(win, text=‘查找’, command=do_find) # 创建按钮用于查找内容
btn_replace = Button(win, text=‘替换’, command=do_replace) # 创建按钮用于替换内容
text = Text(win) # 创建多行文本框,用于编辑文件
entry_file.pack() # 放置各组件
btn_build.pack()
btn_open.pack()
btn_save.pack()
btn_find.pack()
btn_replace.pack()
text.pack()
win.mainloop() # 进入消息循环
要实现wenjianming文本框在第一行文本框前有“请输入文件名”提示字,5个按钮并列在第二行,第二行以下为text文本框
最新发布