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