[英]Fully mimic stdout in tkinter text widget to support the end parameter from Python's print function
How do I fully mimic sys.stdout
in a tkinter text widget so that I can use the print()
function (mainly the end
parameter) to its full capacity? 如何在tkinter文本小部件中完全模仿sys.stdout
,以便我可以将print()
函数(主要是end
参数)用于其全部容量? So that I can use print("Hello World", end='\\r')
to print to the text widget where if I print something else it will overwrite the previously printed text. 这样我就可以使用print("Hello World", end='\\r')
打印到文本小部件,如果我打印其他内容,它将覆盖以前打印的文本。
class Main:
def __init__(self):
self.master = tk.Tk()
self.output = tk.Text(self.master)
self.output.pack()
sys.stdout = self
self.master.mainloop()
def write(self, txt):
self.output.insert(tk.INSERT, str(txt))
self.output.see('end')
def flush(self):
# What do I do here?
Running 运行
print("Hello World", end='\r')
print("Goodbye World", end='\r')
Gives the following in the text widget 在文本小部件中提供以下内容
Hello World
Goodbye World
But I expect it to show the following instead 但我希望它能显示以下内容
Goodbye World
As a bonus question, how would I (re)define the flush functionality of stdout to work with a tkinter text widget? 作为一个额外的问题,我如何(重新)定义stdout的刷新功能以使用tkinter文本小部件?
I fixed the problem with the return carriage by updating the write function with the following: 我通过使用以下更新write函数修复了返回托架的问题:
def write(self, txt):
if '\r' in txt:
self.return_carriage = True
return
if self.return_carriage:
self.output.delete(tk.INSERT + " linestart", tk.INSERT + " lineend")
self.return_carriage = False
self.output.insert(tk.INSERT, str(txt))
self.output.see('end')
This only solves the problem when using end='\\r'
in the print()
function though. 这只能解决在print()
函数中使用end='\\r'
时的问题。 This still does not mimic the full sys.stdout.write
functionality. 这仍然不能模仿完整的sys.stdout.write
功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.