2017-01-08 53 views
0

私は、(請求システムとして)ツリービューにいくつかの値を追加し、すべての商品の価格の合計または合計を得るというGUIを開発しています。TkinterでTreeviewの値を合計する方法

A shot of the GUI, and "Generar" button result in the terminal ボタン「アグレガール」(英語で追加)は、エントリのデータを取得し、それをtreevewに追加します。それらのうちの1つが支払う金額の場合。 ここで私が欲しいものは得られていませんが、 "Generar"(Generate in English)ボタンが押されたときに、ツリービューで与えられた値の合計がツリービューの下にあるフィールドまたはエントリに表示されます。

次に、私が得たコード:

#!/usr/bin/python 
#-*- coding:utf-8 -*- 
from Tkinter import* 
from ttk import Combobox, Treeview 
from tkMessageBox import* 
import MySQLdb 
from controller import * 
import math 

class Gastos(Frame): 
    def __init__(self, parent, controller): 
     Frame.__init__(self, parent) 

     #INSTANCIAS 
     global cc, nombre, pago, ref, cod, desc, valor 
     #INSTANCIAS DE LOS WIDGETS 
     global e1, e2, e3, e4, e5, tree, l8 

     cc = IntVar() 
     nombre = StringVar() 
     pago = StringVar() 
     ref = StringVar() 
     cod = StringVar() 
     desc = StringVar() 
     valor = DoubleVar() 

     tbancos = ['Bancolombia', "Banco Bogotá", "Banco Agrario", "Banco Occidente"] 

     lupa = PhotoImage(file='img/lupa.png') 

     tbanktype = ['Corriente','Ahorro'] 
     fpago = ['Efectivo','Transferencia'] 

     resultado = DoubleVar() 

     #BUSQUEDA = ["Nombre","CC/Nit"] 
     busqueda = StringVar() 
     busqueda.trace("w", lambda name, index, mode: buscar()) 
     dato = StringVar() 

     #WIDGETS 

     #========================= HEADER ============================== 

     self.titleL = Label(self, text="GASTOS", font="bold") 
     self.titleL.pack(pady=20, side=TOP) 

     #========================== WRAPPER ============================ 

     self.wrapper = Frame (self) 
     self.wrapper.pack(side=LEFT, fill=Y) 
     #Esto centro el wrapper 
     #self.wrapper.pack(side=LEFT, fill=BOTH, expand=True) 

     #======================== BENEFICIARIO ======================= 

     self.lf1 = LabelFrame(self.wrapper, text="Beneficiario") 
     self.lf1.pack(fill=X, ipady=5) 

     self.f0 = Frame(self.lf1) 
     self.f0.pack(pady=5, fill=X)#----------------------------------- 

     l1 = Label(self.f0, text='CC/Nit:') 
     l1.pack(side=LEFT) 

     e1 = Entry(self.f0, textvariable=cc) 
     e1.pack(side=LEFT) 

     b0 = Button(self.f0, text='Buscar:', image=lupa, command=buscarB) 
     b0.pack(side=LEFT) 

     l2 = Label(self.f0, text='Nombre:') 
     l2.pack(side=LEFT) 
     e2 = Entry(self.f0, textvariable=nombre) 
     e2.pack(side=LEFT, fill=X, expand=1) 

     self.f1 = Frame(self.lf1) 
     self.f1.pack(pady=5, fill=X)#----------------------------------- 

     l3 = Label(self.f1, text='Forma de Pago:') 
     l3.pack(side=LEFT) 
     Cbx = Combobox(self.f1, textvariable=pago, values=fpago, width=15) 
     Cbx.set('Efectivo') 
     Cbx.pack(side=LEFT) 

     l4 = Label(self.f1, text='Ref. Bancaria:') 
     l4.pack(side=LEFT) 
     e3 = Entry(self.f1, textvariable=ref) 
     e3.pack(side=LEFT, fill=X, expand=1) 

     b1 = Button(self.f1, text='Buscar:', image=lupa) 
     b1.image=lupa 
     b1.pack(side=LEFT) 

     #======================== CONCEPTO ======================== 

     self.lf2 = LabelFrame(self.wrapper, text="Concepto") 
     self.lf2.pack(fill=X, ipady=5) 

     self.f2 = Frame(self.lf2) 
     self.f2.pack(pady=5, fill=X)#------------------------------- 

     l5 = Label(self.f2, text='Código:') 
     l5.pack(side=LEFT) 
     e4 = Entry(self.f2, textvariable=cod) 
     e4.pack(side=LEFT) 

     b2 = Button(self.f2, text='Buscar:', image=lupa, command=buscarC) 
     b2.pack(side=LEFT) 

     self.f3 = Frame(self.lf2) 
     self.f3.pack(pady=5, fill=X)#------------------------------- 

     l6 = Label(self.f3, text='Descripción:') 
     l6.pack(side=LEFT) 
     e5 = Entry(self.f3, textvariable=desc, state=DISABLED) 
     e5.pack(side=LEFT, fill=X, expand=1) 

     l7 = Label(self.f3, text='Valor:') 
     l7.pack(side=LEFT) 
     e6 = Entry(self.f3, width=15, textvariable=valor) 
     e6.pack(side=LEFT) 

     b3 = Button(self.f3, text='Agregar:', command=agregar) 
     b3.pack(side=LEFT) 

     #-------------------------- TREEVIEW --------------------------- 

     self.f4 = Frame(self.wrapper) 
     self.f4.pack(pady=5,fill=X) 

     tree = Treeview(self.f4, height=4, show="headings", columns=('col1','col2','col3')) 
     tree.pack(side=LEFT, fill=X, expand=1) 
     tree.column('col1', width=20, anchor='center') 
     tree.column('col2', width=200, anchor='center') 
     tree.column('col3', width=10, anchor='center') 

     tree.heading('col1', text='Código') 
     tree.heading('col2', text='Concepto') 
     tree.heading('col3', text='Valor') 

     scroll = Scrollbar(self.f4,orient=VERTICAL,command=tree.yview) 
     tree.configure(yscrollcommand=scroll.set) 

     #-------------------------------------------------------------- 

     self.f5 = Frame(self.wrapper) 
     self.f5.pack(pady=5,fill=X)#------------------- 

     #RESULT MUST BE SHOWN HERE 
     l8 = Label(self.f5, text=resultado, fg="red", bg="white", anchor='e', font="bold, 22", relief= SUNKEN) 
     l8.pack(fill=X, side=RIGHT, expand=1) 
     #l8.set("link") 

     self.fBtn = Frame(self.wrapper) 
     self.fBtn.pack()#------------------------------- 

     clean = Button(self.fBtn, text='Cancelar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=limpiar) 
     clean.pack(side=RIGHT) 

     update = Button(self.fBtn, text='Actualizar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', state=DISABLED) 
     update.pack(side=RIGHT) 

     add = Button(self.fBtn, text='Generar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=generar) 
     add.pack(side=RIGHT) 

     #========================= ASIDE =========================== 

     self.aside = Frame(self) 
     self.aside.pack(side=TOP, fill=BOTH) 

     self.wrap1 = Frame(self.aside) 
     self.wrap1.pack() 

     self.viewer = Label(self.wrap1, text="LISTA DE GASTOS") 
     self.viewer.pack() 

     scroll = Scrollbar(self.wrap1, orient=VERTICAL) 
     scroll.pack(side=RIGHT, fill=Y) 

     lb = Listbox(self.wrap1, yscrollcommand=scroll.set, height=20, width=30) 
     scroll.config (command=lb.yview) 
     lb.pack(fill=BOTH) 
     lb.bind("<Double-Button-1>", callback) 

     self.wrap2 = Frame(self.aside) 
     self.wrap2.pack() 

     load = Button(self.wrap2, text='Cargar lista', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=cargar_lista) 
     load.pack(fill=X) 

     delete = Button(self.wrap2, text='Borrar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=borrar) 
     delete.pack(fill=X) 

     edit = Button(self.wrap2, text='Modificar', bg='navy', foreground='white', activebackground='red3', activeforeground='white', command=modificar) 
     edit.pack(fill=X) 

     buscador = Label(self.wrap2, text="Buscar por Número:") 
     buscador.pack() 
     E = Entry(self.wrap2, textvariable=busqueda, width=24) 
     E.pack() 
     E.bind("<KeyRelease>", caps) 

def cargar_lista(): 
    try: 
     connect.commit() 
     display = "SELECT g_num FROM detalles order by g_num;" 
     cursor.execute(display) 
     registros = cursor.fetchall() 
     lb.delete(0, END) 
     for item in registros: 
      #print item 
      num = item[0] 
      lb.insert(END, num) 
    except: 
     showerror("Mensaje", "Ha ocurrido un error") 

# NUEVO/CANCELAR 
def limpiar(): 
    tree.delete(*tree.get_children()) 
    pass 

def agregar(): 
    v1 = cc.get() 
    v2 = None 
    v3 = cod.get() 
    v4 = desc.get() 
    v5 = valor.get() 
    tree.insert('', 0, values=(v3,v4,v5)) 

#FUNCTION THAT GIVE THE VALUES 
def generar(): 
    children = tree.get_children()#OBTIENE LOS iid DE LOS ITEMS 
    for child in children: 
     i = tree.item(child, 'values')[2]#OBTIENE LOS VALORES DE LOS ITEMS 
     print i 

def borrar(): 
    pass 

def bloquear(): 
    pass 

def callback(event): 
    llenar_campos() 

def llenar_campos(): 
    pass 

def habilitar(): 
    pass 

def modificar(): 
    pass 

def actualizar(): 
    pass 

def buscar(): 
    pass 

def buscarB(): 
    connect.commit() 
    try: 
     v = cc.get() 
     sql = "SELECT b_nombre from beneficiarios WHERE b_cc='%d';" % (v) 
     cursor.execute(sql) 
     query = cursor.fetchone() 
     for n in query: 
      nombre.set(n) 
    except TypeError, e: 
     showerror("Error", e) 

    except MySQLdb.IntegrityError, e: 
     showerror("Error", e) 

def buscarC(): 
    connect.commit() 
    try: 
     v = cod.get() 
     sql = "SELECT cg_nombre from concepto_gastos WHERE cg_cod='%s';" % (v) 
     cursor.execute(sql) 
     query = cursor.fetchone() 
     for n in query: 
      desc.set(n) 
    except TypeError, e: 
     showerror("Error", e) 

    except MySQLdb.IntegrityError, e: 
     showerror("Error", e) 
    except: 
     showerror ("Mensaje", "No se encuentra!") 

# CONVIERTE LA ENTRADA DE LOS ENTRIES EN MAYÚSCULA 
def caps(event): 
    pass 

コードは、それはとても多くの情報を持っている理由です、終了していません。このファイルは、それと対話するために、別の(home.py)によって呼び出されるところで

def generar(): 
    children = tree.get_children()#OBTIENE LOS iid DE LOS ITEMS 
    for child in children: 
     i = tree.item(child, 'values')[2]#OBTIENE LOS VALORES DE LOS ITEMS 
     print i 

:しかし、次の関数は、私が合計になるように必要なものを私に値を与えることです。

誰かが私にこの問題を与えることができれば、命を救うでしょう。お時間をいただきありがとうございます。これを見て、あなたが答えることができるものを探してください。私の英語は申し訳ありません。

+0

私はあなたがこれまでに持っているものはすべて正しいと思います。整数変数を作り、それを集計するだけです。代わりに、ジェネレーターを使ってもっとコンパクトにすることができます(私はジェネレーターに慣れていないと思います)。がんばろう。 –

+0

(TreeViewだけでなく)一部のリストのすべての情報をこの情報に簡単にアクセスできるようにします。 – furas

+0

またはtotal_sumの変数を作成し、 'agregar()'の中に値を追加してください – furas

答えて

0

文字列をfloatに変換してから変数ieに追加する必要があります。 total

def generar(): 

    total = 0.0 

    for child in tree.get_children(): 
     total += float(tree.item(child, 'values')[2]) 

    print total 

しかし、あなたはあなたのコードがあるので、あなたがPY_VAR240を得ている理由は

# create global variables 
total = 0.0 
# or 
total_var = DoubleVar() 

def agregar(): 
    # inform function to use external/global variable when you use `+=` 
    global total 

    v1 = cc.get() 
    v2 = None 
    v3 = cod.get() 
    v4 = desc.get() 
    v5 = valor.get() 

    total += v5 
    # or 
    total_var.set(total_var.get() + v5) 

    tree.insert('', 0, values=(v3,v4,v5)) 

ボタンを使用して完全な作業例

import Tkinter as tk 
import ttk 

# --- functions --- 

def agregar(v3, v4, v5): 
    tree.insert('', 0, values=(v3,v4,v5)) 

def generar(): 

    total = 0.0 

    for child in tree.get_children(): 
     total += float(tree.item(child, 'values')[2]) 

    print total 

    result['text'] = 'Total: {}'.format(total) 

# --- main --- 

root = tk.Tk() 

tree = ttk.Treeview(root, height=4, show="headings", columns=('col1','col2','col3')) 
tree.pack() 

tree.heading('col1', text='Código') 
tree.heading('col2', text='Concepto') 
tree.heading('col3', text='Valor') 

add = tk.Button(root, text='Generar', command=generar) 
add.pack() 

result = tk.Label(root, text='Total: 0') 
result.pack() 

agregar("1", "AAA", 1.11) 
agregar("2", "BBB", 2.22) 
agregar("3", "CCC", 3.33) 

root.mainloop() 
+0

ええ、この情報はそれを作った!しかし、今私は、 "Generar"ボタンは、Reportlabライブラリと、そのためのフィールドの値を合計し、ツリービューにデータを挿入するには、 "Agregar"ボタンをクリックしてPDF請求書を生成するのに役立つことに気づいた。しかし、SuprまたはDeleteキーを押してツリービューから行を削除して、減算結果を取得したい場合はどうでしょうか。それはどうですか? DEF borrar(イベント): I = tree.selection()[0] tree.delete(I)また 、Iを添加tree.bind(」 Einnerlink

+0

Iは、選択された行を削除するには、次の関数を作成しました"、borrar)、そしてそれは仕事をしますが、削除された値を結果に引く方法は? – Einnerlink

+0

新しい要素を追加したり、古い要素を削除したりするときに、単に要素をテーブルに合計して実行する関数を作成するだけです。 – furas

0

totalを得るためにも、agregarに値を追加することもできます値の代わりにオブジェクトを表示しようとしています。 Python Tkinter Treeview - Iterating 'get_children' output

をまたここで私は、行から値を取得する方法をされています:

だけでなく、問題を示唆し、ここで答えが既に存在し

rowItem = treeSomeTree.item(itemID) 
itemDictionary = rowItem['values'] 
someVariable = itemDictionary[0] 

注アイテムID変数は、行項目を表し識別子は数字であってもなくてもよく、一意でなければならない。指定されていない場合、treeview .insertのデフォルトはNone(iid = None)です。

不活性行としてiidを整数値として指定すると、要約する行(または取得する必要がある行)が常にわかります。

+0

ああ、そうだよ!さて、私は "l8"ラベルがtextvariableではなく "text"を持っていて、変数 'resultado'はグローバルではないことに気付きました。 – Einnerlink

関連する問題