[英]Is there a way to overwrite the previous print to Text in tkinter?
There's a simple program that have two text and one button widgets.有一个简单的程序,它有两个文本和一个按钮小部件。
The first text widget is for writing codes which will be executed after pressing "run" button.第一个文本小部件用于编写将在按下“运行”按钮后执行的代码。 And the second text widget is for using as stdout and stderr.第二个文本小部件用作标准输出和标准错误。
I have been trying to overwrite the previous print statement with using "\\r".我一直在尝试使用“\\r”覆盖之前的打印语句。 But the result is not as i wish.但结果并不如我所愿。
The after command is activated after all the processes have done.在所有进程完成后激活 after 命令。
What should i do to overwrite the previous print statement, is there a way?我该怎么做才能覆盖之前的打印语句,有没有办法?
Here are the codes:以下是代码:
#!/usr/bin/env python3
# -*- coding: utf -*-
import sys
import tkinter as tk
import time
class StdIORedirector:
def __init__(self, text):
self.text = text
def write(self, string):
self.text.insert("end", string)
def flush(self):
self.text.update_idletasks()
class App(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid(row=0, column=0)
self.WriteIn = tk.Text(master=self)
self.WriteIn.grid(row=0, column=0)
self.StdOut = tk.Text(master=self)
self.StdOut.grid(row=0, column=2)
sys.stdout = StdIORedirector(self.StdOut)
sys.stderr = StdIORedirector(self.StdOut)
self.RunButton = tk.Button(master=self, text="Run")
self.RunButton.grid(row=0, column=1)
self.RunButton.configure(command=self.run)
def run(self):
self.StdOut.delete("1.0", "end")
if "\\r" in self.WriteIn.get("1.0", "end"):
print("Start")
self.master.after(1, self.overwrite)
time.sleep(2)
print("End")
exec(self.WriteIn.get("1.0", "end"))
def overwrite(self):
self.StdOut.delete("1.0", "end")
self.master.after(1, self.overwrite)
if __name__ == "__main__":
root = tk.Tk()
app = App(master=root)
app.mainloop()
You can't "overwrite" per se , but you can easily delete existing text using the delete
method of the text widget.您本身不能“覆盖”,但您可以使用文本小部件的delete
方法轻松删除现有文本。
For example, to delete the current line that has the cursor you can do:例如,要删除具有光标的当前行,您可以执行以下操作:
self.StdOut.delete("insert linestart", "insert lineend")
insert
represents the location of the insertion cursor. insert
表示插入光标的位置。 linestart
and lineend
are modifiers that adjust the index to be either the start or end of the line, respectively. linestart
和lineend
是修饰符,分别将索引调整为行的开头或结尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.