I\'m trying to redirect the stdout of a function to a tkinter text widget. The problem I am running into is that it writes each line to a new window instead of listing every
The fix is simple: don't create more than one redirector. The whole point of the redirector is that you create it once, and then normal print statements will show up in that window.
You'll need to make a couple of small changes to your redirector
function. First, it shouldn't call Tk
; instead, it should create an instance of Toplevel
since a tkinter program must have exactly one root window. Second, you must pass a text widget to IORedirector
since it needs to know the exact widget to write to.
def redirector(inputStr=""):
import sys
root = Toplevel()
T = Text(root)
sys.stdout = StdoutRedirector(T)
T.pack()
T.insert(END, inputStr)
Next, you should only call this function a single time. From then on, to have data appear in the window you would use a normal print
statement.
You can create it in the main block of code:
win = Tk()
...
r = redirector()
win.mainloop()
Next, you need to modify the write
function, since it must write to the text widget:
class StdoutRedirector(IORedirector):
'''A class for redirecting stdout to this Text widget.'''
def write(self,str):
self.text_area.insert("end", str)
Finally, change your Zerok
function to use print statements:
def Zerok():
...
if os.stat(filename).st_size==0:
print(filename)
else:
print("There are no empty files in that Directory")
break