Error with SQLite3 on Python - python

This is my code. When I am trying to run this code. I face following error. Anyone can suggest me how to correct that error and this script can run successfully.
from tkinter import *
import sqlite3
global a, b
def sair_mestre ():
global mestre
mestre.quit()
def criar_tabela():
c.execute("CREATE TABLE IF NOT EXISTS Registro (Nome text, Senha text)")
def receberl():
global Nome, Senha
Nome = entradalogin.get()
Senha = entradasenha.get()
ler_dados(Senha)
if x:
sucesso = Label(mestre, text="Login Realizado com sucesso!")
sucesso.grid(row=1,column=1)
else:
inexistente = Label(mestre, text="Login errado")
inexistente.grid(row=1, column=1)
def receber2():
logincadastro2 = entradalogin2.get()
senhacadastro2 = entradasenha2.get()
c.execute("INSERT INTO Registro VALUES(?, ?)", (logincadastro2, senhacadastro2)) # Utilização de Variáveis
conexao.commit()
cadastro.destroy()
realizado = Label(mestre, text="Cadastrado com sucesso")
realizado.grid(row=1, column=1)
botaorealizado = Button(mestre, text="Ok", command=sair_mestre)
botaorealizado.grid(row=2, column=1)
def registro():
programa.destroy()
global cadastro
cadastro = Frame(mestre)
cadastro.grid()
realizando_cadastro = Label(cadastro, text="Realizando Cadastro...")
realizando_cadastro.grid(row=0, column=1)
labellogin = Label(cadastro, text="Login")
labellogin.grid(row=1, column=0)
labelsenha = Label(cadastro, text="Senha")
labelsenha.grid(row=2, column=0)
global entradalogin2
entradalogin2 = Entry(cadastro)
entradalogin2.grid(row=1, column=1)
global entradasenha2
entradasenha2 = Entry(cadastro, show="•")
entradasenha2.grid(row=2, column=1)
botaocadastro = Button(cadastro, text="Ok", command=receber2)
botaocadastro.grid(row=3, column=1)
def ler_dados (valorbusca):
global row
global x
buscar_dados = "SELECT * FROM Registro WHERE Nome = ? AND Senha = ?"
for row in c.execute(buscar_dados, (valorbusca,)):
if Nome and Senha in row:
x = True
conexao = sqlite3.connect("Registro_Cadastro.db")
c = conexao.cursor()
criar_tabela()
mestre = Tk()
programa = Frame(mestre)
programa.grid()
login = Label(programa, text="Login")
login.grid(row=0, column=0)
global entradalogin
entradalogin = Entry(programa)
entradalogin.grid(row=0, column=1)
senha = Label(programa, text="Senha")
senha.grid(row=1, column=0)
global entradasenha
entradasenha = Entry(programa, show="•")
entradasenha.grid(row=1, column=1)
botaook = Button(programa, text="Entrar",command= receberl)
botaook.grid(row=2, column=1)
botaoregistro = Button(programa, text="Cadastro",command= registro)
botaoregistro.grid(row=3,column=1)
mestre.mainloop()
This is the error thrown by my program. Can anyone help me to resolve this error?
I think the error is in receberl function.
File "-------", line 1558, in __call__
return self.func(*args)
File "------", line 17, in receberl
ler_dados(Senha)
File "------", line 69, in ler_dados
for row in c.execute(buscar_dados, (valorbusca,)):
sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 2, and there are 1 supplied.

The error message you are getting is pretty clear: your SELECT query binds two parameters, but your code only specifies one of them. To fix, first change your call to ler_dados() to pass in both the username and password:
def receberl():
global Nome, Senha
Nome = entradalogin.get()
Senha = entradasenha.get()
ler_dados(Nome, Senha)
# ... etc.
And then in your query bind both the username and password:
def ler_dados(username, valorbusca):
global row
global x
buscar_dados = "SELECT * FROM Registro WHERE Nome = ? AND Senha = ?"
for row in c.execute(buscar_dados, (username, valorbusca,)):
if Nome and Senha in row:
x = True

You need to provide 2 arguments for this query :
buscar_dados = "SELECT * FROM Registro WHERE Nome = ? AND Senha = ?"
When you call ler_dados(Senha) in the function receberl, looks like Nome is missing.
You should use something like : ler_dados(Nome, Senha) first
and then change the method ler_dados to :
def ler_dados (nome, senha):
global row
global x
buscar_dados = "SELECT * FROM Registro WHERE Nome = ? AND Senha = ?"
for row in c.execute(buscar_dados, (nome, senha)):
if Nome and Senha in row:
x = True

Related

How to store a lot of data from a treeview in a list, Python

I have the following problem with this part of my code I explain
What this function does is get the data from the DB and then fill the Treeview
def obtenerDatos():
cursor = conexion.cursor()
cursor.execute("SELECT empresas.empresa, picos.pico, tamano_precio.tamano FROM cilindros, empresas, picos, tamano_precio WHERE empresa_id = empresas.id AND pico_id = picos.id AND tamano_id = tamano_precio.id AND jefesf_id =? ORDER BY cilindros.tamano_id ASC", (validarCi,))
datosConsulta = cursor.fetchall()
return datosConsulta
cursor.close()
cursor.execute("SELECT * FROM jefesf WHERE ci =?", (validarCi,))
Then I use an if to check if there are people with that data registered in the DB
if cursor.fetchall():
ventana3 = Toplevel()
datosConsulta = obtenerDatos()
contador = 0
datosJefes = ttk.Treeview(ventana3, columns=("colum1", "colum2"))
datosJefes.column("#0", width=80)
datosJefes.column("colum1", width=80, anchor=CENTER)
datosJefes.column("colum2", width=80, anchor=CENTER)
datosJefes.heading("#0", text="Empresa")
datosJefes.heading("colum1", text="Pico")
datosJefes.heading("colum2", text="Tamaño")
Here I begin to fill the Treview with the data
for listado in datosConsulta:
datosJefes.insert("", "end", text=listado[0], values=(listado[1], listado[2]))
datosJefes.pack()
This is where I have the problem, what I want to do is to be able to select records from the treview and that those records are saved in a multilist and print them to me by console, but I don't know how
def SeleccinarRegistro():
global listaCilin
global dato1
global dato2
listaCilin = []
dato = datosJefes.item(datosJefes.selection())
datos = list(dato.values())
dato1 = datos[0]
dato2 = datos[2][0]
dato3 = datos[2][1]
I tried with a While loop but it generates an infinite loop, and my idea was every time I press the button the loop runs and saves the elements in the list
while SeleccinarRegistro:
listaCilin.append([dato1, dato2, dato3, validarCi])
print("Empresa: ", dato1)
print("Pico: ", dato2)
print("Tamano: ", dato3)
print(listaCilin)
Button(ventana3, text="Seleccionar", command=SeleccinarRegistro).pack()

Sum values ​from a treeview column

Good,
I'm trying to sum the values ​​of a column, while inputting it. Since I put a code in the entry and check if it exists and put it in columns in treeview, and I would like to add only the "price" values, but I can't do it, I get the data from the price column, but I can't get if This 5.99 I have entered another 5.99 add up and give me a total, as I add a price.
What I can be doing wrong? or what I have wrong
Any additional information would be appreciated.
def Cesta(self):
self.conex()
self.b_codigo = self.s_Codigo.get()
self.sql3 = "SELECT * FROM productos WHERE codigo = %s"
self.mycursor.execute(self.sql3,[(self.b_codigo)])
self.r_codigo = self.mycursor.fetchall()
self.row3 = [item['nombre'] for item in self.r_codigo]
if self.s_Codigo.get() == "":
MessageBox.showinfo("ERROR", "DEBES INTRODUCIR DATOS", icon="error")
elif self.r_codigo:
for self.x2 in self.r_codigo:
print (self.x2["nombre"], self.x2["talla"], self.x2["precio"]+"€")
self.tree.insert('', 'end', text=self.x2["nombre"], values=(self.x2["talla"],self.x2["precio"]+" €"))
print(self.x2["fecha"])
for self.item in self.tree.get_children():
self.resultado = 0
self.celda = int(self.tree.set(self.item,"col2"))
self.total = int(self.resultado) + int(float(self.celda))
print(self.total)
else:
MessageBox.showinfo("ERROR", "EL CODIGO INTRODUCIDO NO ES CORRECTO", icon="error")
self.clear_entry()
`
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/tkinter/__init__.py", line 1921, in __call__
return self.func(*args)
File "/Users/tomas/Downloads/PROYECTO/main.py", line 205, in Cesta
self.celda = int(self.tree.set(self.item,"col2"))
ValueError: invalid literal for int() with base 10: '134,99 €'
[Finished in 6.7s]
`
self.tree = ttk.Treeview(self.pagina1,columns=("col1","col2"), height=50)
self.tree.grid(column=0, row=2, padx=50, pady=100)
### COLUMNAS ###
self.tree.column("#0",width=250)
self.tree.column("col1",width=150, anchor=CENTER)
self.tree.column("col2",width=150, anchor=CENTER)
### NOMBRES COLUMNAS ###
self.tree.heading("#0", text="Articulo", anchor=CENTER)
self.tree.heading("col1", text="Talla", anchor=CENTER)
self.tree.heading("col2", text="Precio", anchor=CENTER)
Everything else is going well for me, but the part in which I want to add the results of the price column does not
What am I doing wrong, to be able to add the values ​​of the prices column every time I insert a new product?
I have already managed to solve the error, the new price is already added to the old one, thanks for making me reflect on it.
for self.x2 in self.r_codigo:
print (self.x2["nombre"], self.x2["talla"], self.x2["precio"]+"€")
self.tree.insert('', 'end', text=self.x2["nombre"], values=(self.x2["talla"],self.x2["precio"]))
self.total = 0
for self.item in self.tree.get_children():
self.celda = float(self.tree.set(self.item,"col2"))
self.total+=self.celda
print(self.total)

Set value on ttk.Checkbutton from a ttk.ComboBox

Hi i trying to set data on checkbutton from a combobox list, and then save this on json file. I have this codes from the program and save function.
def create_odontograma():
#Odontograma
global selected_patologias
global selected_p
selected_patologias = tk.StringVar()
patologias = ttk.Combobox(odontograma_frame, textvariable=selected_patologias)
patologias.grid(row=10,column=37)
patologias["values"] = ["Caries", "Endodoncia", "Exodoncia", "Corona", "Puente"]
global e18d
global e18o
global e18m
global e18v
global e18p
e18d = tk.StringVar()
e18o = tk.StringVar()
e18m = tk.StringVar()
e18v = tk.StringVar()
e18p = tk.StringVar()
elemento18L = ttk.Label(odontograma_frame, text="18")
elemento18L.grid(column=7, row=1)
elemento18D = ttk.Checkbutton(odontograma_frame, width=0 ,offvalue='Sano', onvalue=f'{selected_patologias.get()}', variable=e18d)
elemento18D.grid(column=6, row=3)
elemento18O = ttk.Checkbutton(odontograma_frame, width=0,offvalue=f'Sano', onvalue=f'{e18o}')
elemento18O.grid(column=7, row=3, padx= 1)
elemento18M = ttk.Checkbutton(odontograma_frame, width=0,offvalue=f'Sano', onvalue=f'{e18m}')
elemento18M.grid(column=8, row=3)
elemento18V = ttk.Checkbutton(odontograma_frame, width=0,offvalue=f'Sano', onvalue=f'{e18v}')
elemento18V.grid(column=7, row=2)
elemento18P = ttk.Checkbutton(odontograma_frame, width=0,offvalue=f'Sano', onvalue=f'{e18p}')
elemento18P.grid(column=7, row=4)
And here is the save function for json file
def guardar():
pacientes = {}
pacientes = []
pacientes.append(
{
"Nombre y Apellido": nombre.get(),
"Enf. Respiratorias" : f"{agreementa.get()}, {enfrespiratorias.get()}",
"Enf. Cardiacas" : f"{agreementb.get()}, {enfcardiacas.get()}",
"Enf. Alergicas" : f"{agreementc.get()}, {enfalegicas.get()}",
"Enf. Autoinmunes" : f"{agreementd.get()}, {enfautoinmunes.get()}",
"Enf. Renales" : f"{agreemente.get()}, {enfrenales.get()}",
"Cirugias Previas" : f"{agreementf.get()}, {cirugiasprevias.get()}",
"Motivo de Consulta" : f"{motivoc.get()}",
"18" :f"Palatino: {e18p.get()}, Vestibular: {e18v.get()}, Oclusal: {e18o.get()}, Mesial: {e18m.get()}, Distal: {e18d.get()}"
}
)
verificar = os.path.exists('./grupopacientes')
if verificar == True:
fileName = f"C:/Users/diego/Desktop/ProgrmacionPhyton/consultorio/pacientes/grupopacientes/{nombre.get()}.json"
isarchivo = os.path.isfile(fileName)
if isarchivo == True:
with open(f'grupopacientes/{nombre.get()}.json','w') as document:
json.dump(pacientes, document, indent=3)
messagebox.showinfo("Informacion","Se ha actualizado el paciente correctamente")
print (selected_patologias.get())
else:
with open(f'grupopacientes/{nombre.get()}.json','w') as document:
json.dump(pacientes, document, indent=3)
messagebox.showinfo("Informacion","Se ha añadido el paciente correctamente")
else:
directorio = "grupopacientes"
# Parent Directory path
parent_dir = "C:/Users/diego/Desktop/ProgrmacionPhyton/consultorio/pacientes"
# Path
path = os.path.join(parent_dir, directorio)
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
os.mkdir(path)
messagebox.showinfo("Informacion","La Carpeta no existia, se ha creado y se ha añadido el Paciente")
with open(f'grupopacientes/{nombre.get()}.json','w') as document:
json.dump(pacientes, document, indent=3)
messagebox.showinfo("Informacion","Se ha añadido el paciente correctamente")
I would like to get data from selected_patologias.get() and put in OnValue on checkbutton atributes, then get this "onvalue" and carry to json.

Combobox in tkinter not giving correct .get() value

This so weird, like i am trying to use if statement and the selection in combobox to do some specific command and when combobox value is selected to 'full_name' (part of elif) they return an messagebox, that is supposed to be showed only when the first if statement is executed but according to the conditions its supposed to return the elif part but it returns the if part. Is there a mistake in my code? If the Q is unclear please try referring the code or lemme knw :) Thanks in advance.
CODE:
def sp_patient():
#Creating window
sp_pat = Toplevel(update)
sp_pat.title('Choose Patient')
def search():
#Assigning variable to .get()
a = drops.get()
if a == 'id' or 'emirate_id' or 'email_adress' or 'gender' or 'DOB' or 'blood_grp' or 'COVID_test':
#Establishing connection
con = mysql.connect(host='***', user='nihaalnz',
password='****', database='nihaalnztrying')
# Making SQL command
c = con.cursor()
c.execute(f"SELECT * FROM patient_infos where `{a}` = '{e_1.get()}'")
# Executing and saving SQL command
records = c.fetchall()
if records == []:
messagebox.showinfo('Does not exist!','Sorry such patient does not exist')
else:
#Creating window
result_win = Toplevel(sp_pat)
result_win.title('Search result')
index=0
for index,x in enumerate(records):
num=0
for y in x:
lookup_label = Label(result_win,text=y)
lookup_label.grid(row=index+1,column=num)
num += 1
#Closing connection
con.close()
#Creating column header and exit button
l_1 = Label(result_win,text='ID',font=font_text)
l_2 = Label(result_win,text='Full Name',font=font_text)
l_3 = Label(result_win,text='Phone no.',font=font_text)
l_4 = Label(result_win,text='Emirates ID',font=font_text)
l_5 = Label(result_win,text='Email addr.',font=font_text)
l_6 = Label(result_win,text='Gender',font=font_text)
l_7 = Label(result_win,text='DOB',font=font_text)
l_8 = Label(result_win,text='Nationality',font=font_text)
l_9 = Label(result_win,text='Blood group',font=font_text)
l_10 = Label(result_win,text='COVID test',font=font_text)
l_11 = Label(result_win,text='Emergency no.',font=font_text)
btn_ext = Button(result_win,text='Exit',font=font_text,command=result_win.destroy,borderwidth=2,fg='#eb4d4b')
#Placing it in screen
l_1.grid(row=0,column=0,padx=20)
l_2.grid(row=0,column=1,padx=20)
l_3.grid(row=0,column=2,padx=20)
l_4.grid(row=0,column=3,padx=20)
l_5.grid(row=0,column=4,padx=20)
l_6.grid(row=0,column=5,padx=20)
l_7.grid(row=0,column=6,padx=20)
l_8.grid(row=0,column=7,padx=20)
l_9.grid(row=0,column=8,padx=20)
l_10.grid(row=0,column=9,padx=20)
l_11.grid(row=0,column=10,padx=20)
btn_ext.grid(row=index+2,columnspan=11,ipadx=240,sticky=E+W)
elif a == 'full_name' or 'ph_no' or 'nationality' or 'emergency_no':
#Creating window
result_win = Toplevel(sp_pat)
result_win.title('Search result')
#Establishing connection
con = mysql.connect(host='****', user='nihaalnz',
password='*****', database='nihaalnztrying')
# Making SQL command
c = con.cursor()
c.execute(f"SELECT * FROM patient_infos where `{a}` regexp '{e_1.get()}'")
# Executing and saving SQL command
records = c.fetchall()
index=0
for index,x in enumerate(records):
num=0
for y in x:
lookup_label = Label(result_win,text=y)
lookup_label.grid(row=index+1,column=num)
num += 1
#Closing connection
con.close()
#Creating column headers and exit button
l_1 = Label(result_win,text='ID',font=font_text)
l_2 = Label(result_win,text='Full Name',font=font_text)
l_3 = Label(result_win,text='Phone no.',font=font_text)
l_4 = Label(result_win,text='Emirates ID',font=font_text)
l_5 = Label(result_win,text='Email addr.',font=font_text)
l_6 = Label(result_win,text='Gender',font=font_text)
l_7 = Label(result_win,text='DOB',font=font_text)
l_8 = Label(result_win,text='Nationality',font=font_text)
l_9 = Label(result_win,text='Blood group',font=font_text)
l_10 = Label(result_win,text='COVID test',font=font_text)
l_11 = Label(result_win,text='Emergency no.',font=font_text)
btn_ext = Button(result_win,text='Exit',font=font_text,command=result_win.destroy,borderwidth=2,fg='#eb4d4b')
#Placing it on screen
l_1.grid(row=0,column=0,padx=20)
l_2.grid(row=0,column=1,padx=20)
l_3.grid(row=0,column=2,padx=20)
l_4.grid(row=0,column=3,padx=20)
l_5.grid(row=0,column=4,padx=20)
l_6.grid(row=0,column=5,padx=20)
l_7.grid(row=0,column=6,padx=20)
l_8.grid(row=0,column=7,padx=20)
l_9.grid(row=0,column=8,padx=20)
l_10.grid(row=0,column=9,padx=20)
l_11.grid(row=0,column=10,padx=20)
btn_ext.grid(row=index+2,columnspan=11,ipadx=240,sticky=E+W)
elif a == 'Search by...':
#Error message
messagebox.showinfo('No choice given','Please choose a valid option to search by...')
#Defining dropdown and entry box
drops = ttk.Combobox(sp_pat,value=['Search by...','id','full_name','ph_no','emirate_id','email_addr','gender','DOB','nationality','blood_grp','COVID_test','emergency_no'],state='readonly')
print(drops.get())
drops.current(0)
e_1 = Entry(sp_pat)
#Defining Labels and search button
l_sch = Label(sp_pat,text='Search',font=Font(size='20'))
l_id = Label(sp_pat,text='Enter',font=font_text)
bt_db = Button(sp_pat,text='Search',command=search)
#Placing it in screen
drops.grid(row=1,columnspan=3,ipady=5,padx=5,pady=10)
e_1.grid(row=2,column=1,ipady=5,padx=5,pady=5)
l_id.grid(row=2,column=0,padx=5,pady=5)
bt_db.grid(row=3,columnspan=2,padx=5,pady=5,sticky=E+W)
l_sch.grid(row=0,columnspan=2,sticky=E+W,padx=10,pady=10)
The problem is this line:
if a == 'id' or 'emirate_id' or...
This statement always return True. It is evaluating whether a=="id" or emirate_id is True, and a non-empty string always returns True.
You can be explicit and use:
if a == 'id' or a == 'emirate_id' or ...
Or better yet, use keyword in:
if a in ("id", "emirate_id",...)

Kivy reload Buttons(via function)on app startup

Hi i'm pretty new with python and kivy , im trying to do a simple "to do" app.. My code looks horrible, i know, and im sorry for that..
I have a table in sqlite3 with some information stored in it. I would like to call a function that query this table on app start up. I can't figure out how to make it work.. Here is my code
Python:
import sqlite3
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.textinput import TextInput
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.togglebutton import ToggleButton
from kivy.clock import Clock
from kivy.uix.floatlayout import FloatLayout
from functools import partial
class GetLinksButton(Button):
def get_caption(self):
# DEFINIZIONE CHE SI POTREBBE FARE IN KV .. CREAZIONE POPUP CON 2 BOTTONI E TEXTINPUT
content = BoxLayout(orientation='vertical')
txt = TextInput(text = "",focus=False,multiline=False,size_hint=(1,0.2),font_size= 40)
content.add_widget(txt)
mybutton = Button(text='Add',size_hint=(1,0.2),font_size=20)
mybutton2 = Button(text='Close',size_hint=(1,0.2),font_size=20)
content.add_widget(mybutton)
content.add_widget(mybutton2)
mypopup = Popup(title = 'Add item to list',
content = content,
size_hint = (1, 0.4),
auto_dismiss = False,
).open()
def saveTxt(tt):
mypopup.dismiss() # FUNZIONE CHIAMATA, CHIUSURA POPUP
try:
self.set_caption(txt.text) # CHIAMA FUNZIONE DI CREAZIONE BOTTONE CON ARG IL CAPTURE DEL TESTO IN TEXTBOX
except:
pass
mybutton.bind(on_press = saveTxt) # CHIAMA FUNZIONE DI CAPTURE DEL TESTO E CHIUSURA POPUP
txt.bind(on_text_validate = saveTxt)# CHIAMA FUNZIONE DI CAPTURE DEL TESTO E CHIUSURA POPUP
mybutton2.bind(on_press = mypopup.dismiss)
# FUNZIONE CHIAMATA PER INSERIMENTO NUOVO BOTTONE IN TABELLA LOCALTB
def btn_db(self,st):
#con = None
elementList =[]
print "stringa dentro a dtn_db "+ st
try:
con = sqlite3.connect('localdb.db')
cur = con.cursor()
cur.execute("insert into localtb (Item, State) values ( ?, ?)",(st, 0))
con.commit()
cur.execute("select * from localtb")
data = cur.fetchall()
con.close()
for x in data:
print x
elementList.append(x[0])
except:
print "non va"
w = str(elementList)
return w
# CREAZIONE BOTTONE DA INPUTO DI TESTO , TEXT BUTTON == INPUT INSERITO IN BOX
def set_caption(self,stringa):
string = stringa[0].upper()+stringa[1:].lower()
print string, " stringa prima del for"
# DA SISTEMARE CICLO "INUTILE"
#for i in range(1):
link_button = LinkButton(
text = string)
print "tra for e add_widget"
self.links_grid.add_widget(link_button)
print string," strinda PRIMA call a btn_db"
self.btn_db(string) # CALL A FUNZIONE PER INSERIRE IL BOTTONE IN TABELLA LOCALE (LOCALTB)
print string," strinda DOPO call a btn_db"
class LinkButton(ToggleButton):
# GESTIONE DEL TOGGLE.. QUNANDO SI TOGGLA IL BOTTONE PARTE LA QUERY E INVERTE LO STATO ATTUALE CON L'ALTRO STATO , DA 0 A 1 E VICEVERSA PER IL BOTTONE PREMUTO
def toggleState(self):
#con = None
red = (83,0,0,1)
green = (0,83,0,1)
print self.background_color
if self.background_color == [83,0,0,1]:
self.background_color = green
else:
print "dentro ELSE"
self.background_color = red
elementList =[]
pressed = str(self.text)
print "tasto premuto cambio stato: "+pressed
try:
con = sqlite3.connect('localdb.db')
cur = con.cursor()
cur.execute("update localtb set State = (CASE WHEN State = 0 THEN State + 1 WHEN State = 1 THEN State - 1 end ) WHERE Item = ?",(pressed,)) # ATTENTO ALLA VIRGOLA DOPO PRESSED(SE NON NON FUNZIONA)
con.commit()
cur.execute("select * from localtb")
data = cur.fetchall()
con.close()
for x in data:
print x
elementList.append(x[0])
except:
print "non va"
w = str(elementList)
return w
class SmsButton(Button):
# PROVE DI RELOAD SESSIONE PRECENDETE- FALLITE.
def reloadSession(self):
try:
con = sqlite3.connect('localdb.db')
cur = con.cursor()
cur.execute("select * from localtb")
data = cur.fetchall()
con.close()
for x in data:
reload_Element = str(x[0])
if x[1] == 0:
print "in if: ", x[1]
link_button = LinkButton(text = reload_Element,background_color = [83,0,0,1])
else:
print "in else: ", x[1]
link_button = LinkButton(text = reload_Element,background_color = [0,83,0,1])
self.links_grid.add_widget(link_button)
except Exception as inst:
print inst.args
print "non va"
class Test(App):
pass
if __name__ == '__main__':
Test().run()
KV:
#:kivy 1.9.1
MyRootasdasd:
rows: 1
RightArea:
<MyRootasdasd#GridLayout>:
#rows: 1
#RightArea:
<RightArea#GridLayout>:
cols: 1
size_hint_x: 0.3
spacing: '1dp'
ScrollView:
LinksGrid:
id: links_grid
BoxLayout:
size_hint: (1,0.08)
GetLinksButton:
links_grid: links_grid
SmsButton:
links_grid: links_grid
<LinksGrid#GridLayout>:
cols: 2
spacing: '.5dp'
size_hint_y: None
height: self.minimum_height
<SmsButton>:
size_hint_y: 1
text: 'SMS'
on_press: self.reloadSession()
<GetLinksButton>:
size_hint_y: 1
text: 'Get links'
on_press: self.get_caption()
<LinkButton>:
color: (0, 0, 0, 1) #COLORE TESTO
background_normal: '' # RESET DELLA TINTA (STRINGA, quindi carica un immagine non un colore)
background_color: (83, 0, 0, 1) #COLORE SFONDO -> qui sotto la call alla classe che gestisce il toggle del bottone
on_release: self.toggleState()
size_hint_y: None
height: '80dp'
some pieces of code are unused don't worry about it.
Function i need to call is reloadSession that query table and then with the information retrieved create n buttons...
As you can see, in the SmsButton class(in KV) call that function(ON_PRESS), i need to do the same thing but automatically on app start up... How can i do that??
Sorry for my bad english and coding.. Im new, im trying a lot of stuff, i would appreciate your help.
Thank you.
Yvan.
EDIT: removed unused code
EDIT : #bj0
thanks for the tips.. i've tryied to use build function in alla the way i know. but it doesnt work ...i get this error
("'Test' object has no attribute 'links_grid'",)
the code im using now is this..
class Test(App):
def build(self):
try:
con = sqlite3.connect('localdb.db')
cur = con.cursor()
cur.execute("select * from localtb")
data = cur.fetchall()
con.close()
for x in data:
reload_Element = str(x[0])
if x[1] == 0:
print "in if: ", x[1]
link_button = LinkButton(text = reload_Element,background_color = [83,0,0,1])
else:
print "in else: ", x[1]
link_button = LinkButton(text = reload_Element,background_color = [0,83,0,1])
self.links_grid.add_widget(link_button)
except Exception as inst:
print inst.args
print "non va"
obviously Test class has no links_grid attribute.. but how can i solve this problem ?
Thanks again

Categories

Resources