添加到数据库并在多列表框中显示

时间:2015-05-28 20:39:31

标签: python-3.x sqlite tkinter

大家好我试图制作一个应用程序,它从一些tkinter输入框中获取数据,将它们添加到数据库中,并将它们显示在tktreectrl的多列表框中。我试图用来向数据库添加内容的代码基于各种在线教程,但所有这一切都是在数据库的最后一列中添加0。即使我使用数据库浏览器将值放入数据库,它们仍然不会显示在多列表框中。 (这是完整的代码)

#Import Modules
import tkinter
import TkTreectrl
import sqlite3
#Database
db = sqlite3.connect("marks.db")
cursor=db.cursor()
print("Opened Database")
db.execute("CREATE TABLE IF NOT EXISTS marks (Firstname, Surname, Mark)")
print("Table created")
#Variables
Surname = str()
Firstname = str()
Mark = int()
#Define Buttons
def addentry() :
   db.execute('INSERT INTO marks VALUES (?,?,?);', (Firstname,Surname,Mark))
   db.commit()
   print ("Entry Added To Database")

def deleteentry() :
   selected=listbox.get(ACTIVE)
   name=selected[0]
   db.execute('DELETE FROM marks where Firstname =?', (name))
   print ("Entry Deleted")
#Window
window = tkinter.Tk()
window.title("marks")
window.geometry("875x500")
#Labels
lbl_surname = tkinter.Label(window, text="Surname:", font="Arial 12 bold")
lbl_first = tkinter.Label(window, text="First-Name:", font="Arial 12 bold")
lbl_mark = tkinter.Label(window, text="Mark (Percentage):", font="Arial 12 bold")
#Entry
txt_surname = tkinter.Entry(window, textvariable=Surname)
txt_first = tkinter.Entry(window, textvariable=Firstname)
txt_mark = tkinter.Entry(window, textvariable=Mark)
#Button
but_save = tkinter.Button(window, text="Save", command= addentry, width=10)
but_delete = tkinter.Button(window, text="Delete", command=deleteentry, width=10)
#List
listbox = TkTreectrl.MultiListbox(window)
listbox.config(columns=('Firstname', 'Surname', ' Mark'))
cursor.execute('SELECT * from marks')
for row in cursor.fetchall():
    listbox.insert('end',*map(unicode,row))
#Grid
lbl_surname.grid(row=0, column=1, padx=100)
lbl_first.grid(row=0, column=0)
lbl_mark.grid(row=0, column=2)
txt_surname.grid(row=1, column=1, padx=110)
txt_first.grid(row=1, column=0, padx=10)
txt_mark.grid(row=1, column=2)
but_save.grid(row=0, column=3)
but_delete.grid(row=1, column=3)
listbox.grid(row=2)
#Render
window.mainloop()

任何想法 关于我做错了什么

谢谢Chris

1 个答案:

答案 0 :(得分:0)

您使用textvariable错误。该值必须是特殊的Tkinter变量,例如StringVar。第二个是你必须对这些变量使用get方法来获取值。例如:

firstNameVar = tkinter.StringVar()
...
txt_first = tkinter.Entry(..., textvariable=firstNameVar)
...
Firstname = firstNameVar.get()
...