Skip to content

Instantly share code, notes, and snippets.

@moshekaplan
Last active February 25, 2024 01:33
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save moshekaplan/c425f861de7bbf28ef06 to your computer and use it in GitHub Desktop.
Save moshekaplan/c425f861de7bbf28ef06 to your computer and use it in GitHub Desktop.
A Logging Handler that allows logging to a Tkinter Text Widget
#!/usr/bin/env python
# Built-in modules
import logging
import Tkinter
import threading
class TextHandler(logging.Handler):
"""This class allows you to log to a Tkinter Text or ScrolledText widget"""
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(Tkinter.END, msg + '\n')
self.text.configure(state='disabled')
# Autoscroll to the bottom
self.text.yview(Tkinter.END)
# This is necessary because we can't modify the Text from other threads
self.text.after(0, append)
# Sample usage
if __name__ == '__main__':
# Create the GUI
root = Tkinter.Tk()
import ScrolledText
st = ScrolledText.ScrolledText(root, state='disabled')
st.configure(font='TkFixedFont')
st.pack()
# Create textLogger
text_handler = TextHandler(st)
# Add the handler to logger
logger = logging.getLogger()
logger.addHandler(text_handler)
# Log some messages
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')
root.mainloop()
@larryfast
Copy link

This is a nice simple example but it is not thread safe. Look here for a thread safe example that sets up a logging.Handler with a Queue to receive messages from other TK threads: https://github.com/beenje/tkinter-logging-text-widget

@moshekaplan
Copy link
Author

moshekaplan commented Feb 8, 2024 via email

@lunaeidi
Copy link

Hello, I'm wondering if you know if this could cause the GUI to freeze? perhaps because of not multithreading? Thanks!

@moshekaplan
Copy link
Author

I am not aware of any issues, but I haven't had to use this code in nearly a decade, so it's possible Python 3 has changed something significant that I'm unaware of.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment