【问题标题】:The Tkinter input is not inserting into database (sqlite3)Tkinter 输入未插入数据库(sqlite3)
【发布时间】:2019-11-30 18:13:42
【问题描述】:

当我在 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()

Python 文件:

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 上的添加按钮时,它给了我空白输出,这意味着它没有在数据库中插入任何东西

【问题讨论】:

  • 请尝试制作一个minimal的代码示例。这将对我们有所帮助,也许您可​​以自己找到解决方案。你也可以看看How to debug a program
  • 只需要关于 addContact() 函数的帮助,它不向数据库输入任何输入
  • 您是否收到错误消息?您应该始终使用 except Exception as ex: print(ex) 来查看您遇到了什么异常 - 这样您就可以看到可能是什么问题。
  • 您有问题,因为您定义了函数def insertContact(entry):,但您从未运行它。不知道你为什么要定义这个函数——你应该直接把代码放在try/except

标签: python sqlite tkinter


【解决方案1】:

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 -- Style Guide for Python Code

我删除了import * - 另见PEP 8 -- Style Guide for Python Code


数据库文件.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')

main.py

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

【讨论】:

  • 它仍然给我错误打开数据库成功回溯(最近一次调用最后):文件“C:\TKcontacts.py”,第 119 行,在 createTable() 文件“C:\\ DatabaseFile.py",第 11 行,在 createTable PHONE INT NOT NULL);''') sqlite3.ProgrammingError: 无法对已关闭的数据库进行操作。
  • 现在您遇到了不同的问题,您应该使用新的描述和完整的错误消息创建新问题。
  • 您的问题是在DatabaseFile.py 内部您打开了连接,并且您还在函数外部关闭了它,以便在您导入它时执行它们。因此,当您导入此文件时关闭连接,稍后createTable() 与数据库没有连接。您应该在 createTable() 中打开和关闭数据库
  • 它仍然不起作用;在打开连接并在函数内部关闭后仍无法正常工作
  • 您是否从DatabaseFile.py 中删除了其他conn.close()
猜你喜欢
  • 1970-01-01
  • 2011-12-21
  • 2021-08-05
  • 2017-02-10
  • 2013-10-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-24
相关资源
最近更新 更多