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

Time:04-06

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.

The numbers aren't aligned correctly

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()

CodePudding user response:

Normally I would use tags for formatting:

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()

Have a look at Tkinter Text Styles Demo

  • Related