简体   繁体   中英

I tried to redirect stdout to tkinter label widget but text is not updated correctly

Here is what is bugging me: I try to redirect stdout to tkinter Label .... and it doesn't work. When I press button instead of "Button clicked" I got only blank space. The weirdest thing is when I use file to store output and then I read it and put file text in Label everything just work! My question: why directly redirection of stdout doesn't work for widget here?

from tkinter import *
import sys


class MyLab(Label):
    def write(self, txt):
        '''here is a deal when I use this >hack< label is updated:'''
        f=open("test.txt","a")
        f.write(txt)
        f.close()
        f=open("test.txt")
        x = f.readlines()[-1]
        self.config(text=x) # this works!

   #     self.config(text=txt) # but this doesn't .... of course you need
   #     to  switch off above 'file' method
        f.close()



root = Tk()

w = MyLab(root, text="1st", height=5, width = 20)
sys.stdout = w #redirecting stdout to MyLab instance
t = Entry(root, text='cos')

def btn_clck():
    print('Button clicked!!!') # text should be puted in label

b = Button(root, text='PRESS ME', command = btn_clck, height = 5, width = 20)
b.pack()
t.pack()
w.pack()

root.mainloop()

It actually does set the label text as you've requested, but then changes the text to a newline character with a second call to write because that's the string terminator - see the Python 3 docs for print() .

You could modify the write() method to only set the text if it's not a single newline:

class MyLab(Label):
    def write(self, txt):
        if txt != "\n": self.config(text=txt)

Or you could change the print() call to pass an empty string as a terminator and then write() could be simpler:

def btn_clck():
    print('Button clicked!!!', end='')

class MyLab(Label):
    def write(self, txt):
        if txt: self.config(text=txt)

You could even think about overriding the Label class config() method to only update the text option if the provided argument isn't empty or a newline...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM