我无法解决Tkinter数据库(sqlite3)中的搜索查询问题。我的部分代码:
front.py
# Entries self.name_text = tk.StringVar() self.entry_name = tk.Entry(self.parent, textvariable=self.name_text) self.entry_name.grid(row=3, column=1) self.color_text = tk.StringVar() self.combobox2=ttk.Combobox(self.parent, textvariable=self.color_text) self.combobox2["values"] = ('red','blue','white') self.labelCombobox=ttk.Label(self.parent, textvariable=self.color_text) self.combobox2.grid(row=4, column=1) self.parent.bind('<Return>',lambda e:refresh()) def search_command(self): self.listBox.delete(0,tk.END) for row in backend.database.search(self.name_text.get(),self.color_text.get()): self.listBox.insert(tk.END, row)
backend.py类数据库:
def search(name="",color=""): try: connect = sqlite3.connect("color.db") cur = connect.cursor() sql = "SELECT * FROM color WHERE name=? OR color=?" values = (self, name_text.get(), color_text.get()) cur.execute(sql, values) rows = cur.fetchall() name_text.set(rows[1]) color_text.set(rows[2]) entry_name.configure('disabled') combobox2.configure('disabled') connect.close() except: messagebox.showinfo('nothing found!')
我还试图将自己放入另一个版本的backend.py中。这给出了相同的错误。
def search(self, name="",color=""): try: self.connect = sqlite3.connect("color.db") self.cur = self.connect.cursor() self.sql = "SELECT * FROM color WHERE name=? OR color=?" self.values = (self, name_text.get(), color_text.get()) self.cur.execute(sql, values) self.rows = self.cur.fetchall() self.name_text.set(rows[1]) self.color_text.set(rows[2]) self.entry_name.configure('disabled') self.combobox2.configure('disabled') self.connect.close() except: messagebox.showinfo('nothing!')
请帮助解决错误:
对于backend.database.search(self.name_text.get(),self.color_text.get())中的行:TypeError:“ NoneType”对象不可迭代
错误TypeError: 'NoneType' object is not iterable
表示您的查询未返回任何行。
至少部分是因为此代码:
sql = "SELECT * FROM color WHERE name=? OR color=?"
values = (self, name_text.get(), color_text.get())
cur.execute(sql, values)
[这导致self
用于name
参数,并且name_text.get()
的结果将与color
属性相关联。 color_text.get()
的结果将被忽略。
您需要删除self
-您的SQL使用两个参数,因此您需要向其发送两个参数。
另一个问题似乎是您要遍历search
的结果,但是search
不返回任何内容。您需要在return
函数中添加search
语句。
backend.database.search()
功能上的问题很少:
name_text
和color_text
未定义name
中使用传递的参数color
和values
下面是修改后的search()
函数:
def search(name="", color=""):
rows = () # assume no result in case of exception
try:
connect = sqlite3.connect("color.db")
cur = connect.cursor()
sql = "SELECT * FROM color WHERE name=? OR color=?"
values = (name, color) # use arguments name and color instead
cur.execute(sql, values)
rows = cur.fetchall()
connect.close()
except Exception as e:
print(e) # better to see what is wrong
messagebox.showinfo('nothing found!')
return rows # return result