【问题标题】:Tkinter entry outputTkinter 入口输出
【发布时间】:2020-08-22 06:53:39
【问题描述】:

我正在使用 db 文件创建数据查找器,并且使用 tkinter 条目。但是在控制台中它返回输出[] 并且代码是这样的

import sqlite3
import tkinter

db = sqlite3.connect ('covidjakartadb.db')

window = tkinter.Tk()
window.geometry("500x300")

label = tkinter.Label(window, text="Please enter a area")
label.pack()

entry = tkinter.Entry(window)
entry.pack()

select_all = "SELECT * FROM locations WHERE '%{0}%'".format(entry)

cursor = sqlite3.Cursor(db)

cursor.execute(select_all)

def Search_Completed():
    label = tkinter.Label(window,  text="aaaaa")

Button = tkinter.Button(window, text="Search data", command=Search_Completed)
Button.pack()



positive = cursor.fetchall()

print (positive)

window.mainloop()

这个项目今天到期,所以今天的答案会很棒

【问题讨论】:

  • 由于我没有您的数据库,因此很难重现,但从代码中我会说数据库正在从您的查询中返回“[]”。您是否尝试过手动查询数据库?
  • 您的 SQL 语句中的 WHERE 子句无效。它应该类似于"SELECT * FROM locations WHERE field_name LIKE '%{0}%'".format(entry.get())。将field_name 替换为您要使用的实际字段。
  • @figbeam 是的,我试过了,但还是不行

标签: python sqlite tkinter


【解决方案1】:

要从数据库中选择的代码需要在search_completed 函数中。正如所写,它在 GUI 甚至打开之前运行。

搜索应该使用条目的内容,entry.get() 而不是entry。

import sqlite3
import tkinter

db = sqlite3.connect ('covidjakartadb.db')

window = tkinter.Tk()
window.geometry("500x300")

label = tkinter.Label(window, text="Please enter a area")
label.pack()

entry = tkinter.Entry(window)
entry.pack()

def Search_Completed():
    # select_all = "SELECT * FROM locations WHERE '%{0}%'".format(entry)
    # select_all = "SELECT * FROM locations WHERE '%{0}%'".format( entry.get() )
    # This will work
    select_all = "SELECT * FROM locations WHERE City LIKE '%{0}%'".format( entry.get() )        
    # Or this.
    # select_all = "SELECT * FROM locations WHERE City == '{0}'".format( entry.get() )
    cursor = sqlite3.Cursor(db)
    cursor.execute(select_all)
    positive = cursor.fetchall()
    print (positive)
    label = tkinter.Label(window,  text="aaaaa")

Button = tkinter.Button(window, text="Search data", command=Search_Completed)
Button.pack()
window.mainloop()

我无法测试代码,因为我没有数据库,所以这可能有一些错误。

【讨论】:

  • 我会在 cursor = 之前打印 select_all 以确保查询是您所期望的。
  • 谢谢!但我想通过在条目中输入城市名称来搜索它的数据,它会提取我将提供 db 文件的所有数据
  • 当前生成的 sql 语句是“SELECT * FROM locations WHERE '%Jakarta%'”它需要是“... City LIKE '%Jakarta%'”或“... City = ='雅加达'”。 LIKE 会将“Jak”与 Jakarta 匹配。 == 仅在拼写完美时才匹配。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 2015-12-30
  • 1970-01-01
  • 2016-06-10
  • 2022-08-16
  • 1970-01-01
相关资源
最近更新 更多