我正在尝试使用Python 3.4.2和tkinter / ttk创建一个文本编辑器。加载我的文件后,文本将从文件底部插入文本小部件,使文件文本“向后”。首先插入文件的最后一行,最后一行插入。一切都会有所帮助。谢谢。
from tkinter import *
from tkinter import ttk
import os
class Main(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
self.body = Text(self, width=50, height=15)
self.body.grid(row = 0, column = 0, sticky = W)
self.save_label = Label(self, text="File to Save to:")
self.save_label.grid(row = 2, column = 0, sticky = W)
self.save_entry = ttk.Entry(self)
self.save_entry.grid(row = 3, column = 0, sticky = W)
self.save_button = ttk.Button(self, text="Save File", command=self.save)
self.save_button.grid(row = 4, column = 0, sticky = W)
self.read_label = Label(self, text="File to Read:")
self.read_label.grid(row = 2, column = 1, sticky = W)
self.read_entry = ttk.Entry(self)
self.read_entry.grid(row = 3, column = 1, sticky = W)
self.read_button = ttk.Button(self, text="Read File", command=self.read)
self.read_button.grid(row = 4, column = 1, sticky = W)
scrollbar = ttk.Scrollbar(root, orient=VERTICAL, command=self.body.yview)
scrollbar.grid(row = 0, column = int(1), sticky = 'ns')
self.body.config(yscrollcommand=scrollbar.set)
self.quit_button = ttk.Button(self, text="Quit", command=self.close)
self.quit_button.grid(row = 5, column = 0, sticky = W)
def close(self):
root.destroy()
quit()
def save(self):
body = self.body.get('0.0', 'end-1c')
file = self.save_entry.get()
file = open(file, "w")
file.write(body)
file.close()
def read(self):
self.body.delete("0.0", END)
file = self.read_entry.get()
file = open(file, 'r')
file_data = file.readlines()
for i in file_data:
self.body.insert('1.0', str(i))
file.close()
root = Tk()
root.title("NotePad")
root.geometry("500x600")
root.attributes("-fullscreen", True)
app = Main(root)
root.mainloop()
答案 0 :(得分:1)
您告诉tkinter将每行放在"1.0"
。如果您希望将每一行添加到最后,请使用"end"
for i in file_data:
self.body.insert('end', str(i))
顺便说一下,文本小部件的第一个字符位于"1.0"
,而不是"0.0"
。虽然"0.0"
将如何实现tkinter,但正确的索引是"1.0"
。
例如,使用此:
body = self.body.get('1.0', 'end-1c')
......而不是这个:
body = self.body.get('0.0', 'end-1c')