【问题标题】:Integrating file and text widget python/tkinter集成文件和文本小部件 python/tkinter
【发布时间】:2016-06-06 23:47:29
【问题描述】:

场景是我想要:

  1. -打开一个特定的文本文件
  2. -从文本文件中导入文本以显示在文本小部件中
  3. -然后是文本小部件中的文本,然后将之前文本文件中的内容替换为文本小部件中的当前内容。

目前我已经研究出如何在文本小部件中打开特定的文本文件并使其显示,但是我不知道如何做最后一步。

我试图定义一个“保存”功能,但没有得到任何地方,你可以在下面看到这个。

第 1 步和第 2 步的当前代码:

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

如果有人可以在这里帮助我,那就太好了

大家好

【问题讨论】:

  • 您阅读过文本小部件的文档吗?问题是您不知道如何获取文本,还是您不知道如何将文本保存到文件?你做了什么研究?
  • @BryanOakley 我发现了如何在文本小部件中打开文本文件。我现在希望能够在文本小部件中将更多文本添加到打开的内容中,然后将其全部保存在文本文件中(替换之前的内容)。我曾尝试对此进行研究,这就是我首先发现如何在文本小部件中打开文本文件的方法:)

标签: python file tkinter widget


【解决方案1】:

一旦您知道Widget indices 的工作原理并且您知道insertget methods on the Text widget

starting_text = "THIS WOULD COME FROM A FILE"
...
textbox = TEXT_WIDGET_SETUP_ALREADY

textbox.insert("1.0",starting_text)
...

ending_text = textbox.get("1.0","end-1c")

棘手的部分是在程序关闭时访问文本,但在小部件销毁后不访问(或者您收到_tkinter.TclError: invalid command name ".4384096888" 错误):

import tkinter as tk

class Text(tk.Text):
    def destroy(self):
        global ending_text
        ending_text = self.get("1.0","end-1c")
        super(Text,self).destroy()

虽然如果您使用from tkinter import * 表示法,您将需要调用您的类而不是Text,并且可能不使用ending_text 作为全局变量,但这是展示如何做到这一点的最简单方法.


这是我用于测试 IO 的完整代码,尽管如果您不了解如何处理已经存在的文件,references elsewhere

import tkinter as tk


filename = "test.txt"

class Text(tk.Text):
    def destroy(self):
        global ending_text
        ending_text = self.get("1.0","end-1c")
        super(Text,self).destroy()
try:
    with open(filename) as f:
        text = f.read()
except IOError:
    text = ""

root = tk.Tk()

textbox = Text(root)
textbox.insert("1.0",text)
textbox.grid()

#this would probably just be put in the destroy method
def finish(event=None):
    with open(filename,"w") as f:
        f.write(ending_text)

textbox.bind("<Destroy>",finish) #this will happen after Text.destroy() so textbox.get() fails if used from this point
root.mainloop()

【讨论】:

  • 很大的帮助,我会比较代码并进行必要的更改,如果我需要问其他任何问题,我知道该问谁,感谢您的赞赏并感谢您的宝贵时间
  • 文本小部件中的第一个索引是"1.0",而不是"0.0"。此外,您应该使用"end-1c" 而不是"end"。使用"end",您将获得一个不属于原始数据的额外换行符,因为 tkinter 始终保证小部件中的最后一个字符是换行符。
  • @Bryan Oakley,我忘记了 tkinter 从 1 开始行,很长一段时间都不需要我提供的参考,但我不知道 "end-1c" 和换行符,我将编辑答案.
【解决方案2】:

我创建了一个简单的用户界面,允许您从文件对话框中打开您选择的文本文件。出于可扩展性的原因,我更喜欢稍后将其选项设置为分开(例如,如果您将来希望改为读取文档文件):

        # 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/'

我正在运行 Linux,所以如果您使用的是 MS Windows 操作系统,您可以将 self.file_options['initialdir']='/home/' 更改为您想要的任何目录路径。请注意,您也可以将其删除,在这种情况下,文件对话框窗口将提示您进入运行应用程序的目录,默认情况下。

initialize_user_interface() 方法的作用正如其名称所反映的那样。主要是,它提供了一种舒适的方式来单击退出应用程序并选择要读取的文件:

       self.filemenu.add_command(label="Open",command=self.text_replacement)
       self.filemenu.add_command(label="Exit",command=self.parent.quit)

然后您可以添加一个文本小部件。最好有一个可滚动的文本区域,以防您偶然发现大型内容文件。

为此,您需要创建滚动条,并将其附加到 Text 小部件,因为 Text 小部件不维护自己的滚动条。

这是完整的程序:

'''
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 个屏幕截图组成:

  1. 将原始文本设置到“文本”小部件和一个文件对话框窗口中,用于选择要读取的文件。
  2. file1.txt的内容加载到Tkinter.Text小部件中
  3. 检查Text小部件的原始文件是否保存(替换)在file1.txt

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    相关资源
    最近更新 更多