0

我是 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()
4

1 回答 1

1

我不与 Tkinker 合作,所以我不知道如何Listbox靠近Entry,但我做了一些修改。

如果您在 Entry 中写入文本,则列表框将显示来自 db 的数据。

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

#!/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()
于 2013-11-03T17:37:19.560 回答