亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

python tkinter:使文本小部件自動隨文本滾動

python tkinter:使文本小部件自動隨文本滾動

心有法竹 2022-12-27 16:32:25
我已將 STDOUT 重定向到文本小部件。然后我使用線程來運行子進程,通過 poll() 捕獲標準輸出并打印它(重定向到文本小部件)?,F在我希望小部件隨文本小部件自動滾動,以便用戶始終可以看到最新的輸出。(文本小部件的唯一用途是顯示運行腳本的輸出,因此請隨意提出替代方案)class myGui:  def __init__(self, master=none)    self.text_Output = tk.Text(frame_Output)    self.text_Output.config(borderwidth='1', height='10', insertborderwidth='2', relief='ridge')    self.text_Output.config(width='50')    # redirect stdout    redir = RedirectText(self.text_Output)    sys.stdout = redir  def runCode:   self.p = subprocess.Popen(["COMMAND HERE"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, bufsize=1, universal_newlines=True)    while self.p.poll() is None:        msg = self.p.stdout.readline().strip()        if msg:            print(msg)class RedirectText(object):    def __init__(self, text_ctrl):        """Constructor"""        self.output = text_ctrl    def write(self, string):        self.output.insert(tk.END, string)
查看完整描述

1 回答

?
Helenr

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)


查看完整回答
反對 回復 2022-12-27
  • 1 回答
  • 0 關注
  • 422 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號