1 回答

TA貢獻1780條經驗 獲得超4個贊
Text有方法see(...)可以在插入新文本后使用。
如果你使用see('end')它會滾動到最后。
最小的工作示例 - 每次滾動到末尾insert()
編輯:我添加了see()用于滾動到頂部 ( see('1.0')) 或末尾 ( see('end')) 的按鈕。
import tkinter as tk
root = tk.Tk()
text = tk.Text(root)
text.pack()
button_top = tk.Button(root, text="Move to TOP", command=lambda:text.see('1.0'))
button_top.pack()
button_end = tk.Button(root, text="Move to END", command=lambda:text.see('end'))
button_end.pack()
# instert to Text and scroll it
for x in range(50):
text.insert('end', str(x) + '\n')
text.see('end') # move to the end after adding new text
root.mainloop()
編輯:使用類的最小示例RedirectText
import tkinter as tk
import sys
import datetime
# --- classes ---
class RedirectText(object):
def __init__(self, text_widget):
"""Constructor"""
self.output = text_widget
def write(self, string):
"""Add text to the end and scroll to the end"""
self.output.insert('end', string)
self.output.see('end')
# --- functions ---
def add_time():
"""Add current time every 2 seconds"""
print(datetime.datetime.now())
root.after(2000, add_time)
# --- main ---
root = tk.Tk()
text = tk.Text(root)
text.pack()
button_top = tk.Button(root, text="Move to TOP", command=lambda:text.see('1.0'))
button_top.pack()
button_end = tk.Button(root, text="Move to END", command=lambda:text.see('end'))
button_end.pack()
# keep original `stdout` and assing `RedirectText` as `stdout`
old_stdout = sys.stdout
sys.stdout = RedirectText(text)
# add some datetime at the beginning
print('--- TOP ---')
for _ in range(50):
print(datetime.datetime.now())
# add new datetime every 2 seconds
add_time()
# write to console when `print()` and `sys.stdout` redirect to `Text`
old_stdout.write('Hello World!\n') # needs `\n`
print('Hello World!', file=old_stdout) # doesn't need `\n`
root.mainloop()
# assign back original `stdout`
sys.stdout = old_stdout
順便說一句:如果您需要在print()重定向到時打印到控制臺Text
old_stdout.write('Hello World!\n') # needs `\n`
print('Hello World!', file=old_stdout) # doesn't need `\n`
順便說一句:您也可以使用file=打印而不分配RedirectText給sys.stdout
redirect = RedirectText(text)
print('Hello World!', file=redirect)
添加回答
舉報