我有错误" TypeError:' type'对象不是可订阅的"

时间:2017-08-22 08:26:15

标签: python ms-access tkinter pypyodbc

我想通过以tkinter的形式写入数据来向Access添加数据,但我有一个错误。怎么了?我试图改变con.close ()的位置,但它没有帮助,如果我把它放在def之前,我甚至会犯另一个错误

from tkinter import *
import pypyodbc
import ctypes

form=Tk ()
form.title ("Add data")
form.geometry ('400x200')

#Create connection
con = pypyodbc.connect('DRIVER={Microsoft Access Driver (*.mdb)};UID=admin;UserCommitSync=Yes;Threads=3;SafeTransactions=0;PageTimeout=5;MaxScanRows=8;MaxBufferSize=2048;FIL={MS Access};DriverId=25;DefaultDir=C:/Users/HP/Desktop/PITL;DBQ=C:/Users/HP/Desktop/PITL/PITL.mdb;')
cursor = con.cursor ()

a = Entry (form, width=20, font="Arial 16")
a.pack ()
b = Entry (form, width=20, font="Arial 16")
b.pack ()

def Add (event):
    cursor.execute ("INSERT INTO Crime (`Number_of_article`, `ID_of_criminal`) VALUES (?, ?)", (a, b))

Button=Button(form, text = 'PUSH ME')
Button.pack ()
Button.bind ('<Button-1>', Add)

form.mainloop ()

con.commit ()
cursor.close ()
con.close ()

错误是:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:\Users\HP\Desktop\PITL\ADD DATA.py", line 19, in Add
    cursor.execute ("INSERT INTO Crime (`Number_of_article`, `ID_of_criminal`) VALUES (?, ?)", (a, b))
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypyodbc-1.3.4-py3.6.egg\pypyodbc.py", line 1491, in execute
    self._BindParams(param_types)
  File "C:\Users\HP\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pypyodbc-1.3.4-py3.6.egg\pypyodbc.py", line 1296, in _BindParams
    if param_types[col_num][0] == 'u':
TypeError: 'type' object is not subscriptable

1 个答案:

答案 0 :(得分:-1)

假设您的SQL输入正在运行,那么tkinter方面并不太棘手。

首先,在class内执行此操作可能更容易,使变量传递更容易。

您也不需要绑定到button,而是可以为其添加command属性。

请参阅下面的代码示例:

from tkinter import *

class App:
    def __init__(self, root):
        self.root = root
        #create our entry boxes
        self.entry1 = Entry(self.root)
        self.entry2 = Entry(self.root)
        #create out button, instead of binding we associate a command to it
        self.button = Button(self.root, text="Insert", command=self.command)
        #pack our objects
        self.entry1.pack()
        self.entry2.pack()
        self.button.pack()
    def command(self):
        #this command outputs the results of the two entry boxes
        #so this is where you'd implement your database entry
        print("Insert "+self.entry1.get()+" & "+self.entry2.get())
        #above, *object*.get() is used to return the value of the object rather than the object itself

root = Tk()
App(root)
root.mainloop()