我有一个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()
我希望在大型框架文本小部件中生成的插入看起来像Hello: World!
但是我很难将插入的文本保持在同一行上。 每次插入时,都会生成一个新行。
如何将大型机插入输入字符串保留在同一行上而不换行?
问题不在于insert()
,而在于总是在末尾添加'n'
print()
- 但这是很自然的。
您可以使用end=""
打印文本,而无需'n'
print( 'Hello: ', end='' )
或直接
sys.stdout.write( 'Hello: ' )
或insert()
使用
inputStr.strip('n')
但它会删除所有'n'
- 即使你需要'n'
即。
print( 'Hello:nnn' )
您永远不会知道是否必须删除最后一个'n'
。