首页 > 解决方案 > Tkinter 输入未插入数据库(sqlite3)

问题描述

当我在 tkinter 上单击添加时,它不会在数据库中添加任何内容,我不知道 sqlite3。

我的数据库文件:

import sqlite3
from sqlite3 import *
conn = sqlite3.connect("connects.db")
print("Opened database successfully")
cursor = conn.cursor()

def createTable():
    conn.execute('''CREATE TABLE IF NOT EXISTS contactlist
             (ID INTEGER PRIMARY KEY AUTOINCREMENT,
             NAME         TEXT    NOT NULL,
             PHONE        INT     NOT NULL);''')

    print ("Table created successfully")


cursor.close()
conn.commit()
conn.close()

蟒蛇文件:

from tkinter import *
from tkinter import messagebox
import os
from DatabaseFile import *
import sqlite3

def selection () :
    print ("At %s of %d" % (select.curselection(), len(contactlist)))
    return int(select.curselection()[0])

def addContact() :
    conn = sqlite3.connect('connects.db')
    cursor = conn.cursor()
    entry = (nameVar.get(), phoneVar.get())
    try:
        def insertContact(entry):
            conn.execute('INSERT INTO contactlist (NAME, PHONE) VALUES (?,?)', (entry))
            conn.commit()
            print('record inserted in data')
    except:
        messagebox.showwarning("Field cannot be blank","Please enter a value in both the fields.")
    else:
        setList()


def updateContact() :
    contactlist[selection()]=[nameVar.get(), phoneVar.get()]
    setList ()

def deleteContact() :
    del contactlist[selection()]
    setList ()

def loadContact  () :
    name, phone = contactlist[selection()]
    nameVar.set(name)
    phoneVar.set(phone)

def saveContact  () :
    fobj = open("contacts.py", "w")
    fobj.write("contactlist = [")
    for items in contactlist:
        fobj.write(str(items))
        fobj.write(",")
        fobj.write("\n")
    fobj.write("]")

def exitContact  () :
    app_title = "Contacts"
    if (messagebox.askokcancel(title = app_title, \
        message = "Do you want to exit, OK or Cancel") == 1) :
        os._exit(1)

def buildFrame () :
    global nameVar, phoneVar, select
    root = Tk()
    root.title('My Contact List')

    frame1 = Frame(root)
    frame1.pack()

    Label(frame1, text="Name:").grid(row=0, column=0, sticky=W)
    nameVar = StringVar()
    name = Entry(frame1, textvariable=nameVar)
    name.grid(row=0, column=1, sticky=W)

    Label(frame1, text="Phone:").grid(row=1, column=0, sticky=W)
    phoneVar= StringVar()
    phone= Entry(frame1, textvariable=phoneVar)
    phone.grid(row=1, column=1, sticky=W)

    frame1 = Frame(root)       # add a row of buttons
    frame1.pack()
    btn1 = Button(frame1,text=" Add  ",command=addContact)
    btn2 = Button(frame1,text="Update",command=updateContact)
    btn3 = Button(frame1,text="Delete",command=deleteContact)
    btn4 = Button(frame1,text=" Load ",command=loadContact)
    btn5 = Button(frame1,text=" save ",command=saveContact)
    btn6 = Button(frame1,text=" exit ",command=exitContact)
    btn1.pack(side=LEFT); btn2.pack(side=LEFT)
    btn3.pack(side=LEFT); btn4.pack(side=LEFT)
    btn5.pack(side=LEFT); btn6.pack(side=RIGHT)

    frame1 = Frame(root)       # allow for selection of names
    frame1.pack()
    scroll = Scrollbar(frame1, orient=VERTICAL)
    select = Listbox(frame1, yscrollcommand=scroll.set, height=7)
    scroll.config (command=select.yview)
    scroll.pack(side=RIGHT, fill=Y)
    select.pack(side=LEFT,  fill=BOTH)
    return root

def setList() :
    global contacts
    contacts = readContacts()
    # sort the list
    contacts.sort(key = lambda x : x[1])
    # delete all elements from the select element
    select.delete(0, END)
    # insert each name from the list to the end of the              # select
        # element
    for id, name, phone in contacts :
        select.insert(END, name)

def readContacts():
    contactlistss = []
    cursor.execute("SELECT * FROM contactlist")
    rows = cursor.fetchall()
    for row in rows:
        contactlistss = row
    return contactlistss



# the main program
# initialize the application by building the GUI elements
root = buildFrame()
# initialize the database
createTable()
# set the contents of the list initially
setList()
to keep the program from exiting
root.mainloop()
# end of program

单击 tkinter 上的添加按钮时,它给了我空白输出,这意味着它没有在数据库中插入任何内容

标签: pythonsqlitetkinter

解决方案


try/except您内部定义def insertContact(entry):但您从不执行此功能。但是你可以直接把代码try/excet

try:
    conn.execute('INSERT INTO contactlist (NAME, PHONE) VALUES (?,?)', (entry))
    conn.commit()
    print('record inserted in data')
except Exceptiona as ex:
    print('Ex:', ex)
    messagebox.showwarning("Field cannot be blank","Please enter a value in both the fields.")
else:
    setList()

顺便说一句:我检查了所有代码并且有我的更改。并非所有工作都有效 - 即。Update有问题。

我将所有查询移到DatabaseFile.py并且只打开一次数据库,直到程序结束才关闭它。

lower_case_names用于函数和变量。请参阅:PEP 8 -- Python 代码样式指南

我删除了import *- 另请参阅PEP 8 -- Python 代码的样式指南


数据库文件.py

import sqlite3


conn = None # default value at start 


def open():
    global conn

    conn = sqlite3.connect("connects.db")
    print("Opened database successfully")


def close():
    if conn is not None:
        conn.close()


def create_table():
    cursor = conn.cursor()

    cursor.execute('''CREATE TABLE IF NOT EXISTS contactlist
        (ID INTEGER PRIMARY KEY AUTOINCREMENT,
         NAME         TEXT    NOT NULL,
         PHONE        INT     NOT NULL);''')

    conn.commit()

    print("Table created successfully")


def read_contacts():
    cursor = conn.cursor()

    cursor.execute("SELECT * FROM contactlist ORDER BY id")

    return cursor.fetchall()


def add_contact(name, phone):
    cursor = conn.cursor()

    cursor.execute('INSERT INTO contactlist (NAME, PHONE) VALUES (?,?)', (name, phone))

    conn.commit()

    print('record inserted in data')

主文件

import os
import tkinter as tk
from tkinter import messagebox
import DatabaseFile as db

def selection():
    print("At %s of %d" % (select.curselection(), len(contacts)))
    return int(select.curselection()[0])

def add_contact():
    try:
        db.add_contact(name_var.get(), phone_var.get())
    except Exception as ex:
        print('Ex:', ex)
        messagebox.showwarning("Field cannot be blank", "Please enter a value in both the fields.")
    else:
        set_list()

def update_contact():
    contacts[selection()] = [name_var.get(), phone_var.get()]
    set_list()

def delete_contact():
    del contacts[selection()]
    setList()

def load_contact():
    _, name, phone = contacts[selection()]
    name_var.set(name)
    phone_var.set(phone)

def save_contact():
    fobj = open("contacts.py", "w")
    fobj.write("contactlist = [")
    for items in contacts:
        fobj.write(str(items))
        fobj.write(",")
        fobj.write("\n")
    fobj.write("]")

def exit_contact():
    result = messagebox.askokcancel(title="Contacts", message="Do you want to exit, OK or Cancel")
    if result == 1:
        exit(1)

def build_frame():
    global name_var
    global phone_var
    global select

    root = tk.Tk()
    root.title('My Contact List')

    # ---

    frame_form = tk.Frame(root)
    frame_form.pack()

    tk.Label(frame_form, text="Name:").grid(row=0, column=0, sticky='w')

    name_var = tk.StringVar()
    name = tk.Entry(frame_form, textvariable=name_var)
    name.grid(row=0, column=1, sticky='w')

    tk.Label(frame_form, text="Phone:").grid(row=1, column=0, sticky='w')

    phone_var = tk.StringVar()
    phone = tk.Entry(frame_form, textvariable=phone_var)
    phone.grid(row=1, column=1, sticky='w')

    # ---

    frame_buttons = tk.Frame(root)
    frame_buttons.pack()

    btn1 = tk.Button(frame_buttons, text=" Add  ", command=add_contact)
    btn2 = tk.Button(frame_buttons, text="Update", command=update_contact)
    btn3 = tk.Button(frame_buttons, text="Delete", command=delete_contact)
    btn4 = tk.Button(frame_buttons, text=" Load ", command=load_contact)
    btn5 = tk.Button(frame_buttons, text=" Save ", command=save_contact)
    btn6 = tk.Button(frame_buttons, text=" Exit ", command=exit_contact)
    btn1.pack(side='left') 
    btn2.pack(side='left')
    btn3.pack(side='left') 
    btn4.pack(side='left')
    btn5.pack(side='left')
    btn6.pack(side='right')

    # ---

    frame_list = tk.Frame(root)
    frame_list.pack()

    scroll = tk.Scrollbar(frame_list, orient='vertical')
    select = tk.Listbox(frame_list, yscrollcommand=scroll.set, height=7)
    scroll.config(command=select.yview)
    scroll.pack(side='right', fill='y')
    select.pack(side='left', fill='both')

    return root

def set_list() :
    global contacts

    contacts = db.read_contacts()

    select.delete(0, 'end')

    #for item in contacts:
    #    select.insert('end', item)

    select.insert('end', *contacts) # need star *  to insert all items at once

# --- main ---

contacts = [] # default value at start

# ---

db.open() # open once before program
db.create_table()

root = build_frame()

set_list()

root.mainloop()

db.close() # close after closing program

推荐阅读