将文件读入 tkinter 中的文本框时如何格式化文件中的文本?

How do you format text from a file when reading the file into a text box in tkinter?

我正在使用 tkinter 在 python 中创建一个库存项目,我想让它做的一件事是显示存储在文本文件中的整个库存。到目前为止我已经可以正常工作了,但是文本在读入框架后的格式没有对齐,看起来也不太好。

def openFile():
                tf = filedialog.askopenfilename(
                        initialdir="C:/Users/MainFrame/Desktop/", 
                        title="Open Text file", 
                        filetypes=(("Text Files", "*.txt"),)
        )  
                tf = open(tf)  # or tf = open(tf, 'r')
                data = tf.read()
                self.txtInventory.insert(END, data)
                tf.close()


if __name__=='__main__':
        root=Tk()
        application= Inventory(root)
        root.mainloop()

通常我会使用标签来格式化:

from tkinter import *
 
root = Tk()
root.geometry('400x250+800+50')

txtInventory = Text(root, wrap='word', padx=10, pady=10)
txtInventory.pack(fill='both', padx=10, pady=10)
txtInventory.tag_config('fixed', font='TkFixedFont')    # Fixed style
#             Tag name ----^
txtInventory.tag_add('fixed', '1.0', 'end') # Apply to entire text

# Insert example text
contents = '''ItemName    Qty     Bay#

Bleach       17       4
Towels       20       3'''
txtInventory.insert('end', contents)

root.mainloop()

看看Tkinter Text Styles Demo