使用 Python 在 MySQL 数据库上进行实时搜索



我是Python的新手,正在开发一个简单的桌面应用程序来从MySQL数据库读取记录。我需要通过 mysql db 使用 tkinter 条目进行实时搜索。当用户按下键盘键时,应生成一个自动建议列表,其中包含自动选项供您选择...

目前,下面的代码不起作用。怎么了?

#-*- coding: utf-8 -*-
import Tkinter
from Tkinter import *
import MySQLdb
top = Tkinter.Tk()
top.minsize(300,300)
top.geometry("500x500")
# here we make  text input field
E1 = Entry(top, bd =2)
E1.pack(side = RIGHT)
Lb1 = Listbox(  E1)      # here the list generated from entry but covering it completely is bad ?? 

def clickme(x):
  txtt=E1.get()
  txt=txtt+"%"  
#connection
  db = MySQLdb.connect("127.0.0.1","root","123456","test2",use_unicode=True, charset="utf8"  )
  if db:print"connected"
  cursor=db.cursor()
  cursor.execute("SELECT name FROM `table` WHERE name LIKE '%s' " % (txt))
#------------
  res=cursor.fetchall() 
  i=0
  for query in res: 
    i+=1
    lngth=len(query[0])
    u=query[0].encode('utf-8')
    Lb1.delete (0,lngth)
    if len(txtt)>0:
      Lb1.insert(i, u)
      Lb1.pack()
    else:
        Lb1.delete (0,lngth)
        Lb1.pack_forget()
top.bind("<Key>", clickme)
top.mainloop()

我不使用 Tkinker,所以我不知道如何将Listbox放在Entry附近,但我做了一些修改。

如果在条目中写入文本,则列表框将显示来自数据库的数据。

如果从条目中删除文本,则列表框将隐藏。

#!/usr/bin/python
#-*- coding: utf-8 -*-
import Tkinter
from Tkinter import *
import MySQLdb
#----------------------------------------------------------------------
class MainWindow():
    def __init__(self, root):
        frame = Frame(root, width=500, height=500)
        #root.minsize(300,300)
        frame.pack()

        # here we make  text input field
        self.E1 = Entry(frame, bd=2)
        self.E1.pack(side=TOP)
        # here the list generated from entry but covering it completely is bad ?? 
        self.Lb1 = Listbox(frame, bd=2)
        #Lb1.pack(side=BOTTOM)
        root.bind("<Key>", self.clickme)
        # open database (only once) at start program
        self.db = MySQLdb.connect("127.0.0.1", "root", "password", "test", use_unicode=True, charset="utf8")
    #-------------------
    def __del__(self): 
        # close database on exit
        self.db.close()
    #-------------------
    def clickme(self, x):
        txt = self.E1.get()
        self.Lb1.delete(0, END) # delete all on list
        if txt == '':
            self.Lb1.pack_forget() # hide list
        else:
            self.Lb1.pack(side=BOTTOM) # show list
            txt_for_query = txt + "%"  
            cursor = self.db.cursor()
            cursor.execute("SELECT name FROM `table` WHERE name LIKE '%s'" % (txt_for_query))
            res = cursor.fetchall() 
            for line in res: 
                self.Lb1.insert(END, line[0].encode('utf-8')) # append list
            cursor.close()
#----------------------------------------------------------------------
root = Tk()
MainWindow(root)
root.mainloop()

相关内容

  • 没有找到相关文章

最新更新