Calificación:
  • 0 voto(s) - 0 Media
  • 1
  • 2
  • 3
  • 4
  • 5
Tkinter base de datos
#1
Buen dia!!! Necesito de su ayuda, estoy trabajando con Tkinter, el boton agregar de la pestaña agregar alumno no vincula con la base de datos para que modifique o agregue alumno
Código:
#---coding: utf-8 -------

import sys
import time
import sqlite3 as db
import tkinter.messagebox as tkMessageBox

try:
   from Tkinter import *
except ImportError:
   from tkinter import *

try:
   import ttk
   py3 = False
except ImportError:
   import tkinter.ttk as ttk
   py3 = True


def comenzar_ventana():
   
   global vent2, ventana1
   ventana1 = Tk()
   marcoventanainicial = Ventana (ventana1)
   ventana1.mainloop()
   
   

vent2 = None

def Ventana(ventana1):
   
   global vent2, w_win, vent1, pestagregar
   vent1 = ventana1
   vent2 = marcoventanainiciallevel (ventana1)
   marcoventanainicial = Ventana (vent2)
   return (vent2, marcoventanainicial)

def destroy_Ventana():
   global vent2
   vent2.destroy()
   #vent2 = None
 
fecha=time.strftime("Hoy es : %d-%m-%Y\nes la hora : %H:%M")
#db_base = "Cooperadora.s3db"
class Ventana:
       
   def __init__(self, marcoventanainicial):
   
       _bgcolor = '#d9d9d9'  # X11 color: 'gray85'
       _fgcolor = '#000000'  # X11 color: 'black'
       _compcolor = '#d9d9d9' # X11 color: 'gray85'
       _ana1color = '#d9d9d9' # X11 color: 'gray85'
       _ana2color = '#d9d9d9' # X11 color: 'gray85'
       font10 = "-family {Courier New} -size 10 -weight normal -slant"  \
           " roman -underline 0 -overstrike 0"
       font11 = "-family {Wide Latin} -size 24 -weight normal -slant "  \
           "roman -underline 0 -overstrike 0"
       estiloVentana = ttk.Style()
       estiloVentana.theme_use('winnative')
       estiloVentana.configure(".",background=_bgcolor,foreground=_fgcolor,font="TkDefaultFont")
       estiloVentana.map('.',background=[('selected', _compcolor), ('active',_ana2color)])
       
       marcoventanainicial.geometry("996x516+6+3")
       marcoventanainicial.title("programacion 2018")

#************recuadro azul y titulo***************************************************
       cuadrotitulo = Frame(marcoventanainicial)
       cuadrotitulo.place(relx=0.01, rely=0.019, relheight=0.145, relwidth=0.985)
       cuadrotitulo.configure(background="#3253d8")
       titulo1 = Label(cuadrotitulo)
       titulo1.place(relx=0.02, rely=0.0, height=51, width=964)
       titulo1.configure(font=font11, background="#3253d8", text="COOPERADORA")
       
       titulo2 = Label(cuadrotitulo)
       titulo2.place(x=0, y=0)
       titulo2.configure(font=font10, background="#3253d8", text=fecha)
       
       
#*******************recuadro de botones**********************************************
       botones = Frame(marcoventanainicial)
       botones.place(relx=0.01, rely=0.174, relheight=0.7, relwidth=0.126)
       botones.configure(relief=GROOVE, borderwidth="6", background="#d9d9d9", highlightcolor ="black", width=125)
       
#******************botones izquierda**************************************************
       agregar = Button(botones)
       agregar.place(relx=0.16, rely=0.022, height=24, width=87)
       agregar.configure(background="#d9d9d9", text="Alumnos", command = self.pestagregar )
       
       cuotas = Button(botones)
       cuotas.place(relx=0.16, rely=0.09, height=24, width=87)
       cuotas.configure(background="#d9d9d9", text="Cuotas", command=self.pestacuota)
       
       configurar = Button(botones)
       configurar.place(relx=0.16, rely=0.157, height=24, width=87)
       configurar.configure(background="#d9d9d9", text="Configuracion")
       
       contabilidad = Button(botones)
       contabilidad.place(relx=0.16, rely=0.225, height=24, width=87)
       contabilidad.configure(background="#d9d9d9", text="Contabilidad")
       
       salir = Button(botones)
       salir.place(relx=0.16, rely=0.292, height=24, width=87)
       salir.configure(text="Salir", background="#d9d9d9", command = marcoventanainicial.destroy)
       #salir.configure(text="Salir", background="#d9d9d9", command = self.Exit)
#****************************************************************************************        
#*****************pestañas*****************************************************
       estiloVentana.configure('TNotebook.Tab', background=_bgcolor, foreground=_fgcolor)
       estiloVentana.map('TNotebook.Tab', background=[('selected', _compcolor), ('active',_ana2color)])
       self.pestagregar()
       self.tablax()
       self.leerdb()
             
#**********************************************************************************        
# (pestaña agregar)

   def pestagregar(marcoventanainicial):
       pestaña = ttk.Notebook()
       pestaña.place(relx=0.151, rely=0.174, relheight=0.186, relwidth=0.84)
       pestaña.configure(width=854, takefocus="")
       pestaña_t0 = Frame(pestaña)
       
       pestaña.add(pestaña_t0, padding=3)
       pestaña.tab(0, text="\t\tAgregar Alumno\t\t\t",compound="right",underline="-1",)
       pestaña_t0.configure(background="#d9d9d9")
#boton de  AGREGAR de la pestaña Agregar
       botpestagregar = ttk.Button(pestaña_t0)
       botpestagregar.place(relx=0.882, rely=0.286, height=35, width=76)
       #botpestagregar.configure(text="Agregar", command = self.agregadb)
       botpestagregar.configure(text="Agregar")
#cuadro de entrada de apellido
       etiqapellido = Label(pestaña_t0, text="APELLIDO")
       etiqapellido.place(relx=0.047, rely=0.01, height=20, width=204)
       etiqapellido.configure(background="#d9d9d9")
       cuadrentrapellido = Entry(pestaña_t0)
       cuadrentrapellido.focus()
       cuadrentrapellido.place(relx=0.035, rely=0.429,height=20, relwidth=0.264)
       cuadrentrapellido.configure(background="YellowGreen",font="font10")
       #self.cuadrentrapellido.configure(takefocus="0")
#cuadro de entrada de nombre
       etiqnombre = Label(pestaña_t0, text="NOMBRE")
       etiqnombre.place(relx=0.340, rely=0.1, height=20, width=204)
       etiqnombre.configure(background="#d9d9d9")
       cuadrentrnombre = Entry(pestaña_t0)
       cuadrentrnombre.place(relx=0.300, rely=0.429,height=20, relwidth=0.364)
       cuadrentrnombre.configure(background="YellowGreen",font="font10")
       #self.cuadrentrnombre.configure(takefocus="0")
#cuadro de entrada de dni
       etiqdni = Label(pestaña_t0,text="DNI")
       etiqdni.place(relx=0.650, rely=0.0, height=20, width=124)
       etiqdni.configure(background="#d9d9d9")
       cuadrentrdni = Entry(pestaña_t0)
       cuadrentrdni.place(relx=0.665, rely=0.429,height=20, relwidth=0.150)
       cuadrentrdni.configure(background="YellowGreen",font="font10")
       #self.cuadrentrdni.configure(takefocus="0")
#(pestaña editar)
       pestaña_t1 = Frame(pestaña)
       pestaña.add(pestaña_t1, padding=3)
       pestaña.tab(1, text="\t\tEditar\t\t\t",compound="bottom",underline="-1",)
       pestaña_t1.configure(background="#d9d9d9")
#boton de  BUSCAR de la pestaña EDITAR
       botpestagregar = ttk.Button(pestaña_t1, text="Buscar")
       botpestagregar.place(relx=0.4, rely=0.286, height=35, width=76)

#boton de  SELECCIONAR de la pestaña EDITAR
       botpestagregar = ttk.Button(pestaña_t1,text="Seleccionar")
       botpestagregar.place(relx=0.7, rely=0.286, height=35, width=76)
       botpestagregar.configure(takefocus="")
#cuadro de entrada de dni
       etiqdni = Label(pestaña_t1,text="DNI")
       etiqdni.place(relx=0.050, rely=0.0, height=20, width=124)
       etiqdni.configure(background="#d9d9d9")
       cuadrentrdni = Entry(pestaña_t1)
       cuadrentrdni.place(relx=0.065, rely=0.429,height=20, relwidth=0.150)
       cuadrentrdni.focus()
       cuadrentrdni.configure(background="YellowGreen",font="font10")
       #self.cuadrentrdni.configure(takefocus="0")
           
#(pestaña ver)
       pestaña_t2 = Frame(pestaña)
       pestaña.add(pestaña_t2, padding=3)
       pestaña.tab(2, text="\t\t\tVer\t\t\t",compound="bottom",underline="-1",)
       pestaña_t2.configure(background="#d9d9d9")
#*********************************************************************************************
   def pestacuota(marcoventanainicial):
       pestaña = ttk.Notebook()
       pestaña.place(relx=0.151, rely=0.174, relheight=0.186, relwidth=0.84)
       pestaña.configure(width=854, takefocus="")
#(pestaña hisorial de pago)
       pestaña_t0 = Frame(pestaña)
       pestaña.add(pestaña_t0, padding=3)
       pestaña.tab(0, text="\t\t\tHistorial de pago\t\t\t",compound="bottom",underline="-1",)
       pestaña_t0.configure(background="#d9d9d9")
#boton de  BUSCAR de la pestaña EDITAR
       botpestagregar = ttk.Button(pestaña_t0, text="Buscar")
       botpestagregar.place(relx=0.4, rely=0.286, height=35, width=76)

#boton de  SELECCIONAR de la pestaña EDITAR
       botpestagregar = ttk.Button(pestaña_t0,text="Seleccionar")
       botpestagregar.place(relx=0.7, rely=0.286, height=35, width=76)
       botpestagregar.configure(takefocus="")
#cuadro de entrada de dni
       etiqdni = Label(pestaña_t0,text="DNI")
       etiqdni.place(relx=0.050, rely=0.0, height=20, width=124)
       etiqdni.configure(background="#d9d9d9")
       cuadrentrdni = Entry(pestaña_t0)
       cuadrentrdni.place(relx=0.065, rely=0.429,height=20, relwidth=0.150)
       cuadrentrdni.focus()
       cuadrentrdni.configure(background="YellowGreen",font="font10")
       #self.cuadrentrdni.configure(takefocus="0")
           
#(pestaña ver)
       pestaña_t1 = Frame(pestaña)
       pestaña.add(pestaña_t1, padding=3)
       pestaña.tab(1, text="\t\t\tVer\t\t\t",compound="bottom",underline="-1",)
       pestaña_t1.configure(background="#d9d9d9")

   def tablax(self):
       self.tabla = ttk.Treeview(columns=("Orden", "Apellido", "Nombre", "DNI"), selectmode="extended", height=500)
       self.tabla.place(relx=0.151, rely=0.368, relheight=0.624, relwidth=0.835)
       self.tabla.heading('Orden', text="Orden", anchor=W)
       self.tabla.heading('Apellido', text="Apellido", anchor=W)
       self.tabla.heading('Nombre', text="Nombre", anchor=W)
       self.tabla.heading('DNI', text="DNI", anchor=W)
       self.tabla.column('#0', stretch=NO, minwidth=0, width=0)
       self.tabla.column('#1', stretch=NO, minwidth=0, width=80)
       self.tabla.column('#2', stretch=NO, minwidth=0, width=300)
       self.tabla.column('#3', stretch=NO, minwidth=0, width=330)
       self.tabla.column('#4', stretch=NO, minwidth=0, width=120)

       
# ****************operar con la base de datos Cooperadora.s3db******
       
   
   def conectardb(self,traer, datos =()):
       self.db_base = "Cooperadora.s3db"
       conexion= db.connect(self.db_base)
       cursor = conexion.cursor()
       result=cursor.execute(traer, datos)
       conexion.commit()
       return result
   def leerdb(self):
# borrar tabla
       memoria =self.tabla.get_children()
       for elementos in memoria:
           self.tabla.delete(elementos)
#consulta de datos
       traer = "SELECT *FROM Alumnos ORDER BY Orden ASC"
       filas = self.conectardb(traer)
#rellenando los datos
       for fila in filas:
          #print(fila)  muestra datos en consola
          self.tabla.insert('', 'end', values=(fila[0], fila[1], fila[2],fila[3]))
# agregar datos desde cuadro de entrada
   
   # ~ def agregadb(self):

       # ~ if  cuadrentrapellido.get() == "" or cuadrentrnombre.get() == "" or cuadrentrdni.get() == "":
           # ~ txt_result.config(text="Complete todos los campos requeridos!!!!", fg="red")
       # ~ else:
           # ~ conectardb()
           # ~ cursor.execute("INSERT INTO 'Alumnos' (Apellido, Nombre, DNI) VALUES(?, ?, ?)", (str(cuadrentrapellido.get()), str(cuadrentrnombre.get()), str(cuadrentrdni.get()))
           # ~ #conexion.commit()
           
   def validation(self):
       return len(self.cuadrentrapellido.get()) !=0 or len(self.cuadrentrnombre.get())!=0 or len(self.cuadrentrdni.get())!=0
   def agregadb(self):
       if self.validation():
           traer = "INSERT INTO Alumnos VALUES(NULL, ?, ?, ?)"
           datos = (self.cuadrentrapellido.get(), self.cuadrentrnombre.get(), self.cuadrentrdni.get())
           self.conectardb(traer, datos)
           self.mensaje["text"] = "Se ha incorporado a {} exitosamente".format(self.cuadrentrapellido.get())
       else:
           self.mensaje["text"] = "...no se ha ingresado datos. Vuelva a cargar datos por favor"
       self.leerdb()  
   
 
   
   
     
   def Exit(self):
       result = tkMessageBox.askquestion('Cooperadora', 'Me vas a aprobar?\n Daaaale aprobame ...por favooooooo', icon="warning")
       if result == 'yes':
          ventana1.destroy()
          exit()

 
if __name__ == '__main__':
   comenzar_ventana()
Responder
#2
Hola, bienvenido. ¿Podrías ser más específico? ¿Cuál es exactamente el error que estás obteniendo? Tratá de aislar el problema en un código más pequeño para que podamos ayudarte mejor.

Saludos
¡No te pierdas nuestro curso oficial en Udemy para aprender Python, bases de datos SQL, orientación a objetos, tkinter y mucho más!

También ofrecemos consultoría profesional de desarrollo en Python para personas y empresas.
Responder


Salto de foro:


Usuarios navegando en este tema: 1 invitado(s)