Python3 Tkinter Text Widget INSERT在同一行

sad*_*ave 1 python tkinter python-3.x text-widget

我有一个带有文本小部件的tkinter应用程序python3,我插入了文本.我想在与前一个插入相同的行上添加插入的文本,如下所示:

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()
Run Code Online (Sandbox Code Playgroud)

我希望在大型机文本小部件中生成的插入看起来像Hello: World! 我很难将插入的文本保持在同一行上.每次插入时,都会生成一个新行.

如何将mainframe.insert输入字符串保留在同一行而不换行?

fur*_*ras 5

问题不是,insert()print()总是'\n'在最后添加- 但这很自然.

您可以使用end=""不打印文本'\n'

print( 'Hello: ', end='' ) 
Run Code Online (Sandbox Code Playgroud)

或直接

sys.stdout.write( 'Hello: ' )
Run Code Online (Sandbox Code Playgroud)

或者在insert()使用中

inputStr.strip('\n')
Run Code Online (Sandbox Code Playgroud)

但它会删除所有'\n'- 即使你需要'\n'ie.

print( 'Hello:\n\n\n' ) 
Run Code Online (Sandbox Code Playgroud)

你永远不会知道你是否必须删除最后一次'\n'.