我有一個ScrolledText小部件,其中輸出所有日誌消息。由於有很多,並且這個程序運行了幾個小時,它會被超載。限制作爲日誌工作的ScrolledText中的行數
我需要一種限制行數的方式,比如400行。
我試圖清除文字是這樣的:
self.mytext.delete(1.0, END)
但它不會做任何事情。
我的繼承人設置:
class XStatusFrame:
def __init__(self, master, window):
self.frame = Frame(master, relief="raised", width=950)
self.frame.grid(row=4,column=0,sticky=(E,W),columnspan=20,rowspan=2)
self.clear_btn = Button(self.frame,text="Clear Log", command=lambda: self.clear_log())
self.clear_btn.pack(side=TOP, anchor=W)
# text widget
self.mytext = ScrolledText(self.frame, undo=True,state="disabled", fg="white", bg="black")
#self.mytext = Text(self.frame, state="disabled", fg="white", bg="black")
self.mytext.pack(fill=X)
# Create textLogger
text_handler = TextHandler(self.mytext)
# Add the handler to logger
self.logger = logging.getLogger()
self.logger.addHandler(text_handler)
def clear_log(self):
self.mytext.delete(1.0, END)
class TextHandler(logging.Handler):
def __init__(self, text):
# run the regular Handler __init__
logging.Handler.__init__(self)
# Store a reference to the Text it will log to
self.text = text
def num_lines(self):
return int(self.text.index('end').split('.')[0]) - 1
def emit(self, record):
msg = self.format(record)
def append():
self.text.configure(state='normal')
self.text.insert(END, "["+self.timestamp()+"]["+str(self.num_lines())+"] "+msg + '\n')
self.text.configure(state='disabled')
# Autoscroll to the bottom
self.text.yview(END)
# This is necessary because we can't modify the Text from other threads
self.text.after(0, append)
# MY Try at limiting number of lines, which doesnt work...
if self.num_lines() > 5:
self.text.delete("1.0", END)
def timestamp(self):
ts = time.time()
return datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')