Tkinter - 在文本控件中记录文本
我想创建一个可以在文本小部件中“记录”文本的类。其他应用程序可以使用这个类来发送和显示日志信息到这个文本小部件。
class TraceConsole():
def __init__(self):
# Init the main GUI window
self._logFrame = Tk.Frame()
self._log = Tk.Text(self._logFrame, wrap=Tk.NONE, setgrid=True)
self._scrollb = Tk.Scrollbar(self._logFrame, orient=Tk.VERTICAL)
self._scrollb.config(command = self._log.yview)
self._log.config(yscrollcommand = self._scrollb.set)
# Grid & Pack
self._log.grid(column=0, row=0)
self._scrollb.grid(column=1, row=0, sticky=Tk.S+Tk.N)
self._logFrame.pack()
def log(self, msg, level=None):
# Write on GUI
self._log.insert('end', msg + '\n')
def exitWindow(self):
# Exit the GUI window and close log file
print('exit..')
使用示例:
t = TraceConsole()
t.log('hello world!')
我现在的问题是,我不知道该把主循环放在哪里。这个记录器必须在“后台”运行,并且应该能够在任何时候写入日志,直到窗口关闭为止。
2 个回答
0
在这种情况下,你创建了一个可以在应用程序中使用的组件。主循环会在那个应用程序中被调用,然后它会向你的日志小部件写入信息。
你可以在和TraceConsole同一个Python文件里添加一些简单的使用示例(比如你给出的那个)和/或测试,使用类似下面的代码:
if __name__ == '__main__':
m = tkinter.Tk()
t = TraceConsole()
t.log('hello world!')
m.mainloop()
我通常会这样做,这样我就可以单独测试一个tkinter组件,然后再把它放进我的应用程序里。
3
我在这方面花了一些时间,但最终找到了这里的建议:
下面我有一个例子,是我为了说明如何在图形界面控制中记录日志而创建的。这个例子会将日志信息记录到一个文本框中,正如你所要求的,但你也可以通过替换或复制类 MyHandlerText
来将日志信息发送到其他图形界面组件,比如 MyHandlerLabel
、MyHandlerListbox
等等(你可以为处理类选择自己喜欢的名字)。这样你就可以为各种你感兴趣的图形界面控件创建处理器。对我来说,最大的“顿悟”时刻是 python.org 提倡的模块级 getLogger
概念。
import Tkinter
import logging
import datetime
# this item "module_logger" is visible only in this module,
# (but you can also reference this getLogger instance from other modules and other threads by passing the same argument name...allowing you to share and isolate loggers as desired)
# ...so it is module-level logging and it takes the name of this module (by using __name__)
# recommended per https://docs.python.org/2/library/logging.html
module_logger = logging.getLogger(__name__)
class simpleapp_tk(Tkinter.Tk):
def __init__(self,parent):
Tkinter.Tk.__init__(self,parent)
self.parent = parent
self.grid()
self.mybutton = Tkinter.Button(self, text="ClickMe")
self.mybutton.grid(column=0,row=0,sticky='EW')
self.mybutton.bind("<ButtonRelease-1>", self.button_callback)
self.mytext = Tkinter.Text(self, state="disabled")
self.mytext.grid(column=0, row=1)
def button_callback(self, event):
now = datetime.datetime.now()
module_logger.info(now)
class MyHandlerText(logging.StreamHandler):
def __init__(self, textctrl):
logging.StreamHandler.__init__(self) # initialize parent
self.textctrl = textctrl
def emit(self, record):
msg = self.format(record)
self.textctrl.config(state="normal")
self.textctrl.insert("end", msg + "\n")
self.flush()
self.textctrl.config(state="disabled")
if __name__ == "__main__":
# create Tk object instance
app = simpleapp_tk(None)
app.title('my application')
# setup logging handlers using the Tk instance created above
# the pattern below can be used in other threads...
# ...to allow other thread to send msgs to the gui
# in this example, we set up two handlers just for demonstration (you could add a fileHandler, etc)
stderrHandler = logging.StreamHandler() # no arguments => stderr
module_logger.addHandler(stderrHandler)
guiHandler = MyHandlerText(app.mytext)
module_logger.addHandler(guiHandler)
module_logger.setLevel(logging.INFO)
module_logger.info("from main")
# start Tk
app.mainloop()