text widget example?

James Stroud jstroud at mbi.ucla.edu
Mon Nov 7 03:22:47 CET 2005


On Sunday 06 November 2005 16:25, wanwan wrote:
> I need my GUI to open and display a text file. I'm thinking of using a
> text widget but it looks so complicated in the tkinter manual.
>
> question I have is:
>
> is there an example anyone can find on the internet?

Couldn't find a good one, so here's a 5 minute version (your exercise is to 
put in a scroll bar). See:

        http://www.pythonware.com/library/tkinter/introduction/

James

from Tkinter import *
import tkFileDialog
import tkMessageBox 

class MyText(Frame):
  def __init__(self, parent=None, *args, **kwargs):
    Frame.__init__(self, parent)
    self.pack()
    self.text = Text(self, *args, **kwargs)
    self.text.config(background='white')
    self.text.pack(expand=YES, fill=BOTH)
  def get(self):
    return self.text.get(1.0,"%s-1c" % END)
  def set(self, astr):
    self.text.delete(1.0, END)
    self.text.insert(INSERT, astr)
  def set_from_file(self):
    afilename = tkFileDialog.askopenfilename()
    if afilename:
      try:
        afile = open(afilename)
        self.set(afile.read())
        afile.close()
      except Exception, e:
        tkMessageBox.showwarning("File Problem",
           "Couldn't read file '%s': %s" % (afilename, str(e)))

def main():
  tk = Tk()
  tk.title('Text Reader App')
  atext = MyText(tk)
  atext.pack()
  open_button = Button(tk, text="Open File",
                       activeforeground='blue',
                       command=atext.set_from_file)
  open_button.pack()
  tk.mainloop()

if __name__ == "__main__":
  main()




-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list