初始化数据库后,第一次加载时无法在“输入”框中输入输入吗?

时间:2019-01-31 08:04:33

标签: python sql python-3.x sqlite tkinter

我用tkinker编写了一个Python GUI程序,该程序将从文本文件中读取行到数据库中。通过将详细信息输入到GUI输入框并按下按钮,用户可以在数据库中添加或删除条目。但是,当我运行代码时,第一次尝试时无法在“输入”框中键入任何内容,即该框牢固,不能键入任何内容。

import tkinter as tk
import tkinter.ttk as ttk
from tkinter import StringVar
from tkinter import messagebox
import sqlite3
import os

window = tk.Tk() 

#Food Name label
labelName=ttk.Label(window,text="Name")
txtName=StringVar()
textName=ttk.Entry(window,textvariable=txtName)

#Food Category label
labelCategory=ttk.Label(window,text="Category")
txtCategory=StringVar()
textCategory=ttk.Entry(window,textvariable=txtCategory)

#Initialize Database
def initDatabase():
    file=open("foodList.txt")
    lines=file.readlines()

    conn=sqlite3.connect('foodDatabase.db')
    sql="create table food(name text primary key, category text)"
    conn.execute(sql)
    conn.commit()

    for line in lines:
        line=line.replace("\n","")
        cols=line.split(",")
        name=cols[0]
        category=cols[1]
        sql="insert into food(name,category) values(?,?)"
        conn.execute(sql,(name,category))

    conn.commit()
    conn.close()
    messagebox.showinfo("Success", "Database Initialized!")

if not os.path.exists("foodDatabase.db"): 
    initDatabase()

#Buttons for Insert & Delete
def insertData():
    conn=sqlite3.connect('foodDatabase.db')
    sql="insert into food(name,category) values(?,?)"
    conn.execute(sql,(txtName.get(),txtCategory.get()))
    conn.commit()
    conn.close()
    messagebox.showinfo("Success", "Insert Successful!")

def deleteData(name):
    conn=sqlite3.connect('foodDatabase.db')
    sql="delete from food where name=?"
    conn.execute(sql,(txtName.get(),))
    conn.commit()
    conn.close()
    messagebox.showinfo("Success","Delete Successful!")

#Insert BUtton
buttonInsert=ttk.Button(window,text='Insert',command=insertData)

#Delete Button
buttonDelete=ttk.Button(window,text='Delete',command=deleteData)

window.mainloop()

1 个答案:

答案 0 :(得分:0)

ttk.Label应该是tk.Label。

我提供了一个基于您的工作示例:

from tkinter import *
from tkinter.messagebox import showinfo
import sqlite3
import os


#Initialize Database
def initDatabase():
    file=open("foodList.txt")
    lines=file.readlines()

    conn=sqlite3.connect('foodDatabase.db')
    sql="create table food(name text primary key, category text)"
    conn.execute(sql)
    conn.commit()

    for line in lines:
        line=line.replace("\n","")
        cols=line.split(",")
        name=cols[0]
        category=cols[1]
        sql="insert into food(name,category) values('{0}','{1}')".format(name,category)
        conn.execute(sql)

    conn.commit()
    conn.close()
    showinfo("Success", "Database Initialized!")

def main():
    window = Tk() 

    window.title("Welcome to test app")
    # window.geometry('350x200')

    if not os.path.exists("foodDatabase.db"): 
        initDatabase()

    #Food Name label
    nombre = StringVar()
    labelName=Label(window,text="Name").grid(row=0)
    textName=Entry(window,textvariable=nombre).grid(row=0, column=1)

    #Food Category label
    categoria = StringVar()
    labelCategory=Label(window,text="Category").grid(row=1)
    textCategory=Entry(window, textvariable=categoria).grid(row=1, column=1)

    res_name = StringVar()
    res_category = StringVar()
    textRes_name = Label(window, textvariable=res_name).grid(row=5,column=0)
    textRes_category = Label(window, textvariable=res_category).grid(row=5,column=1)


    #Buttons for Insert & Delete
    def insertData():
        conn=sqlite3.connect('foodDatabase.db')
        sql="insert into food(name,category) values('{0}','{1}')".format(nombre.get(),categoria.get())
        conn.execute(sql)
        conn.commit()
        conn.close()
        showinfo("Success", "Insert Successful!")
        nombre.set('')
        categoria.set('')
        showData()

    def deleteData():
        conn=sqlite3.connect('foodDatabase.db')
        sql="delete from food where name='{0}'".format(nombre.get())
        conn.execute(sql)
        conn.commit()
        conn.close()
        showinfo("Success","Delete Successful!")
        nombre.set('')
        categoria.set('')
        showData()

    def showData():
        conn=sqlite3.connect('foodDatabase.db')
        sql="select * from food"
        q = conn.execute(sql)
        rows = q.fetchall()

        result_name = ["name"]
        result_category = ["category"]
        for row in rows:
            result_name.append(row[0])
            result_category.append(row[1])

        res_name.set("\n".join(result_name))
        res_category.set("\n".join(result_category))


        conn.commit()
        conn.close()

    #Insert Button
    buttonInsert = Button(window,text='Insert',command=insertData).grid(row=3, column=0, pady=4)

    #Delete Button
    buttonDelete = Button(window,text='Delete',command=deleteData).grid(row=3, column=1, pady=4)

    #Show list Button
    # buttonShow = Button(window,text='Show',command=showData).grid(row=3, column=2, pady=4)
    showData()
    window.mainloop()

if __name__ == '__main__':
    main()