集成文件和文本小部件python/tkinter
情况是,我想:集成文件和文本小部件python/tkinter,python,file,tkinter,widget,Python,File,Tkinter,Widget,情况是,我想: -打开特定的文本文件 -从文本文件导入要在文本小部件中显示的文本 -然后将文本小部件中的文本替换为文本小部件中当前的文本文件。 目前,我已经解决了如何将特定的文本文件打开到文本小部件中并显示它,但是我无法解决如何执行最后一步 我试图定义一个“Save”函数,但是没有任何结果,你可以在下面看到 步骤1和步骤2的当前代码: class PropertynewsA(Propertynews): def __init__(self): Propertynews.__init__
class PropertynewsA(Propertynews):
def __init__(self):
Propertynews.__init__(self)
def save():
file.write(txt)
file.close()
messagebox.showinfo('Saved!','Your Message has been Saved')
self.delete
file = open('PropertynewsA.txt', 'r+') #Text file i am using
with open('PropertynewsA.txt') as file: # Use file to refer to the file object
data = file.read() #date=current text in text file
#Text widget
Time = strftime("%d %b %Y\n")#getting gmt time
txt = Text(self.GenericGui,height=14, width=53,font=('TkDefaultFont',12)) #Creating text widget
txt.insert('1.0',data) #showing text from text file in widget
txt.tag_configure('format', background='lightblue', font='helvetica 14 bold', relief='raised')
txt.focus()
txt.place(x=8,y=40) #places text widget
如果有人能在这里帮助我,那就太好了
干杯伙计们一旦你知道了工作原理,知道了插入
和获取
:
棘手的部分是在程序关闭时访问文本,而不是在小部件被销毁后(或者您得到一个\u tkinter.TclError:无效的命令名“.4384096888”
错误):
虽然如果使用tkinter import*表示法中的,则需要调用类,而不是Text
,也可能不使用ending_Text
作为全局变量,但这是演示如何操作的最简单方法
这是我用来测试IO的完整代码,尽管如果您不了解如何使用已经存在的文件
将tkinter作为tk导入
filename=“test.txt”
类文本(tk.Text):
def销毁(自我):
全局结束文本
end_text=self.get(“1.0”,“end-1c”)
super(Text,self).destroy()
尝试:
打开(文件名)为f时:
text=f.read()
除IOError外:
text=“”
root=tk.tk()
textbox=文本(根)
文本框。插入(“1.0”,文本)
textbox.grid()
#这可能只是放在销毁方法中
def完成(事件=无):
打开(文件名为“w”)作为f:
f、 写入(结束文本)
textbox.bind(“,finish)#这将在Text.destroy()之后发生,因此如果从此时开始使用textbox.get()将失败
root.mainloop()
一旦您了解了工作原理并了解了插入
和获取
:
棘手的部分是在程序关闭时访问文本,而不是在小部件被销毁后(或者您得到一个\u tkinter.TclError:无效的命令名“.4384096888”
错误):
虽然如果使用tkinter import*
表示法中的,则需要调用类,而不是Text
,也可能不使用ending_Text
作为全局变量,但这是演示如何操作的最简单方法
这是我用来测试IO的完整代码,尽管如果您不了解如何使用已经存在的文件
将tkinter作为tk导入
filename=“test.txt”
类文本(tk.Text):
def销毁(自我):
全局结束文本
end_text=self.get(“1.0”,“end-1c”)
super(Text,self).destroy()
尝试:
打开(文件名)为f时:
text=f.read()
除IOError外:
text=“”
root=tk.tk()
textbox=文本(根)
文本框。插入(“1.0”,文本)
textbox.grid()
#这可能只是放在销毁方法中
def完成(事件=无):
打开(文件名为“w”)作为f:
f、 写入(结束文本)
textbox.bind(“,finish)#这将在Text.destroy()之后发生,因此如果从此时开始使用textbox.get()将失败
root.mainloop()
我创建了一个简单的用户界面,允许您从文件对话框中打开所选的文本文件。出于可伸缩性的原因,我希望稍后将此选项分开设置(例如,如果您将来喜欢阅读文档文件):
我运行的是Linux,所以如果您使用的是MS Windows操作系统,您可以将self.file_选项['initialdir']='/home/'
更改为所需的任何目录路径。请注意,您也可以删除它,在这种情况下,默认情况下,“文件”对话框窗口将提示您到运行应用程序的目录
方法initialize\u user\u interface()。主要是,它提供了一种轻松的方式,通过单击退出应用程序并选择要读取的文件:
self.filemenu.add_command(label="Open",command=self.text_replacement)
self.filemenu.add_command(label="Exit",command=self.parent.quit)
然后可以添加一个文本小部件。最好是有一个可滚动的文本区,以防你无意中发现一个大的内容文件
为此,您需要创建滚动条,并将其附加到文本小部件,因为文本小部件不维护自己的滚动条
以下是完整的程序:
'''
Created on Feb 25, 2016
@author: begueradj
'''
import Tkinter # Tkinter -> tkinter in Python3
import Tkconstants
import tkFileDialog
class Begueradj(Tkinter.Frame):
""" Get text file content and past it into a scrollable Text widget.
Replace the content of the file with the pre-existing Text widget content.
"""
def __init__(self,parent):
""" Set some class variables:
mainly the file dialog interface options.
"""
Tkinter.Frame.__init__(self,parent)
self.parent=parent
# Opening file options
self.file_options={}
self.file_options['defaultextension'] = '.txt'
self.file_options['filetypes'] = [('text files', '.txt'), ('all files', '.*')]
self.file_options['parent'] = self.parent
self.file_options['title'] = 'Open a text file'
self.file_options['initialdir']='/home/'
self.initialize_user_interface()
def initialize_user_interface(self):
""" Design of the user interface.
It mainly consists of a bar menu and a horizontally & vertically
scrollable Text widget in case the text file to read is large.
"""
self.parent.title("Text replacement")
# Set the bar menu and its items
self.menubar=Tkinter.Menu(self.parent)
self.filemenu=Tkinter.Menu(self.menubar,tearoff=0)
self.filemenu.add_command(label="Open",command=self.text_replacement)
self.filemenu.add_command(label="Exit",command=self.parent.quit)
self.menubar.add_cascade(label="File",menu=self.filemenu)
self.parent.config(menu=self.menubar)
self.parent.grid_rowconfigure(0,weight=1)
self.parent.grid_columnconfigure(0,weight=1)
# Set the horizontal and vertical scrollbars
self.hscrollbar=Tkinter.Scrollbar(self.parent,orient=Tkconstants.HORIZONTAL)
self.hscrollbar.grid(row=1,column=0,sticky=Tkinter.E+Tkinter.W)
self.vscrollbar=Tkinter.Scrollbar(self.parent)
self.vscrollbar.grid(row=0,column=1,sticky=Tkinter.N+Tkinter.S)
# Set the Text widget and make it scrollable
self.text=Tkinter.Text(self.parent,wrap=Tkinter.NONE,bd=0,
xscrollcommand=self.hscrollbar.set,
yscrollcommand=self.vscrollbar.set)
self.text.grid(row=0,column=0,sticky=Tkinter.E+Tkinter.W+Tkinter.S+Tkinter.N)
self.text.insert("1.0","Original text here")
self.hscrollbar.config(command=self.text.xview)
self.vscrollbar.config(command=self.text.yview)
def text_replacement(self):
""" Return the name of a file
opened in read mode
"""
self.filename = tkFileDialog.askopenfilename(**self.file_options)
if self.filename:
self.original=self.text.get("0.0","end-1c")
print self.original
with open(self.filename) as self.filetoread:
self.txtfilecontent=self.filetoread.read()
self.filetoread.close()
self.text.delete("1.0", Tkinter.END) # Erase the previous Text widget content
self.text.insert("1.0", self.txtfilecontent)
with open(self.filename,'w') as self.filetowrite:
self.filetowrite.write(self.original)
self.filetowrite.close()
def main():
""" Main method to be executed.
Instantiate Begueradj class
"""
root=Tkinter.Tk()
b=Begueradj(root)
root.geometry("300x250+300+300")
root.mainloop()
if __name__=="__main__":
""" Run the application
"""
main()
应用程序演示:
'''
Created on Feb 25, 2016
@author: begueradj
'''
import Tkinter # Tkinter -> tkinter in Python3
import Tkconstants
import tkFileDialog
class Begueradj(Tkinter.Frame):
""" Get text file content and past it into a scrollable Text widget.
Replace the content of the file with the pre-existing Text widget content.
"""
def __init__(self,parent):
""" Set some class variables:
mainly the file dialog interface options.
"""
Tkinter.Frame.__init__(self,parent)
self.parent=parent
# Opening file options
self.file_options={}
self.file_options['defaultextension'] = '.txt'
self.file_options['filetypes'] = [('text files', '.txt'), ('all files', '.*')]
self.file_options['parent'] = self.parent
self.file_options['title'] = 'Open a text file'
self.file_options['initialdir']='/home/'
self.initialize_user_interface()
def initialize_user_interface(self):
""" Design of the user interface.
It mainly consists of a bar menu and a horizontally & vertically
scrollable Text widget in case the text file to read is large.
"""
self.parent.title("Text replacement")
# Set the bar menu and its items
self.menubar=Tkinter.Menu(self.parent)
self.filemenu=Tkinter.Menu(self.menubar,tearoff=0)
self.filemenu.add_command(label="Open",command=self.text_replacement)
self.filemenu.add_command(label="Exit",command=self.parent.quit)
self.menubar.add_cascade(label="File",menu=self.filemenu)
self.parent.config(menu=self.menubar)
self.parent.grid_rowconfigure(0,weight=1)
self.parent.grid_columnconfigure(0,weight=1)
# Set the horizontal and vertical scrollbars
self.hscrollbar=Tkinter.Scrollbar(self.parent,orient=Tkconstants.HORIZONTAL)
self.hscrollbar.grid(row=1,column=0,sticky=Tkinter.E+Tkinter.W)
self.vscrollbar=Tkinter.Scrollbar(self.parent)
self.vscrollbar.grid(row=0,column=1,sticky=Tkinter.N+Tkinter.S)
# Set the Text widget and make it scrollable
self.text=Tkinter.Text(self.parent,wrap=Tkinter.NONE,bd=0,
xscrollcommand=self.hscrollbar.set,
yscrollcommand=self.vscrollbar.set)
self.text.grid(row=0,column=0,sticky=Tkinter.E+Tkinter.W+Tkinter.S+Tkinter.N)
self.text.insert("1.0","Original text here")
self.hscrollbar.config(command=self.text.xview)
self.vscrollbar.config(command=self.text.yview)
def text_replacement(self):
""" Return the name of a file
opened in read mode
"""
self.filename = tkFileDialog.askopenfilename(**self.file_options)
if self.filename:
self.original=self.text.get("0.0","end-1c")
print self.original
with open(self.filename) as self.filetoread:
self.txtfilecontent=self.filetoread.read()
self.filetoread.close()
self.text.delete("1.0", Tkinter.END) # Erase the previous Text widget content
self.text.insert("1.0", self.txtfilecontent)
with open(self.filename,'w') as self.filetowrite:
self.filetowrite.write(self.original)
self.filetowrite.close()
def main():
""" Main method to be executed.
Instantiate Begueradj class
"""
root=Tkinter.Tk()
b=Begueradj(root)
root.geometry("300x250+300+300")
root.mainloop()
if __name__=="__main__":
""" Run the application
"""
main()
演示包括3个屏幕截图,显示:
将原始文本设置到文本小部件和文件对话框窗口中,以拾取要读取的文件
将file1.txt
的内容加载到Tkinter.Text
小部件中
检查文本小部件的原始文件是否保存(替换)在file1.txt中
我创建了一个简单的用户界面,允许您从文件对话框中打开所选的文本文件。出于可伸缩性的原因,我希望稍后将此选项分开设置(例如,如果您将来喜欢阅读文档文件):
我运行的是Linux,所以如果您使用的是MS Windows操作系统,您可以将self.file_选项['initialdir']='/home/'
更改为所需的任何目录路径。请注意,您也可以删除它,在这种情况下,默认情况下,“文件”对话框窗口将提示您到运行应用程序的目录
方法initialize\u user\u interface()。主要是,它提供了一种轻松的方式,通过单击退出应用程序并选择要读取的文件:
self.filemenu.add_command(label="Open",command=self.text_replacement)
self.filemenu.add_command(label="Exit",command=self.parent.quit)
然后可以添加一个文本小部件。最好是有一个可滚动的文本区,以防你无意中发现一个大的内容文件
为此,您需要创建滚动条,并将其附加到文本
self.filemenu.add_command(label="Open",command=self.text_replacement)
self.filemenu.add_command(label="Exit",command=self.parent.quit)
'''
Created on Feb 25, 2016
@author: begueradj
'''
import Tkinter # Tkinter -> tkinter in Python3
import Tkconstants
import tkFileDialog
class Begueradj(Tkinter.Frame):
""" Get text file content and past it into a scrollable Text widget.
Replace the content of the file with the pre-existing Text widget content.
"""
def __init__(self,parent):
""" Set some class variables:
mainly the file dialog interface options.
"""
Tkinter.Frame.__init__(self,parent)
self.parent=parent
# Opening file options
self.file_options={}
self.file_options['defaultextension'] = '.txt'
self.file_options['filetypes'] = [('text files', '.txt'), ('all files', '.*')]
self.file_options['parent'] = self.parent
self.file_options['title'] = 'Open a text file'
self.file_options['initialdir']='/home/'
self.initialize_user_interface()
def initialize_user_interface(self):
""" Design of the user interface.
It mainly consists of a bar menu and a horizontally & vertically
scrollable Text widget in case the text file to read is large.
"""
self.parent.title("Text replacement")
# Set the bar menu and its items
self.menubar=Tkinter.Menu(self.parent)
self.filemenu=Tkinter.Menu(self.menubar,tearoff=0)
self.filemenu.add_command(label="Open",command=self.text_replacement)
self.filemenu.add_command(label="Exit",command=self.parent.quit)
self.menubar.add_cascade(label="File",menu=self.filemenu)
self.parent.config(menu=self.menubar)
self.parent.grid_rowconfigure(0,weight=1)
self.parent.grid_columnconfigure(0,weight=1)
# Set the horizontal and vertical scrollbars
self.hscrollbar=Tkinter.Scrollbar(self.parent,orient=Tkconstants.HORIZONTAL)
self.hscrollbar.grid(row=1,column=0,sticky=Tkinter.E+Tkinter.W)
self.vscrollbar=Tkinter.Scrollbar(self.parent)
self.vscrollbar.grid(row=0,column=1,sticky=Tkinter.N+Tkinter.S)
# Set the Text widget and make it scrollable
self.text=Tkinter.Text(self.parent,wrap=Tkinter.NONE,bd=0,
xscrollcommand=self.hscrollbar.set,
yscrollcommand=self.vscrollbar.set)
self.text.grid(row=0,column=0,sticky=Tkinter.E+Tkinter.W+Tkinter.S+Tkinter.N)
self.text.insert("1.0","Original text here")
self.hscrollbar.config(command=self.text.xview)
self.vscrollbar.config(command=self.text.yview)
def text_replacement(self):
""" Return the name of a file
opened in read mode
"""
self.filename = tkFileDialog.askopenfilename(**self.file_options)
if self.filename:
self.original=self.text.get("0.0","end-1c")
print self.original
with open(self.filename) as self.filetoread:
self.txtfilecontent=self.filetoread.read()
self.filetoread.close()
self.text.delete("1.0", Tkinter.END) # Erase the previous Text widget content
self.text.insert("1.0", self.txtfilecontent)
with open(self.filename,'w') as self.filetowrite:
self.filetowrite.write(self.original)
self.filetowrite.close()
def main():
""" Main method to be executed.
Instantiate Begueradj class
"""
root=Tkinter.Tk()
b=Begueradj(root)
root.geometry("300x250+300+300")
root.mainloop()
if __name__=="__main__":
""" Run the application
"""
main()