gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:29:36 25 4
gpt4 key购买 nike

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

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

#-*- 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 附近,但我做了一些修改。

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

如果您从 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()

关于mysql - 使用 Python 在 MySQL 数据库上进行实时搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19652763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com