{"id":3380,"date":"2019-09-06T09:05:37","date_gmt":"2019-09-06T07:05:37","guid":{"rendered":"https:\/\/pythonprogramming.altervista.org\/?p=3380"},"modified":"2019-11-13T19:18:34","modified_gmt":"2019-11-13T18:18:34","slug":"sqlite-and-tkinter-in-python-part-3-3","status":"publish","type":"post","link":"https:\/\/pythonprogramming.altervista.org\/sqlite-and-tkinter-in-python-part-3-3\/","title":{"rendered":"Sqlite and Tkinter (in Python) &#8211; part 3.3"},"content":{"rendered":"<p>Here we are with the final part of the re-organization of the code. Now we can create (again) the tables. Next time we will look at inserting data.<\/p>\n<h2>The sql code<\/h2>\n<p>To create a table we can do something like this in sql:<\/p>\n<pre class=\"lang:default decode:true\">create table names (\r\n\tid integer,\r\n\tname text,\r\n\tcity text\r\n\t);<\/pre>\n<p>So, what we need it to input a name and the text with the id, name and city. It&#8217;s so simple. But&#8230; to create widgets to get the input and open the database and execute that code&#8230; could take some time&#8230; once you get the habit to this code, you will make it in no time, but the start can be a little &#8216;messy&#8217;.<\/p>\n<p>What we need to do, in the essence, is to execute the code with this code in a function called mk_tb:<\/p>\n<pre class=\"lang:default decode:true \">conn = lite.connect(\"database.db\")\r\ncur = conn.cursor()\r\ncur.execute(\"create table name(id integer, name text, city text);\")<\/pre>\n<p>Strangely, the code below to make this simple stuff is very long.<\/p>\n<p>First of all we need to make the name &#8216;abstract&#8217; using a variable. The same for the fields. We also need to get the specific name and fields by the input to the user. We will use an entry for the name of the table and a text widgets for the fields name. So, it will be all very simple.<\/p>\n<p>The code should be something like this:<\/p>\n<pre class=\"lang:default decode:true \">cur.execute(\"\"\"create table {} (\r\n\t{}\r\n);\"\"\".format(name, fields))<\/pre>\n<p>We will use this into a method of a class, so the variables will have a self. before their names, as you will see in the next part of this post and in the video.<\/p>\n<h2>Let&#8217;s take a look at the code until now<\/h2>\n<p>All will be explained in the video at the end, but let&#8217;s focus on the changes in the code.<\/p>\n<p>In the last post the code was this:<\/p>\n<pre class=\"lang:default decode:true\">import sqlite3 as lite\r\nfrom sqlite3 import Error\r\nimport tkinter as tk\r\nfrom glob import glob\r\n\r\nclass App:\r\n    # window\r\n    def __init__(self, root):\r\n        self.root = root\r\n        self.root.geometry(\"200x200\")\r\n        self.root['bg'] = \"cyan\"\r\n        tk.Button(self.root, text = \"Create a database\",\r\n            command= lambda: self.new_window(Win1)).pack()\r\n        tk.Button(self.root, text = \"Create a table\",\r\n            command= lambda: self.new_window(Win2)).pack()\r\n    \r\n    def new_window(self, _class):\r\n        self.new = tk.Toplevel(self.root)\r\n        _class(self.new)\r\n\r\n\r\nclass Win:\r\n    fields = [] # To create the records field in the databases table\r\n    def listbox(self):\r\n        self.lab_lb = tk.Label(self.root, text=\"Database in the folder\")\r\n        self.lab_lb.pack()\r\n        self.lb = tk.Listbox(self.root) # create a listbox\r\n        self.lb.pack()                  # make it visible\r\n        for file in glob(\"*.db\"):       # insert all the db file in the listbox\r\n            self.lb.insert(tk.END, file)\r\n\r\nclass Win1(Win):\r\n    def __init__(self, root):\r\n        self.root = root\r\n        self.root.geometry(\"400x300\")\r\n        self.root.title(\"Create Database\")\r\n        self.widgets_db() # widgets to create the new db\r\n        self.listbox()\r\n\r\n    def widgets_db(self):\r\n        \"\"\"Widgets to create a new database\r\n\r\n            - a label \"Create a db\" ........ self.l\r\n            - an entry ..................... self.e \r\n            - a button ..................... self.b\r\n        \r\n        \"\"\"\r\n        self.l = tk.Label(self.root, text=\"Create a db [insert the name]\")\r\n        self.l.pack()\r\n        self.db = tk.StringVar()\r\n        self.e = tk.Entry(self.root, textvariable = self.db)\r\n        self.e.pack()\r\n        self.b = tk.Button(self.root, text=\"Create DB\", command= lambda: self.mk_db())\r\n        self.b.pack()\r\n\r\n    def mk_db(self):\r\n        db = self.e.get()\r\n        if db.endswith(\".db\"):\r\n            pass\r\n        else:\r\n            db = db + \".db\"\r\n        try:\r\n            conn = lite.connect(db)\r\n            if db in self.lb.get(0, tk.END):\r\n                pass\r\n            else:\r\n                self.lb.insert(tk.END, db)\r\n            return conn\r\n        except Error as e:\r\n            print(e)\r\n        finally:\r\n            self.db.set(\"\")\r\n            conn.close()\r\n\r\nclass Win2(Win):\r\n    def __init__(self, root):\r\n        self.root = root\r\n        self.root.geometry(\"400x500\")\r\n        self.root.title(\"Create Tables\")\r\n        self.listbox()\r\n\r\nroot = tk.Tk()\r\napp = App(root)\r\nroot.mainloop()<\/pre>\n<h2>The new code<\/h2>\n<p>In this &#8216;episode&#8217; we&#8217;ve added the widgets for the input of the name of the table<\/p>\n<pre class=\"lang:default decode:true\">    def widgets_tb(self):\r\n        \"\"\"Widgets to create tables\"\"\"\r\n        self.frame1 = tk.Frame(self.root)\r\n        self.frame1.pack()\r\n        self.lbdbn = tk.Label(self.frame1, text = \"Choose a Database\")\r\n        self.lbdbn.pack(side=\"left\")\r\n        # entry + StringVar\r\n        self.string_dbn = tk.StringVar() # THIS get() the text in the entry\r\n        # to get the value in the entry =&gt; a = self.string_tbn.get()\r\n        # or a = self.entry_tbn.get()\r\n        # if we want to clear the text into the entry =&gt; self.string_tbn(\"\")\r\n        self.entry_dbn = tk.Entry(self.frame1, textvariable = self.string_dbn)\r\n        self.entry_dbn.pack(side=\"left\")\r\n    \r\n        # ========== insert table data ===================\r\n        # name of table\r\n        self.frame2 = tk.Frame(self.root)\r\n        self.frame2.pack()\r\n        self.lbtbn = tk.Label(self.frame2, text = \"Insert Table name\")\r\n        self.lbtbn.pack(side=\"left\")\r\n        self.string_tbn = tk.StringVar()\r\n        self.entry_tbn = tk.Entry(self.frame2, textvariable = self.string_tbn)\r\n        self.entry_tbn.pack(side=\"left\")<\/pre>\n<p>We needed also to input the fields text<\/p>\n<pre class=\"lang:default decode:true \">    def widgets_fl(self):\r\n        \"\"\"The widgets to insert fields\"\"\"\r\n        self.frame3 = tk.Frame(self.root)\r\n        self.frame3.pack()\r\n        self.lfl = tk.Label(self.frame3, text = \"Insert the table fields\")\r\n        self.lfl.pack()\r\n        self.lfl['bg'] = 'gold'\r\n        self.text = tk.Text(self.frame3, height=9)\r\n        self.text.pack()\r\n        self.btb = tk.Button(self.root, text=\"Create The table\", command= lambda: self.mk_tb())\r\n        self.btb.pack()<\/pre>\n<h2>The video explaining everything<\/h2>\n<p><iframe loading=\"lazy\" title=\"Sqlite and tkinter with Python - Part 3.3\" width=\"747\" height=\"420\" src=\"https:\/\/www.youtube.com\/embed\/ULk2X0OFy4w?feature=oembed&amp;enablejsapi=1\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<h2>The entire new code<\/h2>\n<pre class=\"lang:default decode:true \">import sqlite3 as lite\r\nfrom sqlite3 import Error\r\nimport tkinter as tk\r\nfrom glob import glob\r\n\r\n\r\nclass App:\r\n\r\n    def __init__(self, root):\r\n        self.root = root\r\n        self.root.geometry(\"200x200\")\r\n        self.root['bg'] = \"cyan\"\r\n        tk.Button(\r\n            self.root, text=\"Create a database\",\r\n            command=lambda: self.new_window(Win1)).pack()\r\n        tk.Button(\r\n            self.root, text=\"Create a table\",\r\n            command=lambda: self.new_window(Win2)).pack()\r\n\r\n    def new_window(self, _class):\r\n        self.new = tk.Toplevel(self.root)\r\n        _class(self.new)\r\n\r\n\r\nclass Win:\r\n    fields = []\r\n\r\n    def listbox(self):\r\n        self.lab_lb = tk.Label(self.root, text=\"Database in the folder\")\r\n        self.lab_lb['bg'] = 'gold'\r\n        self.lab_lb.pack()\r\n        self.lb = tk.Listbox(self.root)\r\n        self.lb.pack()\r\n        for file in glob(\"*.db\"):\r\n            self.lb.insert(tk.END, file)\r\n        self.lb.bind(\"&lt;Double-Button&gt;\", lambda x: self.show_selection())\r\n\r\n    def show_selection(self):\r\n        print(\"This function here does not works\")\r\n\r\n\r\nclass Win1(Win):\r\n    def __init__(self, root):\r\n        self.root = root\r\n        self.root.geometry(\"400x300\")\r\n        self.root.title(\"Create Database\")\r\n        self.widgets_db()\r\n        self.listbox()\r\n\r\n    def widgets_db(self):\r\n        self.label = tk.Label(\r\n            self.root, text=\"Create a db [insert the name]\")\r\n        self.label.pack()\r\n        self.db = tk.StringVar()\r\n        self.e = tk.Entry(self.root, textvariable=self.db)\r\n        self.e.pack()\r\n        self.b = tk.Button(\r\n            self.root, text=\"Create DB\", command=lambda: self.mk_db())\r\n        self.b.pack()\r\n\r\n    def mk_db(self):\r\n        db = self.e.get()\r\n        if db.endswith(\".db\"):\r\n            pass\r\n        else:\r\n            db = db + \".db\"\r\n        try:\r\n            conn = lite.connect(db)\r\n            if db in self.lb.get(0, tk.END):\r\n                pass\r\n            else:\r\n                self.lb.insert(tk.END, db)\r\n            return conn\r\n        except Error as e:\r\n            print(e)\r\n        finally:\r\n            self.db.set(\"\")\r\n            conn.close()\r\n\r\n\r\nclass Win2(Win):\r\n    def __init__(self, root):\r\n        self.root = root\r\n        self.root.geometry(\"400x500\")\r\n        self.root.title(\"Create Tables\")\r\n        self.listbox()\r\n        self.widgets_tb()\r\n        self.widgets_fl()\r\n\r\n    def widgets_tb(self):\r\n        \"\"\"Widgets to create tables\"\"\"\r\n        self.frame1 = tk.Frame(self.root)\r\n        self.frame1.pack()\r\n        self.lbdbn = tk.Label(\r\n            self.frame1, text=\"Choose a Database\")\r\n        self.lbdbn.pack(side=\"left\")\r\n        # entry + StringVar\r\n        self.string_dbn = tk.StringVar()\r\n        # to get the value in the entry =&gt; a = self.string_tbn.get()\r\n        # or a = self.entry_tbn.get()\r\n        # if we want to clear the text into the entry =&gt; self.string_tbn(\"\")\r\n        self.entry_dbn = tk.Entry(\r\n            self.frame1, textvariable=self.string_dbn)\r\n        self.entry_dbn.pack(side=\"left\")\r\n\r\n        # ========== insert table data ===================\r\n        # name of table\r\n        self.frame2 = tk.Frame(self.root)\r\n        self.frame2.pack()\r\n        self.lbtbn = tk.Label(\r\n            self.frame2, text=\"Insert Table name\")\r\n        self.lbtbn.pack(side=\"left\")\r\n        self.string_tbn = tk.StringVar()\r\n        self.entry_tbn = tk.Entry(\r\n            self.frame2, textvariable=self.string_tbn)\r\n        self.entry_tbn.pack(side=\"left\")\r\n\r\n    def widgets_fl(self):\r\n        \"\"\"The widgets to insert fields\"\"\"\r\n        self.frame3 = tk.Frame(self.root)\r\n        self.frame3.pack()\r\n        self.lfl = tk.Label(\r\n            self.frame3, text=\"Insert the table fields\")\r\n        self.lfl.pack()\r\n        self.lfl['bg'] = 'gold'\r\n        self.text = tk.Text(self.frame3, height=9)\r\n        self.text.pack()\r\n        self.btb = tk.Button(\r\n            self.root, text=\"Create The table\", command=lambda: self.mk_tb())\r\n        self.btb.pack()\r\n\r\n    def show_selection(self):\r\n        x = self.lb.curselection()[0]\r\n        x = self.lb.get(x)\r\n        self.string_dbn.set(x)\r\n\r\n    def mk_tb(self):\r\n        self.conn = lite.connect(self.string_dbn.get())\r\n        self.cur = self.conn.cursor()\r\n        self.cur.execute(\r\n            \"\"\"create table {}(\r\n            {});\"\"\".format(\r\n                self.string_tbn,\r\n                self.text.get(\"1.0\", 'end-1c')))\r\n\r\n\r\nroot = tk.Tk()\r\napp = App(root)\r\nroot.mainloop()\r\n<\/pre>\n<script>\r\nlet title = \"SqLite3 & Python\"\r\n\tlet links = [\r\n[\"https:\/\/pythonprogramming.altervista.org\/python-and-sqlite-basics\/\",\"Sqlite3 Basic 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/python-and-sqlite-with-tkinter-part-1\/\",\"Sqlite3 - part 1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/sqlite3-tkinter-part-ii\/\",\"Sqlite3 - part 2\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/python-sqlite3-part-3-reoganizing-the-code\/\",\"Sqlite3 - part 3.1\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/sqlite-and-python-part-3-2\/\",\"Sqlite3 - part 3.2\"],\r\n[\"https:\/\/pythonprogramming.altervista.org\/sqlite-and-tkinter-in-python-part-3-3\/\",\"Sqlite3 - part 3.3\"]\r\n\t];\r\n<\/script>\r\n<script>\r\n\t\r\nif (typeof next2 != \"undefined\"){let next2 = 0;}\r\n\t\r\nnext2 = 0;\r\n\thtml = \"\";\/\/<b style='color:coral;font-size:1.2em'>Other posts about \" + title + \"<\/b><br>\";\r\nfor (address of links) \r\n{\r\n\r\n\tif (next2 == 1){\r\n\t\thtml += \"<div style='background:coral'>\";\r\n\t\thtml += \"Next link => <a href='\" + address[0] + \"'>\" + address[1] + \"<\/a>\";\r\n\t\thtml += \"<\/div><br>\";\r\n\t\tnext2 = 0;\r\n\t}\r\n\tif (address[0] == document.URL) {\r\n\t\tnext2 = 1;\r\n\t}\r\n}\r\n\r\nif (typeof next != \"undefined\") {let next = 0;}\r\nif (typeof addressStart != \"undefined\") {let addressStart = \"\";}\r\nnext = 0;\r\naddressStart = \"<a href='\";\r\nfor (address of links) {\r\n\tif (next == 1){\r\n\t\thtml += \">>>\" + addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t\tnext = 0;\r\n\t}\r\n\telse if (addressStart + address[0] != document.URL)\r\n\t{\r\n\t\thtml += addressStart + address[0] + \"'>\" + address[1] + \"<\/a><br>\";\r\n\t}\r\n\telse\r\n\t{\r\n\t\tnext = 1;\r\n\t\tnext_address = address[0]\r\n\t\tnext_title = address[1]\r\n\t\thtml += \"<span style='color:gray'>\" + address[1] + \"<\/span><br>\";\r\n\t}\r\n\r\n}\r\n\r\n\thtml += `<span style=\"font-size:8px\">Powered by <a href=\"https:\/\/pythonprogramming.altervista.org\"><img loading=\"lazy\" decoding=\"async\" class=\"alignnone size-full wp-image-2673\" src=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png\" alt=\"\" width=\"70\" height=\"25\" srcset=\"https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2.png 156w, https:\/\/pythonprogramming.altervista.org\/wp-content\/uploads\/2019\/06\/altervista2-150x56.png 150w\" sizes=\"auto, (max-width: 70px) 100vw, 70px\" \/>pythonprogramming.altervista.org<\/a><\/span>`\r\n\thtml = \"<div style='background:yellow'>\" + html + \"<\/div>\";\r\n\tdocument.write(html)\r\n<\/script>\n","protected":false},"excerpt":{"rendered":"Let&#8217;s complete our code, until now, with the 2 windows for each feature of the database. Sqlite and tkinter together with Python.\n<a class=\"moretag\" href=\"https:\/\/pythonprogramming.altervista.org\/sqlite-and-tkinter-in-python-part-3-3\/\"> [...]<\/a>","protected":false},"author":1,"featured_media":3381,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_crdt_document":"","footnotes":""},"categories":[479,481,49],"tags":[239,4,533,51],"class_list":["post-3380","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-database","category-sqlite3","category-tkinter","tag-database","tag-python","tag-sqlite","tag-tkinter"],"avopt_banners_inside_post":true,"avopt_banners_on_page":true,"av_copy_from":"","av_sharing_message":"","av_sharing_allowed":false,"av_sharing_on":{"fb":[],"tw":[]},"av_allow_affiliate_banner":false,"av_allow_affiliate_multi_banner":false,"av_show_affiliation_buy_button":false,"av_post_rating":true,"av_have_post_rating_value":false,"av_is_artificial_intelligence_content":false,"_links":{"self":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/3380","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/comments?post=3380"}],"version-history":[{"count":4,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/3380\/revisions"}],"predecessor-version":[{"id":4147,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/posts\/3380\/revisions\/4147"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/media\/3381"}],"wp:attachment":[{"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/media?parent=3380"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/categories?post=3380"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/pythonprogramming.altervista.org\/wp-json\/wp\/v2\/tags?post=3380"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}