emayecs | 5656b2b | 2021-08-04 12:44:13 -0400 | [diff] [blame] | 1 | #!/usr/bin/env python3 |
Tim Edwards | 55f4d0e | 2020-07-05 15:41:02 -0400 | [diff] [blame] | 2 | # |
| 3 | #-------------------------------------------------------- |
| 4 | """ |
| 5 | consoletext --- extends tkinter class Text |
| 6 | with stdout and stderr redirection. |
| 7 | """ |
| 8 | #-------------------------------------------------------- |
| 9 | # Written by Tim Edwards |
| 10 | # efabless, inc. |
| 11 | # September 11, 2016 |
| 12 | # Version 0.1 |
| 13 | #-------------------------------------------------------- |
| 14 | |
| 15 | import sys |
| 16 | import tkinter |
| 17 | |
| 18 | class ConsoleText(tkinter.Text): |
emayecs | 5966a53 | 2021-07-29 10:07:02 -0400 | [diff] [blame] | 19 | linelimit = 10000 |
Tim Edwards | 55f4d0e | 2020-07-05 15:41:02 -0400 | [diff] [blame] | 20 | class IORedirector(object): |
| 21 | '''A general class for redirecting I/O to this Text widget.''' |
| 22 | def __init__(self,text_area): |
| 23 | self.text_area = text_area |
| 24 | |
| 25 | class StdoutRedirector(IORedirector): |
| 26 | '''A class for redirecting stdout to this Text widget.''' |
| 27 | def write(self,str): |
| 28 | self.text_area.write(str,False) |
| 29 | |
| 30 | class StderrRedirector(IORedirector): |
| 31 | '''A class for redirecting stderr to this Text widget.''' |
| 32 | def write(self,str): |
| 33 | self.text_area.write(str,True) |
| 34 | |
| 35 | def __init__(self, master=None, cnf={}, **kw): |
| 36 | '''See the __init__ for Tkinter.Text.''' |
| 37 | |
| 38 | tkinter.Text.__init__(self, master, cnf, **kw) |
| 39 | |
| 40 | self.tag_configure('stdout',background='white',foreground='black') |
| 41 | self.tag_configure('stderr',background='white',foreground='red') |
| 42 | # None of these works! Cannot change selected text background! |
| 43 | self.config(selectbackground='blue', selectforeground='white') |
| 44 | self.tag_configure('sel',background='blue',foreground='white') |
| 45 | |
| 46 | def write(self, val, is_stderr=False): |
| 47 | lines = int(self.index('end-1c').split('.')[0]) |
| 48 | if lines > self.linelimit: |
| 49 | self.delete('1.0', str(lines - self.linelimit) + '.0') |
| 50 | self.insert('end',val,'stderr' if is_stderr else 'stdout') |
| 51 | self.see('end') |
| 52 | |
| 53 | def limit(self, val): |
| 54 | self.linelimit = val |