我正在尝试制作一个非常基本的记事本程序。我唯一的问题是尝试打开.txt
文件并将其内容放入主文本字段。但我一直都有错误。
from Tkinter import *
import tkFileDialog
class Application(Frame):
def __init__(self, master):
Frame.__init__(self,master)
self.grid()
self.Create_Widgets()
def Create_Widgets(self):
self.SButton = Button(self,width=35)
self.SButton["text"]="Save"
self.SButton["command"]=self.Save
self.SButton.grid(row=0,column=0)
self.OButton = Button(self,width=35)
self.OButton["text"]="Open"
self.OButton["command"]=self.Open
self.OButton.grid(row=0,column=1)
self.Cont = Text(self,width=60,height=40)
self.Cont.grid(row=1,column=0,columnspan=2)
def Save(self):
Content=self.Cont.get(1.0,END)
File = tkFileDialog.asksaveasfile(mode='w', defaultextension=".txt")
File.write(Content)
File.close()
def Open(self):
Content=self.Cont.get(0.0,END)
File1 = tkFileDialog.askopenfilename()
File2 = open(File1,"r")
print(File2.read())
root=Tk()
root.title="Basic Notepad"
app=Application(root)
root.mainloop()
答案 0 :(得分:1)
您可以使用Tkinter.Text.insert
将文件的文字插入文本框中:
def Open(self):
File1 = tkFileDialog.askopenfilename()
File2 = open(File1, "r")
#######################################
self.Cont.insert("1.0", File2.read())
#######################################
File2.close() # Make sure you close the file when done
"1.0"
告诉Python从哪里开始插入文本。