【发布时间】:2017-06-12 15:51:06
【问题描述】:
我在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 输入字符串保持在同一行而不换行?
【问题讨论】:
-
尝试在
"end-1c"的位置插入,而不是END。 -
此代码无法运行。请发布实际、工作代码。如果您编辑代码使其实际运行,它确实会生成一个带有“Hello: World!”的文本小部件,就像您想要的那样。
-
@jasonharper:没必要。在这种情况下,
"end"或END完全可以接受。 -
@BryanOakley 你是对的,对不起。我只是想发布相关代码,但我遗漏了必要的项目。我修复了 OP,它现在正确地说明了问题。 (也许你现在可以改变你的反对票 wink wink)
-
问题不是
insert(),而是print(),它总是在末尾添加'\n'——但这是很自然的。您可以使用end=""打印没有'\n'的文本 - 试试print( 'Hello: ', end='' )。或者在insert()文本之前使用inputStr.strip('\n')。
标签: python python-3.x tkinter text-widget