Search code examples
pythontkintersplittreeviewreadfile

Python read file by line separate by tab then insert into tkinter treeview


I am attempting to create a treeview in tkinter that is populated with data from a txt file. This file has a few lines and on each line there is an article title, a single tab, and then an article number matching the title. I am attempting to read all lines in the file and split by tab so that I can insert the titles and article numbers into their respective columns in a treeview made with Tkinter. The treeview only has two columns for title and article number. Obviously I need the title and numbers to match up in the treeview even if the treeview is filtered or rearranged. How would I do this?

I figured something like this would at least get me two lists with the correct values:

filename = "ArtIDs.txt"
with open(filename, "r") as readfile:    
   types = (line.split("\t") for line in readfile)
   xys = ((type[1], type[2]) for type in types)
   for x, y in xys:
      print(x,y)

But I keep getting a "list index out of range" error.


Solution

  • It should be started from 0

    try:

    filename = "ArtIDs.txt"  
    with open(filename, "r") as readfile:      
        types = (line.split("\t") for line in readfile)  
        xys = ((type[0], type[1]) for type in types)  
        for x, y in xys:  
            print(x,y)
    

    please try this one, may be it help:

    main = tk.Tk()
    frame = tk.Frame(main)
    frame.grid()
    tree = ttk.Treeview(main, columns=('1', '2'))
    tree.grid(column=0, sticky='N' + 'S' + 'E' + 'W')
    n = 1
    with open(filename, "r") as readfile:
        types = (line.split("\t") for line in readfile)
        xys = ((type[0], type[1]) for type in types)
        for x, y in xys:
           tree.insert("", n, values=(x, y))
           n+=1
    
    main.mainloop()