微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在tkinter文本小部件中动态插入文本?

如何解决如何在tkinter文本小部件中动态插入文本?

我想创建一个日志窗口,在其中显示错误或成功消息的记录。 请告诉我从当前应用程序中的任何小部件在text_Box中插入文本的任何解决方案。

有没有像我们使用textvariable

解决方案?

目的: 假设我们有两个标签,其中一个正在下载内容,并且其中出现一些错误,然后将此错误插入另一个标签的文本框中。

我正在更新我的问题以获得更好的答案。

文件结构:

enter image description here

downloader.py

import tkinter as tk


class DownloadWindow(tk.Frame):
    def __init__(self,parent):
        super().__init__(parent)
        ################# self configure ##########################
        self.columnconfigure(0,weight=1)

        ############### entry ################################
        self.entry = tk.Entry(self)
        self.entry.grid(row=0,column=0,sticky='nsew')
        self.entry.insert(0,'I am error send me to Logs...')

        ################ Button #################################
        self.button = tk.Button(self,text='Send to Log')
        self.button.grid(row=1,sticky='nsew')

insert.py

"""
Help me to write a function in this module for button in downloader
"""

logs.py

import tkinter as tk


class LogWindow(tk.Frame):
    def __init__(self,parent):
        super().__init__(parent)
        ################# self configure ##########################
        self.rowconfigure(0,weight=1)
        self.columnconfigure(0,weight=1)
        self.text_Box = tk.Text(self,wrap=None,bg='black',font='roboto 14 bold')
        self.text_Box.grid(row=0,sticky='nsew')

        self.scroller = tk.Scrollbar(self,command=self.text_Box.yview,orient='vertical')
        self.text_Box.configure(yscrollcommand=self.scroller.set)
        self.scroller.grid(row=0,column=1,sticky='nse')

        self.text_Box.tag_configure('welcome',foreground='white',background='black')
        self.text_Box.tag_configure('error',foreground='red')
        self.text_Box.tag_configure('success',foreground='green')

        self.text_Box.insert('end','>>> Welcome to Log Window','welcome')
        self.text_Box.insert('end','\n>>> Completed','success')
        self.text_Box.insert('end','\n>>> Something Wrong in Data Download','error')


luncher.py

import tkinter as tk
from tkinter import ttk
from Test.logs import LogWindow
from Test.downloader import DownloadWindow
root = tk.Tk()

base_tab = ttk.Notebook(root)
base_tab.grid(row=0,sticky='nsew')


base_tab.add(DownloadWindow(base_tab),text='Download')
base_tab.add(LogWindow(base_tab),text='Logs')

root.mainloop()

屏幕截图:

enter image description here

enter image description here

最终更新和实现的目标

添加downloader.py

        self.button.config(command=self.create_log)

    def create_log(self):
        write_log(self.entry.get())

添加insert.py

def write_log(text):
    with open('logs_data.txt','a') as log:
        log.write(f'\n{text}')

添加logs.py

        self.show_log()

    def show_log(self):
        global file_name,cached_stamp
        stamp = os.path.getmtime(file_name)
        if stamp != cached_stamp:
            with open(file_name,'r') as log:
                data = log.readlines()
                self.text_Box.insert('end',f'\n{data[-1]}','success')
        cached_stamp = stamp
        self.after(1000,self.show_log)

结论

我将每个日志附加到.txt文件中,并每秒钟读取一次。从LogWindow并检测更改。如果发生更改,则将其插入“文本”小部件中。

解决方法

您的问题非常不清楚。我不知道这是语言障碍还是术语问题。我猜您实际上不是在问如何将文本插入到窗口小部件中,因为该文档已明确记录,而是在如何在一个类中创建窗口小部件并从另一个类访问它。

如果是这种情况,那么我的建议是做两件事:在LogWindow中创建一个方法以将文本插入到文本小部件中,然后从应用程序中的其他任何地方调用该方法。

在LogWindow中创建日志记录方法

第一个步骤是在LogWindow中创建一个函数,其他对象可以使用该函数将数据添加到日志中。以下示例创建一个info方法,该方法接受一个字符串并将其添加到文本小部件中:

class LogWindow(tk.Frame):
    def __init__(self,parent):
        ...
        self.text_box = tk.Text(...)
        ...
        
    def info(self,message):
        self.text_box.insert("end",message)
        if not message.endswith("\n"):
            self.text_box.insert("end","\n")

修改DownloadWindow以接受LogWindow实例

接下来,您需要确保其他代码可以调用此方法。您可以通过设置全局变量,创建所有选项卡都可以访问的全局控制器或将引用传递给其他选项卡来实现此目的。

可以说,最简单的方法是将实例传递给其他类。为此,您可以先修改DownloadWindow来接受日志窗口作为参数:

class DownloadWindow(tk.Frame):
    def __init__(self,parent,logwindow):
        super().__init__(parent)
        self.logger = logwindow

一旦这样做,您就可以在类中的任何地方使用self.logger.info("...")来向日志窗口发送消息。

将LogWindow实例传递给DownloadWindow

最后一步是将LogWindow的实例传递给DownloadWindow。这需要首先创建LogWindow的实例,保存引用,并将该引用传递给DownloadWindow

log_window = LogWindow(base_tab)
download_window =  DownloadWindow(base_tab,log_window)

base_tab.add(download_window,text='Download')
base_tab.add(log_window,text='Logs')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。