I’m creating an Inventory project in python using tkinter and one of the things I want it to do is display the entire inventory that is stored in a text file. So far I have it working but the format of the text after its read onto the frame is not aligned and doesn’t look great.
JavaScript
x
17
17
1
def openFile():
2
tf = filedialog.askopenfilename(
3
initialdir="C:/Users/MainFrame/Desktop/",
4
title="Open Text file",
5
filetypes=(("Text Files", "*.txt"),)
6
)
7
tf = open(tf) # or tf = open(tf, 'r')
8
data = tf.read()
9
self.txtInventory.insert(END, data)
10
tf.close()
11
12
13
if __name__=='__main__':
14
root=Tk()
15
application= Inventory(root)
16
root.mainloop()
17
Advertisement
Answer
Normally I would use tags for formatting:
JavaScript
1
20
20
1
from tkinter import *
2
3
root = Tk()
4
root.geometry('400x250+800+50')
5
6
txtInventory = Text(root, wrap='word', padx=10, pady=10)
7
txtInventory.pack(fill='both', padx=10, pady=10)
8
txtInventory.tag_config('fixed', font='TkFixedFont') # Fixed style
9
# Tag name ----^
10
txtInventory.tag_add('fixed', '1.0', 'end') # Apply to entire text
11
12
# Insert example text
13
contents = '''ItemName Qty Bay#
14
15
Bleach 17 4
16
Towels 20 3'''
17
txtInventory.insert('end', contents)
18
19
root.mainloop()
20
Have a look at Tkinter Text Styles Demo