Reputation: 111
I'm trying to work on a Tkinter GUI with a backed sqlite3 database. I want to control the database with Buttons on my Tkinter window. Also I'm figuring out, how to improve my code while using classes. However, if I'm pressing the button "create database" no table is inserted into the database.
Following my code:
import sqlite3
import datetime
import os.path
import tkinter as tk
from tkinter import *
from tkinter import messagebox
from tkinter.ttk import Treeview, Separator
class MainApplication():
def __init__(self, master):
self.master = master
self.frame = tk.Frame(self.master)
self.master.title('Titanic DB')
self.master.geometry('850x600')
self.master.resizable(False, False)
self.search_frame = tk.Frame(self.master).grid(row=0, column=0)
self.label_search_heading = tk.Label(self.search_frame, text='DATABASE |', font=('bold', 14), pady=10).grid(row=0, column=0, sticky=W)
self.button_create_database = tk.Button(self.search_frame, text='create database', command=self.ActionButtons, font=('bold', 14), pady=5, padx=50).grid(row=20, column=0, sticky=W)
def ActionButtons(self):
self.db = Database()
self.createDB = self.db.CreateDatabase
class Database():
DATABASE = "TitanicPassengers.db"
def __init__(self):
self.connection = sqlite3.connect(Database.DATABASE)
self.cursor = self.connection.cursor()
def CreateDatabase(self):
self.connection = sqlite3.connect(Database.DATABASE)
self.cursor = self.connection.cursor()
self.execute("CREATE TABLE IF NOT EXISTS Passengers(Survived INTEGER, " \
"PClass INTEGER, " \
"Name TEXT, " \
"Sex TEXT, " \
"Age INTEGER, " \
"SiblingsSpousesAbord INTEGER, " \
"ParentsChildrenAbord INTEGER, " \
"Fare REAL ) "
)
self.connection.commit()
self.connection.close()
def main():
root = tk.Tk()
app = MainApplication(root)
root.mainloop()
if __name__ == '__main__':
main()
I would be glad, if someone could give me a hint, what I'm doing wrong. All additional tips how to organize my code better, are highly appreciated. Thanks!
Upvotes: 1
Views: 660
Reputation: 149
I believe that
self.execute("CREATE TABLE IF NOT EXISTS...etc
should be
self.cursor.execute..
is not it?
Upvotes: 0
Reputation: 111
Well, I figured it out by myself.
I changed
self.createDB = self.db.CreateDatabase
to
self.db.CreateDatabase()
Nevermind, all tips for a better code structure are helpful.
Thanks!
Upvotes: 1