help with storing value of a local variable in python

0
Hello, well, I'm writing an application using SQLite and Python, everything was running fine until I had a problem that I can not solve, I happen to have a db of fipe, so I need to load 3 combobox with brand, model and year , then I decided to do it as follows, in the first combobox I load the tags, then I load the choice with a "get ()" , with the response from that "get () " I would load _id like this:

  

('SELECT _id FROM tag WHERE name = {}'. format (respostado.get ()))

Soon after this response would load the models with the response of this select, my problem is that the answer from "get ()" is inside my "def , event): " and I'm not able to use this local variable, I already tried to transform it into a global variable, I already tried adding the string before creating an open variable and then adding it inside the function, I already tried to do everything that my knowledge is capable but I can not solve it, someone gives me a light, now besides being with the problem I am curious also to know the solution, I will leave the application code (it has some parts incomplete because I have already rewrote a thousand times to try to solve the problem, but it is better for you to understand my problem).

import tkinter as tk

import tkinter.ttk as ttk import sqlite3

class Sqlite:

def __init__(self, master):
    self.master = master
    self.db = sqlite3.connect('fdb.db')
    self.cb = ttk.Combobox(master)
    self.cb.pack()
    self.cb['values'] = self.combo_input()
    self.cb.bind("<<ComboboxSelected>>", self.PegarMarca)
    self.cc = ttk.Combobox()
    self.cc.pack()
    self.cc['values'] = self.modelo()

def combo_input(self) -> object:
    cursor = self.db.cursor()
    cursor.execute('SELECT nome FROM marca')
    data = []

    for row in cursor.fetchall():
        data.append(row[0])
    return data

def PegarMarca(self, event):
    print(self.cb.get())

def modelo(self) -> object:
    cursor = self.db.cursor ()
    cursor.execute('SELECT _id FROM marca WHERE nome = "{}"')
    data = []

    for row in cursor.fetchall():
        data.append(row[0])
    return data

root = tk.Tk () Sqlite (root) root.mainloop ()

    
asked by anonymous 02.07.2018 / 04:43

1 answer

0

The form that is structured does not facilitate queries in the database.

As I do not know the structure of your table let's try to simulate.

Following the example below:

BEGIN TRANSACTION;
CREATE TABLE IF NOT EXISTS 'veiculos' (
    'marca' TEXT,
    'modelo'    TEXT,
    'ano'   INTEGER,
    'cor'   TEXT
);
INSERT INTO 'veiculos' VALUES ('Fiat','Uno',2000,'Branco');
INSERT INTO 'veiculos' VALUES ('Fiat','Palio',2017,'Preto');
INSERT INTO 'veiculos' VALUES ('Fiat','Uno',1990,'Roxo');
INSERT INTO 'veiculos' VALUES ('Ford','Ka',2015,'Amarelo');
INSERT INTO 'veiculos' VALUES ('Fiat','Uno',2000,'Preto');
COMMIT;

I believe that:

  • When combobox tags the combobox templates should be completed.
  • When selecting the template combobox year should be completed.
  • Lastly by selecting the year combobox the vehicles are displayed (or you can by a button that triggers the final event).

Based on the above:

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Exemplo Tkinter com SQLite"""
import sqlite3
import tkinter as tk
import tkinter.ttk as ttk


class ConectarDB:
    def __init__(self):
        self.conexao = sqlite3.connect('fdb.db')
        self.cursor = self.conexao.cursor()

    def buscar_marca(self):
        return self.cursor.execute('SELECT DISTINCT marca FROM veiculos').fetchall()

    def busca_modelo(self, marca):
        return self.cursor.execute(
            "SELECT DISTINCT modelo FROM veiculos WHERE marca=? COLLATE NOCASE", (marca,)).fetchall()

    def buscar_ano(self, modelo):
        return self.cursor.execute(
            "SELECT DISTINCT ano FROM veiculos WHERE modelo=? COLLATE NOCASE", (modelo,)).fetchall()

    def buscar_veiculos(self, marca, modelo, ano):
        return self.cursor.execute(
            "SELECT * FROM veiculos WHERE marca=? and modelo=? and ano=? COLLATE NOCASE",
            (marca, modelo, ano,)).fetchall()


class Janela(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        # Coletando informações do monitor
        largura = round(self.winfo_screenwidth() / 2)
        altura = round(self.winfo_screenheight() / 2)
        tamanho = ('%sx%s' % (largura, altura))

        # Título da janela principal.
        self.master.title('Exemplo')
        # Tamanho da janela principal.
        self.master.geometry(tamanho)
        # Gerenciador de layout da janela principal.
        self.pack()

        # Criando uma instancia do banco de dados (Abrindo a conexão).
        self.banco = ConectarDB()

        # Inserindo widgets na janela principal.
        self.criar_widgets()

    def criar_widgets(self):
        # Combobox marcas.
        self.comboboxMarca = ttk.Combobox()
        # Preenchedo o combobox com os valores do banco.
        self.comboboxMarca['values'] = self.banco.buscar_marca()
        # Evento que é disparado quando algo é selecionado.
        self.comboboxMarca.bind('<<ComboboxSelected>>', self.pegar_modelo)
        self.comboboxMarca.pack()

        # Combobox modelo.
        self.comboboxModelo = ttk.Combobox()
        self.comboboxModelo.bind('<<ComboboxSelected>>', self.pegar_ano)
        self.comboboxModelo.pack()

        # Combobox ano.
        self.comboboxAno = ttk.Combobox()
        self.comboboxAno.bind('<<ComboboxSelected>>', self.resultado)
        self.comboboxAno.pack()

        # Listbox que irá exibir os resultados localizados.
        self.listbox = tk.Listbox()
        self.listbox.pack()

    def pegar_modelo(self, event):
        # Coletando o valor que foi selecionado no combobox marca.
        marca = self.comboboxMarca.get()

        # Buscando dados no banco e preenchendo o combobox modelo.
        self.comboboxModelo['values'] = self.banco.busca_modelo(marca=marca)

    def pegar_ano(self, event):
        # Coletando o valor que foi selecionado no combobox modelo.
        modelo = self.comboboxModelo.get()

        # Buscando dados no banco e preenchendo o combobox ano.
        self.comboboxAno['values'] = self.banco.buscar_ano(modelo=modelo)

    def resultado(self, event):
        # Coletando os valores de todos os combobox.
        marca = self.comboboxMarca.get()
        modelo = self.comboboxModelo.get()
        ano = self.comboboxAno.get()

        # Limpando o listbox.
        self.listbox.delete(0, tk.END)

        # Buscando dados no banco e utilizando um
        # laço de repetição para preencher o listbox.
        for veiculo in self.banco.buscar_veiculos(marca=marca, modelo=modelo, ano=ano):
            self.listbox.insert(tk.END, veiculo)


root = tk.Tk()
app = Janela(master=root)
app.mainloop()

I hope it helps you as a reference or for ideas.

    
02.07.2018 / 18:25