2015-11-08 135 views
-1

我想在Python/Tkinter中創建一個簡單的,可重用的文本輸出窗口類,其功能與控制檯輸出類似,但是具有更好的窗口。Python/Tkinter:如何從方法中訪問ScrolledText小部件?

到目前爲止,我設法直接從構造函數中將文本寫入ScrolledText小部件,但那不是我想要的。

我想創建一個printprintln方法,讓我隨時添加主程序中的文本。

如何從打印方法中'調用'文本小部件?

主要程序:

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") 

Textwindow類在GUI包(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 
+0

請不要使用大膽的一切,只爲重要的事情。 –

+0

'Textwindow.print()'不起作用,因爲self.stxt沒有在'Textwindow .__ init __()'中定義。 – martineau

+0

另外,'TextWindow'的'__init__'方法調用'root.mainloop()',所以在主窗口銷燬之前不會執行下面的'a.print'調用。 – saulspatz

回答

0

給你TextWindo寫入方法和實例a成爲可寫入的文件。這是Lib/idlelib/OutputWindow的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) 

添加後,print('Hello in TextWindow', file=a)應該在3.x或2.7中使用print_function future import。

相關問題