-1

I'd like to create a simple, reusable text output window class in Python / Tkinter that functions just like the console output, but with a nicer window.

So far I managed to write text into a ScrolledText widget directly from within the constructor, but that is not what I want.

I'd like to create a print or println method that lets me add text from the main procedure any time.

How can I 'call' the text widget from within the print method?

My main procedure:

    from gui.simpleio import Textwindow 

    a = Textwindow("This is my Textwindow !")
    a.print("I'd like to see a hello from the print method")
    a.stxt.INSERT("but nothing happens")

My Textwindow class in the gui package (simpleio.py):

    from tkinter import Tk, Frame, INSERT
    from tkinter import scrolledtext

    class Textwindow(Frame):

        def __init__(self , title):
            root = Tk()  
            stxt = scrolledtext.ScrolledText(root)
            stxt.pack()
            root.wm_title(title)
            stxt.insert(INSERT,"blah\nblabla\n")
            stxt.insert(INSERT,"yes\nno")
            root.mainloop()

        def print(self,text):
            #self.stxt.insert(INSERT,text)       
            pass
pppery
  • 3,731
  • 22
  • 33
  • 46
Woozle
  • 1
  • Please don't use bold for everything, just for the important things. – Jonah Fleming Nov 08 '15 at 01:36
  • `Textwindow.print()` doesn't work because `self.stxt` isn't defined in `Textwindow.__init__()`. – martineau Nov 08 '15 at 01:55
  • Also, the `__init__` method of `TextWindow` calls `root.mainloop()` so the following `a.print` call won't be executed until the main window is destroyed. – saulspatz Nov 08 '15 at 01:58
  • Take a look at the `errorwindow.py` module in [my answer](http://stackoverflow.com/a/18091356/355230) to the question [_Writing to easygui textbox as function is running_](http://stackoverflow.com/questions/18089506/writing-to-easygui-textbox-as-function-is-running-python). – martineau Nov 08 '15 at 02:06

1 Answers1

0

Give your TextWindow a write method and instance a becomes a file open for writing. Here is simplified version of Lib/idlelib/OutputWindow's OutputWindow.write.

# Act as output file
def write(self, s):
    self.text.insert('insert', s)
    self.text.see('insert')
    self.text.update()
    return len(s)

After adding this, print('Hello in TextWindow', file=a) should work in 3.x or 2.7 with print_function future import.

Terry Jan Reedy
  • 18,414
  • 3
  • 40
  • 52