I'm trying to figure out how to display a .csv
file in tkinter's grid, but haven't found much online.
Here is how far I got.
import tkinter
root = tkinter.Tk()
for r in range(3):
for c in range(4):
tkinter.Label(root, text='R%s/C%s'%(r,c),borderwidth=1 ).grid(row=r,column=c)
root.mainloop()
How would I read a .csv
file using the same approach?
You can use reader from the python csv module to read the file. Reader takes a .csv file as input, and can then be iterated over like a table. I've included code, a sample .csv file, and my result.
Code:
import tkinter
import csv
root = tkinter.Tk()
# open file
with open("test.csv", newline="") as file:
reader = csv.reader(file)
# r and c tell us where to grid the labels
for r, col in enumerate(reader):
for c, row in enumerate(col):
# i've added some styling
label = tkinter.Label(
root, width=10, height=2, text=row, relief=tkinter.RIDGE
)
label.grid(row=r, column=c)
root.mainloop()
CSV File:
col1,col2,col3
thing1,thing2,thing3
hi,hey,hello
Result: