Python Logging to Tkinter Text Widget

后端 未结 6 1856
悲哀的现实
悲哀的现实 2020-12-14 16:46

Does any one out there have an example of how to setup logging in Python to a Tkinter Text Widget? I have seen this used in several apps but cannot figure out how to direct

6条回答
  •  悲哀的现实
    2020-12-14 17:39

    Building on ford's too but adding colored text !

    class WidgetLogger(logging.Handler):
        def __init__(self, widget):
            logging.Handler.__init__(self)
            self.setLevel(logging.DEBUG)
            self.widget = widget
            self.widget.config(state='disabled')
            self.widget.tag_config("INFO", foreground="black")
            self.widget.tag_config("DEBUG", foreground="grey")
            self.widget.tag_config("WARNING", foreground="orange")
            self.widget.tag_config("ERROR", foreground="red")
            self.widget.tag_config("CRITICAL", foreground="red", underline=1)
    
            self.red = self.widget.tag_configure("red", foreground="red")
        def emit(self, record):
            self.widget.config(state='normal')
            # Append message (record) to the widget
            self.widget.insert(tk.END, self.format(record) + '\n', record.levelname)
            self.widget.see(tk.END)  # Scroll to the bottom
            self.widget.config(state='disabled') 
            self.widget.update() # Refresh the widget
    

提交回复
热议问题