将输出重定向到文本字段时在 Tkinter 中复制字符串

Duplicate a string in Tkinter when redirecting output to a text field

我将所有输出重定向到 Tkinter 中的程序文​​本字段,并且我想在消息中添加日期和时间:

class StdRedirector(object):
    def __init__(self, text_field):
        self.text_field = text_field

    def write(self, string):
        msg_time = datetime.now().strftime('%m-%d %H:%M:%S')
        self.text_field.configure(state='normal')
        self.text_field.insert('end', f'{msg_time} >> {string}')
        self.text_field.see('end')
        self.text_field.configure(state='disabled')


class App:
    def __init__(self):
        self.builder = pygubu.Builder()
        self.__init_ui()
        self.__init_callbacks()
        self.mainwindow.mainloop()

    def __init_ui(self):
        self.builder.add_from_file(path.join(base_dir, 'assets', 'app.ui'))
        self.mainwindow = self.builder.get_object('mainwindow')
        self.output_text_field = self.builder.get_object('output_text_field')
        sys.stdout = StdRedirector(self.output_text_field)
        sys.stderr = StdRedirector(self.output_text_field)

    def __init_callbacks(self):
        callbacks = {
            'update_balance_function': self.__update_balance
        }
        self.builder.connect_callbacks(callbacks)

    def __update_balance(self):
        print(True)

但是我添加的日期行是重复的:

据我了解,行由行分隔符\n分隔,每个子字符串单独发送,包括换行符。我能以某种方式修复它吗?

您可以简单地检查write()中的string参数是否包含任何有意义的内容,例如使用 ìf string.strip():

class StdRedirector(object):
    def __init__(self, text_field):
        self.text_field = text_field

    def write(self, string):
        self.text_field.configure(state='normal')
        if string.strip():  # add date before message
            msg_time = datetime.now().strftime('%m-%d %H:%M:%S')
            self.text_field.insert('end', f'{msg_time} >> {string}')
        else:  # simply insert string
            self.text_field.insert('end', string)
        self.text_field.see('end')
        self.text_field.configure(state='disabled')