2013-10-29 50 views
0

我是Python新手,正在研究簡單的桌面應用程序以從MySQL數據庫中讀取記錄。我需要通過mysql數據庫使用tkinter條目進行實時搜索。當用戶敲擊鍵盤按鍵時,應使用自動完成選項生成自動建議列表以供選擇...在Python上使用Python進行實時搜索分貝

目前下面的代碼不起作用。哪裏不對?

#-*- 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() 

回答

0

我不Tkinker工作,所以我不知道如何把Listbox附近Entry,但我做了一些修改。

如果您在Entry中編寫文本,則Listbox將顯示來自db的數據。

如果您從Entry中刪除文本,則Listbox將隱藏。

#!/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()