有没有一个例子说明如何在Python中设置日志记录到Tkinter Text Widget?我已经看到这在几个应用程序中使用但无法弄清楚如何将日志记录指向除日志文件之外的任何其他内容。
答案 0 :(得分:10)
除了上面的答案之外:尽管有很多建议的解决方案(在这里以及在this other thread中),但我自己也在努力完成这项工作。最终我遇到this text handler class by Moshe Kaplan,它使用ScrolledText小部件(这可能比ScrollBar方法更容易)。
花了一些时间来弄清楚如何在线程应用程序中实际使用Moshe的类。最后,我创建了一个最小的演示脚本,演示如何使其全部工作。因为它可能对其他人有帮助,我将在下面分享。在我的特定情况下,我想记录两者 GUI和文本文件;如果您不需要,只需删除 logging.basicConfig 中的 filename 属性即可。
import time
import threading
import logging
try:
import tkinter as tk # Python 3.x
import tkinter.scrolledtext as ScrolledText
except ImportError:
import Tkinter as tk # Python 2.x
import ScrolledText
class TextHandler(logging.Handler):
# This class allows you to log to a Tkinter Text or ScrolledText widget
# Adapted from Moshe Kaplan: https://gist.github.com/moshekaplan/c425f861de7bbf28ef06
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 emit(self, record):
msg = self.format(record)
def append():
self.text.configure(state='normal')
self.text.insert(tk.END, msg + '\n')
self.text.configure(state='disabled')
# Autoscroll to the bottom
self.text.yview(tk.END)
# This is necessary because we can't modify the Text from other threads
self.text.after(0, append)
class myGUI(tk.Frame):
# This class defines the graphical user interface
def __init__(self, parent, *args, **kwargs):
tk.Frame.__init__(self, parent, *args, **kwargs)
self.root = parent
self.build_gui()
def build_gui(self):
# Build GUI
self.root.title('TEST')
self.root.option_add('*tearOff', 'FALSE')
self.grid(column=0, row=0, sticky='ew')
self.grid_columnconfigure(0, weight=1, uniform='a')
self.grid_columnconfigure(1, weight=1, uniform='a')
self.grid_columnconfigure(2, weight=1, uniform='a')
self.grid_columnconfigure(3, weight=1, uniform='a')
# Add text widget to display logging info
st = ScrolledText.ScrolledText(self, state='disabled')
st.configure(font='TkFixedFont')
st.grid(column=0, row=1, sticky='w', columnspan=4)
# Create textLogger
text_handler = TextHandler(st)
# Logging configuration
logging.basicConfig(filename='test.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# Add the handler to logger
logger = logging.getLogger()
logger.addHandler(text_handler)
def worker():
# Skeleton worker function, runs in separate thread (see below)
while True:
# Report time / date at 2-second intervals
time.sleep(2)
timeStr = time.asctime()
msg = 'Current time: ' + timeStr
logging.info(msg)
def main():
root = tk.Tk()
myGUI(root)
t1 = threading.Thread(target=worker, args=[])
t1.start()
root.mainloop()
t1.join()
main()
Github Gist链接到上面的代码:
https://gist.github.com/bitsgalore/901d0abe4b874b483df3ddc4168754aa
答案 1 :(得分:9)
你应该继承logging.Handler
,例如:
import logging
from Tkinter import INSERT
class WidgetLogger(logging.Handler):
def __init__(self, widget):
logging.Handler.__init__(self)
self.widget = widget
def emit(self, record):
# Append message (record) to the widget
self.widget.insert(INSERT, record + '\n')
答案 2 :(得分:7)
我建立在Yuri的想法上,但需要做一些改变才能让事情发挥作用:
import logging
import Tkinter as tk
class WidgetLogger(logging.Handler):
def __init__(self, widget):
logging.Handler.__init__(self)
self.setLevel(logging.INFO)
self.widget = widget
self.widget.config(state='disabled')
def emit(self, record):
self.widget.config(state='normal')
# Append message (record) to the widget
self.widget.insert(tk.END, self.format(record) + '\n')
self.widget.see(tk.END) # Scroll to the bottom
self.widget.config(state='disabled')
请注意,为了使Text
窗口小部件为只读,必须在“正常”和“禁用”之间来回切换状态。
答案 3 :(得分:2)
也建立在福特的基础上,但添加彩色文字!
public interface ISqlType
{
string getHeader();
}
public class SqlProc : ISqlType
{
public string getHeader()
{
return "I'm a SqlProc!"
}
}
public class SqlFunction : ISqlType
{
public string getHeader()
{
return "I'm a SqlFunction!"
}
}
public class SqlView : ISqlType
{
public string getHeader()
{
return "I'm a SqlView!"
}
}
ISqlType objSqlType;
switch (type)
{
case ObjectType.PROC:
objSqlType = new SqlProc();
break;
case ObjectType.FUNCTION:
objSqlType = new SqlFunction();
break;
case ObjectType.VIEW:
objSqlType = new SqlView();
break;
default:
break;
}
string header = objSqlType.getHeader();
答案 4 :(得分:1)
进一步建立福特的答案,这里有一个滚动的文本小部件,用于记录日志。 logging_handler
成员是您添加到记录器的成员。
import logging
from Tkinter import END, N, S, E, W, Scrollbar, Text
import ttk
class LoggingHandlerFrame(ttk.Frame):
class Handler(logging.Handler):
def __init__(self, widget):
logging.Handler.__init__(self)
self.setFormatter(logging.Formatter("%(asctime)s: %(message)s"))
self.widget = widget
self.widget.config(state='disabled')
def emit(self, record):
self.widget.config(state='normal')
self.widget.insert(END, self.format(record) + "\n")
self.widget.see(END)
self.widget.config(state='disabled')
def __init__(self, *args, **kwargs):
ttk.Frame.__init__(self, *args, **kwargs)
self.columnconfigure(0, weight=1)
self.columnconfigure(1, weight=0)
self.rowconfigure(0, weight=1)
self.scrollbar = Scrollbar(self)
self.scrollbar.grid(row=0, column=1, sticky=(N,S,E))
self.text = Text(self, yscrollcommand=self.scrollbar.set)
self.text.grid(row=0, column=0, sticky=(N,S,E,W))
self.scrollbar.config(command=self.text.yview)
self.logging_handler = LoggingHandlerFrame.Handler(self.text)
答案 5 :(得分:1)
我遇到了同样的问题。找到的常见解决方案就像在该线程中提到的那样-将小部件从GUI模块带到Logging.Handler。
由于将小部件传递到另一个线程(日志记录),因此有人批评它不安全。
找到的最佳解决方案是使用Benjamin Bertrand制作的队列:
https://beenje.github.io/blog/posts/logging-to-a-tkinter-scrolledtext-widget/。
我做了一些改进:应该在日志处理程序中创建队列,并将其传递给GUI小部件。
import logger import queue class QueueHandler(logging.Handler): def __init__(self): super().__init__() self.log_queue = queue.Queue() def emit(self, record): # put a formatted message to queue self.log_queue.put(self.format(record)) queue_handler = QueueHandler() logger.addHandler(queue_handler)
因此,我们拥有通常可用的记录器,任何模块中的每个日志消息都将与其他处理程序一起传递给queue_handler-传递给文件等。
现在我们可以将queue_handler导入小部件。
大部分代码来自上面的链接,我只是更改了原始日志记录队列的位置。
from tkinter.scrolledtext import ScrolledText from some_logging_module import queue_handler class ConsoleUi: """Poll messages from a logging queue and display them in a scrolled text widget""" def __init__(self, frame, queue): self.frame = frame # Create a ScrolledText wdiget self.console = ScrolledText(frame) self.console.configure(font='TkFixedFont') self.console.pack(padx=10, pady=10, fill=BOTH, expand=True) self.log_queue = queue # Start polling messages from the queue self.frame.after(100, self.poll_log_queue) def display(self, msg): self.console.configure(state='normal') self.console.insert(END, msg + '\n') self.console.configure(state='disabled') # Autoscroll to the bottom self.console.yview(END) def poll_log_queue(self): # Check every 100ms if there is a new message in the queue to display while not self.log_queue.empty(): msg = self.log_queue.get(block=False) self.display(msg) self.frame.after(100, self.poll_log_queue)
结果是,小部件显示了应用程序的所有日志记录数据。