如何在网格中显示csv文件?

2lpgd968  于 2023-06-27  发布在  其他
关注(0)|答案(2)|浏览(91)

我试图弄清楚如何在tkinter的网格中显示.csv文件,但在网上没有找到太多。
这是我的进展。

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

如何使用相同的方法读取.csv文件?

mpbci0fu

mpbci0fu1#

您可以使用python csv模块中的reader来读取文件。Reader接受一个.csv文件作为输入,然后可以像表一样迭代。我包含了代码、一个示例.csv文件和我的结果。
代码:

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文件:

col1,col2,col3
thing1,thing2,thing3
hi,hey,hello

结果:

u1ehiz5o

u1ehiz5o2#

而不是标签使用树视图这样,它会更有效。

from tkinter import *
import tkinter.ttk as ttk
import csv

root = Tk()
root.title("Python - Import CSV File To Tkinter Table")
width = 500
height = 400
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (width / 2)
y = (screen_height / 2) - (height / 2)
root.geometry("%dx%d+%d+%d" % (width, height, x, y))
root.resizable(0, 0)

TableMargin = Frame(root, width=500)
TableMargin.pack(side=TOP)

scrollbarx = Scrollbar(TableMargin, orient=HORIZONTAL)
scrollbary = Scrollbar(TableMargin, orient=VERTICAL)
tree = ttk.Treeview(TableMargin, columns=("Employye ID", "Name", "Date",'Registration Time'), height=400, selectmode="extended",
                    yscrollcommand=scrollbary.set, xscrollcommand=scrollbarx.set)
scrollbary.config(command=tree.yview)
scrollbary.pack(side=RIGHT, fill=Y)
scrollbarx.config(command=tree.xview)
scrollbarx.pack(side=BOTTOM, fill=X)
tree.heading('Employye ID', text="Employye ID", anchor=W)
tree.heading('Name', text="Name", anchor=W)
tree.heading('Date', text="Date", anchor=W)
tree.heading('Registration Time', text="Time", anchor=W)
tree.column('#0', stretch=NO, minwidth=0, width=0)
tree.column('#1', stretch=NO, minwidth=0, width=120)
tree.column('#2', stretch=NO, minwidth=0, width=120)
tree.column('#3', stretch=NO, minwidth=0, width=120)
tree.column('#3', stretch=NO, minwidth=0, width=120)
tree.pack()
with open('./RegisteredEmployees/RegisteredEmployees.csv') as f:
  reader = csv.DictReader(f, delimiter=',')
  for row in reader:
    emp_id = row['Employye ID']
    name = row['Name']
    dt = row['Date']
    ti = row['Registration Time']
    tree.insert("", 0, values=(emp_id, name, dt,ti))
root.mainloop()

我只是初始化Treeview,用csv模块读取csv并在Treeview中插入列和行数据。
结果See the result here

相关问题