-1
我想在Python/Tkinter中創建一個簡單的,可重用的文本輸出窗口類,其功能與控制檯輸出類似,但是具有更好的窗口。Python/Tkinter:如何從方法中訪問ScrolledText小部件?
到目前爲止,我設法直接從構造函數中將文本寫入ScrolledText
小部件,但那不是我想要的。
我想創建一個print
或println
方法,讓我隨時添加主程序中的文本。
如何從打印方法中'調用'文本小部件?
我主要程序:
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
請不要使用大膽的一切,只爲重要的事情。 –
'Textwindow.print()'不起作用,因爲self.stxt沒有在'Textwindow .__ init __()'中定義。 – martineau
另外,'TextWindow'的'__init__'方法調用'root.mainloop()',所以在主窗口銷燬之前不會執行下面的'a.print'調用。 – saulspatz