簡體   English   中英

在 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 文本 Styles 演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM