我有一个本地存储的json文件,大约有3万条记录。我想分批显示它们,以便用户在查看记录时可以前进和后退。为了使程序的大小在编译后保持较小,我尝试为此不使用pandas
。
为了更好地说明这一点,以下是我目前在想的事情,使用tkinter作为显示示例:
import tkinter as tk
from tkinter import ttk
root = tk.Tk()
data = {i:[i,i] for i in range(1,10001)} #dummy data; actual key is not a integer
class Tree(ttk.Treeview):
def __init__(self,master=None,**kwargs):
ttk.Treeview.__init__(self,master,**kwargs)
self.height = kwargs.get("height",20)
self["columns"] = ("No.","Item")
start_index = 0
self.page = 0
for k, v in data.items():
self.insert("", tk.END, text=k, value=v)
start_index += 1
if start_index == self.height:
break
def forward(self):
self.delete(*self.get_children())
start_index = 0
for k, v in data.items():
if (self.page+1)*self.height <= start_index < (self.page+2)*self.height:
self.insert("", tk.END, text=k, value=v)
elif start_index > (self.page+2)*self.height:
self.page+=1
current.config(text=f"Page {self.page+1}")
break
start_index += 1
def backward(self):
if self.page == 0: return
self.delete(*self.get_children())
start_index = 0
for k, v in data.items():
if (self.page-1)*self.height <= start_index < self.page*self.height:
self.insert("", tk.END, text=k, value=v)
elif start_index > self.page*self.height:
self.page-=1
current.config(text=f"Page {self.page+1}")
break
start_index += 1
def jump_page(self, event=None):
if entry.get().isnumeric():
self.page = int(entry.get())-2
self.forward()
tree = Tree(root,height=20)
tree.pack()
frame = tk.Frame(root)
frame.pack(side="bottom")
ttk.Button(frame,text="Backward",command=tree.backward).grid(row=0,column=1)
ttk.Button(frame,text="Forward",command=tree.forward).grid(row=0,column=2)
tk.Label(frame,text="Jump to page:").grid(row=0,column=3,padx=2)
entry = ttk.Entry(frame,width=4)
entry.grid(row=0,column=4)
entry.bind("<Return>", tree.jump_page)
current = tk.Label(frame,text="Page 1",width=12)
current.grid(row=0,column=0)
root.mainloop()
我的问题:这是正确的方法吗?我依靠的是从3.6开始就对字典进行插入排序,因此我不确定这样做是否是一个好习惯。另外,我每次都必须遍历整个字典(尽管在获取结果时它可能会中断)。
为完整起见,这是我在pandas
中的做法:
import pandas as pd
s = pd.Series(data, name="No.")
class Tree(ttk.Treeview):
...
def pd_forward(self):
x = s.iloc[(self.page+1)*self.height:(self.page+2)*self.height]
if not len(x): return
self.delete(*self.get_children())
for k, v in x.items():
self.insert("", tk.END, text=k, value=v)
self.page+=1
current.config(text=f"Page {self.page+1}")