简体   繁体   中英

Python3 Tkinter Text Widget INSERT on same line

I have a tkinter app in python3 with a Text widget that I insert text into. I would like to append inserted text on the same line as the previous insert, like so:

from tkinter import *

class App :

    def __init__(self):
        sys.stdout.write = self.print_redirect

        self.root = Tk()
        self.root.geometry("900x600")

        self.mainframe = Text(self.root, bg='black', fg='white')
        self.mainframe.grid(column=0, row=0, sticky=(N,W,E,S)) 
        # Set the frame background, font color, and size of the text window
        self.mainframe.grid(column=0, row=0, sticky=(N,W,E,S))

        print( 'Hello: ' )

        print( 'World!' )

    def print_redirect(self, inputStr):
        # add the text to the window widget
        self.mainframe.insert(END, inputStr, None)
        # automtically scroll to the end of the mainframe window
        self.mainframe.see(END)


a = App()
a.root.mainloop()

I would like the resulting insert in the mainframe text widget to look like Hello: World! I'm having a hard time keeping the inserted text on the same line however. Everytime I insert, a new line is generated.

How can I keep the mainframe.insert input string on the same line without a line break?

Problem is not insert() but print() which always add '\\n' at the end - but it is natural.

You can use end="" to print text without '\\n'

print( 'Hello: ', end='' ) 

or directly

sys.stdout.write( 'Hello: ' )

Or in insert() use

inputStr.strip('\n')

But it will remove all '\\n' - even if you will need '\\n' ie.

print( 'Hello:\n\n\n' ) 

You will never know if you have to remove last '\\n' or not.

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