Python dependant combobox based on sqlite DB values

后端 未结 1 1364
名媛妹妹
名媛妹妹 2021-01-17 03:19

I am new to python and I am trying to make a budget tracking application, with GUI. To do this I enter every amount I spend in the programme. These amounts are stocked in an

1条回答
  •  一整个雨季
    2021-01-17 04:18

    Question: Based on the selected option in the first Combobox, query from a sqlite3 table the values of the second Combobox.


    Core Points:

    1. Bind a callback to the event '<>'

      self.bind('<>', self.on_selected)
      
    2. Query the id of the selected item and pass it to SubCategory.configure(query=)

      def on_selected(self, event):
          _query = 'SELECT id FROM Category WHERE name == "{}"'.format(self.get())
          self.subcategory.configure(query=self.db.query(_query)[0])
      
    3. Query the name's based on the id and configure the SubCategory(Combobox) values.

      def configure(self, cnf=None, **kw):
          ...
              _query = 'SELECT name FROM SubCategory WHERE ID_Category == {}'.format(_query)
              super().configure(values=self.db.query(_query))
      

    Imports and Data

    import tkinter as tk
    import tkinter.ttk as ttk
    import sqlite3
    
    
    class DB:
        conn = None
    
        def __init__(self):
            if not DB.conn:
                DB.conn = sqlite3.connect(':memory:')
    
                print('DB.__init__()'.format())
                cur = DB.conn.cursor()
                cur.execute("CREATE TABLE IF NOT EXISTS Category(name TEXT, id INTEGER)")
    
                for _id, name in enumerate(('Revenues', 'Assets', 'Living expenses'), 1):
                    cur.execute("INSERT INTO Category(id, name) VALUES (?,?)", (_id, name))
    
                cur.execute("CREATE TABLE IF NOT EXISTS SubCategory(name TEXT, id INTEGER, ID_Category INTEGER)")
                for _id, name in enumerate(('Salary', 'Saving account', 'Interest costs'), 1):
                    cur.execute("INSERT INTO SubCategory(id, name, ID_Category) VALUES (?,?,?)", (_id, name, _id))
    
        def query(self, query):
            cur = DB.conn.cursor()
            return [record[0] for record in cur.execute(query)]
    

    Customized Combobox Category

    class Category(ttk.Combobox):
        def __init__(self, parent, **kwargs):
            self.subcategory = kwargs.pop('subcategory', None)
            self.db = kwargs.pop('db', None)
    
            # defaults
            kwargs['width'] = kwargs.get('width', 27)
            super().__init__(parent, values=(), **kwargs)
    
            self.configure(values=self.db.query('SELECT name FROM Category'))
            self.bind('<>', self.on_selected)
    
        def on_selected(self, event):
            _query = 'SELECT id FROM Category WHERE name == "{}"'.format(self.get())
            self.subcategory.configure(query=self.db.query(_query)[0])
    

    Customized Combobox SubCategory

    class SubCategory(ttk.Combobox):
        def __init__(self, parent, **kwargs):
            self.db = kwargs.pop('db', None)
    
            # defaults
            kwargs['width'] = kwargs.get('width', 27)
            super().__init__(parent, values=(), **kwargs)
    
        def configure(self, cnf=None, **kw):
            _query = kw.pop('query', None)
            if _query is not None:
                _query = 'SELECT name FROM SubCategory WHERE ID_Category == {}'.format(_query)
                super().configure(values=self.db.query(_query))
                self.event_generate('')
            else:
                super().configure(cnf, **kw)
    

    Usage

    class App(tk.Tk):
        def __init__(self):
            super().__init__()
            self.geometry('200x200')
    
            self.db = DB()
    
            subcategory = SubCategory(self, db=self.db)
            category = Category(self, subcategory=subcategory, db=self.db)
    
            category.pack()
            subcategory.pack()
    
            category.event_generate('')
    
    
    if __name__ == "__main__":
        App().mainloop()
    

    Tested with Python: 3.5 - 'TclVersion': 8.6 'TkVersion': 8.6

    0 讨论(0)
提交回复
热议问题