更新列表框/树视图,而不是每次都创建一个新的

时间:2015-08-22 13:16:39

标签: python-3.x tkinter tree listbox

我尝试使用ttk.TreeView以表格方式显示CSV中的信息。代码完全符合我的要求。我只是 我希望每次点击第一个Curselec_Croq Listbox时更新树 每次点击都不会创建新树。

我怎么能这样做?

import pdb
#pdb.set_trace()
import sys
import csv
sys.version_info

import tkinter as tk
import tkinter.font as tkFont
import tkinter.ttk as ttk
from tkinter import *

def parse_csv(content, delimiter = ';'):  ## We use here ";" to parse CSV
                                          ## because of the European way of
    csv_data = []                         ## dealing with excel-csv
    for line in content.split('\n'):      ## strips spaces also
        csv_data.append( [x.strip() for x in line.split( delimiter )] )
    return csv_data

global car_header
global car_list

class McListBox(object):
    """use a ttk.TreeView as a multicolumn ListBox"""
    def __init__(self):
        self.tree = None
        self._setup_widgets()
        self._build_tree()

    def _setup_widgets(self):
        s ='""'
        msg = ttk.Label(wraplength="4i", justify="left", anchor="n",
            padding=(10, 2, 10, 6))
        msg.pack(fill='x')

        container = ttk.Frame()
        container.pack(fill='both', expand=True)

        # create a treeview with dual scrollbars
        self.tree = ttk.Treeview(columns=car_header, show="headings")
        vsb = ttk.Scrollbar(orient="vertical",
            command=self.tree.yview)
        hsb = ttk.Scrollbar(orient="horizontal",
            command=self.tree.xview)
        self.tree.configure(yscrollcommand=vsb.set,
            xscrollcommand=hsb.set)
        self.tree.grid(column=0, row=0, sticky='nsew', in_=container)
        vsb.grid(column=1, row=0, sticky='ns', in_=container)
        hsb.grid(column=0, row=1, sticky='ew', in_=container)

        container.grid_columnconfigure(0, weight=1)
        container.grid_rowconfigure(0, weight=1)

    def _build_tree(self):
        for col in car_header:
            self.tree.heading(col, text=col.title(),
                command=lambda c=col: sortby(self.tree, c, 0))
            # adjust the column's width to the header string
            self.tree.column(col,
                width=tkFont.Font().measure(col.title()))

        for item in car_list:
            self.tree.insert('', 'end', values=item)
            # adjust column's width if necessary to fit each value
            for ix, val in enumerate(item):
                col_w = tkFont.Font().measure(val)
                if self.tree.column(car_header[ix],width=None)<col_w:
                    self.tree.column(car_header[ix], width=col_w)


def sortby(tree, col, descending):
    """sort tree contents when a column header is clicked on"""
    # grab values to sort
    data = [(tree.set(child, col), child) \
        for child in tree.get_children('')]
    # if the data to be sorted is numeric change to float
    #data =  change_numeric(data)
    # now sort the data in place
    data.sort(reverse=descending)
    for ix, item in enumerate(data):
        tree.move(item[1], '', ix)
    # switch the heading so it will sort in the opposite direction
    tree.heading(col, command=lambda col=col: sortby(tree, col,
                                                     int(not descending)))

Remplissage = parse_csv(
                open('Remplissage.csv', 'rU', encoding="ISO-8859-1").read())
root = tk.Tk()
root.wm_title("Visualizer")

def CurSelet_croq(evt):
    global car_header
    global car_list

    car_header = [
        'Used Nutrients in the Profession',
        'Nutrients used in this PetFood (Source : Official Website)']
    car_list=[]
    value=str(liste_croq.get(liste_croq.curselection()))
    for i in range(0,len(Remplissage)):
        if Remplissage[i][0]=="Name":
           for j in range(1,len(Remplissage[i])):
               if Remplissage[i][j]==value:
                   for k in range(0,len(Remplissage)-1):
                       if Remplissage[k][j]!="ND":
                           car_list.append([Remplissage[k][0],"OK"])
                       else:
                           car_list.append([Remplissage[k][0],""])

    print(car_list)
    mc_listbox = McListBox()
    return car_header, car_list

liste_croq = Listbox(root,width=70, height=10)
for i in range(0,len(Remplissage)):
               if Remplissage[i][0]=="Name":
                  for j in range(1,len(Remplissage[i])):
                      liste_croq.insert(i,Remplissage[i][j])
                      liste_croq.bind('<<ListboxSelect>>', CurSelet_croq)
                      liste_croq.pack()

root.mainloop()

到目前为止,我已经尝试每次创建一个新的root窗口并销毁前一个窗口,但它看起来就像它。它并不完全&#34;更新&#34;。

任何帮助都值得赞赏。

正如Martineau所要求的那样是Remplissage.csv

的摘录
Name;Puppy Small Breed For Small Breed Puppies weighing 9 KG (20 LBS) at maturity;Puppy & Junior For puppies between 9 and 25;Puppy Large Breed For Puppies 25;Adult Small Breed For Small Breed Dogs 1 Year and Older;Chicken & Burbank Potato For All Breeds and Life Stages
Methionine;0.6%;0.6%;0.6%
Metabolisable energy (calculated according NRC85);ND;ND;ND
Moisture,Water,Humidity,Moisture (max.);10%;10%;10%

1 个答案:

答案 0 :(得分:0)

答案:

import tkinter as tk
import tkinter.font as tkFont
import tkinter.ttk as ttk
from tkinter import *
def parse_csv(content, delimiter = ';'):  ##We use here ";" to parse CSV because of the European way of dealing with excel-csv
  csv_data = []
  for line in content.split('\n'):
    csv_data.append( [x.strip() for x in line.split( delimiter )] ) # strips spaces also
  return csv_data

canvas=parse_csv(open('canvas.csv','rU',encoding="ISO-8859-1").read())
#fediaf_requirements is a list containing where fediaf has a 
fediaf_requirements=[]
for i in range(0,len(canvas)):
               if canvas[i][1]=="FEDIAF":
                  fediaf_requirements.append(canvas[i][0])

car_header = ['Used Nutrients in the Profession', 'Nutrients used in this PetFood (Source : Official Website)', 'FEDIAF Requirement']


#Create the Data to be put into the table
def FromCSV_to_Tree(liste_croq):
    global car_list
    car_list=[]
    value=str(liste_croq.get(liste_croq.curselection()))
    for i in range(0,len(Remplissage)):
               if Remplissage[i][0]=="Name":
                  for j in range(1,len(Remplissage[i])):
                      if Remplissage[i][j]==value:
                          for k in range(0,len(Remplissage)-1):
                              if Remplissage[k][0] in fediaf_requirements :
                                  a="Required"
                              else :
                                  a=""


                              if Remplissage[k][j]!="ND":
                                     car_list.append([Remplissage[k][0],"OK",a])
                              else:
                                  car_list.append([Remplissage[k][0],"",a])



def CurSelet_croq(evt,container):
    global car_list
    FromCSV_to_Tree(liste_croq)
    car_header = ['Used Nutrients in the Profession', 'Nutrients used in this PetFood (Source : Official Website)', 'FEDIAF Requirement']
    print(car_list)


    #create a treeview with dual scrollbars

    #Container and container.pack detached to update the tree with the new datas. 
    container.pack(fill='both', expand=True)




    tree = ttk.Treeview(columns=car_header, show="headings")
    vsb = ttk.Scrollbar(orient="vertical",
                        command=tree.yview)
    hsb = ttk.Scrollbar(orient="horizontal",
                        command=tree.xview)
    tree.configure(yscrollcommand=vsb.set,
                   xscrollcommand=hsb.set)
    tree.grid(column=0, row=0, sticky='nsew', in_=container)
    vsb.grid(column=1, row=0, sticky='ns', in_=container)
    hsb.grid(column=0, row=1, sticky='ew', in_=container)

    container.grid_columnconfigure(0, weight=1)
    container.grid_rowconfigure(0, weight=1)

    def sortby(tree, col, descending):
        """sort tree contents when a column header is clicked on"""
        # grab values to sort
        data = [(tree.set(child, col), child) \
            for child in tree.get_children('')]
        # if the data to be sorted is numeric change to float
        #data =  change_numeric(data)
        # now sort the data in place
        data.sort(reverse=descending)
        for ix, item in enumerate(data):
            tree.move(item[1], '', ix)
        # switch the heading so it will sort in the opposite direction
        tree.heading(col, command=lambda col=col: sortby(tree, col, \

            int(not descending)))

##Put data into the tree
    for col in car_header:
        tree.heading(col, text=col.title(),
                     command=lambda c=col: sortby(tree, c, 0))
        # adjust the column's width to the header string
        tree.column(col,
                    width=tkFont.Font().measure(col.title()))

    for item in car_list:
        tree.insert('', 'end', values=item)
        # adjust column's width if necessary to fit each value
        for ix, val in enumerate(item):
            col_w = tkFont.Font().measure(val)
            if tree.column(car_header[ix],width=None)<col_w:
               tree.column(car_header[ix], width=col_w)










Remplissage=parse_csv(open('Remplissage.csv','rU',encoding="ISO-8859-1").read())
root = tk.Tk()
root.wm_title("Visualizer")

container = ttk.Frame()

liste_croq = Listbox(root,width=70, height=10)
for i in range(0,len(Remplissage)):
               if Remplissage[i][0]=="Name":
                  for j in range(1,len(Remplissage[i])):
                      liste_croq.insert(i,Remplissage[i][j])
                      liste_croq.bind('<<ListboxSelect>>', lambda evt, container=container : CurSelet_croq(evt,container))
                      liste_croq.pack()


root.mainloop()