我有一个简单的应用程序,其中包含一个表示数据结构的类和一个用于 GUI 的类。我在第一个类中使用了一个记录器:
class A(object):
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)
self.logger.info('creating new A object')
等等
GUI 包含在一个带有列表框的 Tkinter 窗口中。
如何将日志定向到列表框?我希望看到消息填充列表而不是因为它们被记录而不是显示在控制台或日志文件中。
如何在执行类中的方法时更新列表框?
最佳答案
在这种情况下,最好实现您自己的 logging.Handler:
from logging import Handler, getLogger
class ListboxHandler(Handler):
def __init__(self, box):
self._box = box
Handler.__init__(self)
def emit(self, record):
r = self.format(record)
self._box.insert(0, r)
# quick test:
target = [] # supports insert like Listbox :)
rootLogger = getLogger()
# add handler to the root logger here
# should be done in the config...
rootLogger.addHandler(ListboxHandler(target))
rootLogger.warn('test')
print(target)
这样您就可以从您的配置中完全控制格式、日志级别等。
关于python - 如何将 python 记录器定向到 Tkinker 的列表框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10311755/