Python3 Tkinter 文本小部件在同一行插入
Python3 Tkinter Text Widget INSERT on same line
我在 python3
中有一个 tkinter
应用程序,其中包含一个文本小部件,我可以在其中插入文本。我想将插入的文本追加到与之前插入的文本相同的行中,如下所示:
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!
但是,我很难将插入的文本保持在同一行上。每次我插入时,都会生成一个新行。
如何让 mainframe.insert 输入字符串不换行地保持在同一行?
问题不是 insert()
,而是 print()
,它总是在末尾添加 '\n'
- 但这是自然的。
您可以使用 end=""
打印没有 '\n'
的文本
print( 'Hello: ', end='' )
或直接
sys.stdout.write( 'Hello: ' )
或在 insert()
中使用
inputStr.strip('\n')
但它会删除所有 '\n'
- 即使您需要 '\n'
即
print( 'Hello:\n\n\n' )
您永远不会知道是否必须删除最后一个 '\n'
。
我在 python3
中有一个 tkinter
应用程序,其中包含一个文本小部件,我可以在其中插入文本。我想将插入的文本追加到与之前插入的文本相同的行中,如下所示:
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!
但是,我很难将插入的文本保持在同一行上。每次我插入时,都会生成一个新行。
如何让 mainframe.insert 输入字符串不换行地保持在同一行?
问题不是 insert()
,而是 print()
,它总是在末尾添加 '\n'
- 但这是自然的。
您可以使用 end=""
打印没有 '\n'
的文本
print( 'Hello: ', end='' )
或直接
sys.stdout.write( 'Hello: ' )
或在 insert()
中使用
inputStr.strip('\n')
但它会删除所有 '\n'
- 即使您需要 '\n'
即
print( 'Hello:\n\n\n' )
您永远不会知道是否必须删除最后一个 '\n'
。