如何在Tkinter中显示数据库查询响应
我对Tkinter还很陌生,所以请原谅我视野有限。我想做的是:给用户提供三个可以输入查询的文本框,一个提交按钮来执行查询,还有一种方式来显示结果。关于数据库查询,我对SQL和Python都没问题。不过,比较棘手的是,我希望用户能点击某个结果,然后再执行一个额外的查询,以获取更多信息。问题是,我想不出一个好的办法来识别用户在可滚动的文本框中点击的是哪一条记录。
我是不是应该用其他的控件,而不是可滚动的文本框,来显示单独的记录,这样当用户点击时我就能知道他们点击的是哪一条?你们是怎么解决这个问题的?
相关问题:
2 个回答
2
下面是你可以用一个 Listbox 来实现的方法:
import Tkinter as tk
rows = ["A few lines", "of text", "for our example"]
def callback(event):
lb=event.widget
# http://www.pythonware.com/library/tkinter/introduction/x5453-patterns.htm
# http://www.pythonware.com/library/tkinter/introduction/x5513-methods.htm
items = lb.curselection()
try: items = map(int, items)
except ValueError: pass
idx=items[0]
print(idx,rows[idx])
root = tk.Tk()
scrollbar = tk.Scrollbar(root, orient="vertical")
lb = tk.Listbox(root, width=50, height=20,
yscrollcommand=scrollbar.set)
scrollbar.config(command=lb.yview)
scrollbar.pack(side="right", fill="y")
lb.pack(side="left",fill="both", expand=True)
for row in rows:
lb.insert("end", row)
# http://www.pythonware.com/library/tkinter/introduction/events-and-bindings.htm
lb.bind('<ButtonRelease-1>',callback)
root.mainloop()
2
假设每条记录是一行,给每一行创建一个标签(从 line_num.0 到 line_num.end)。对于每个标签,使用 text.tag_bind 并将你的标签绑定到 '<Button-1>',这样就可以检测到鼠标点击。然后在回调函数中使用一个 lambda 表达式来返回你的行号给事件处理器。
下面是一个简单的示例,正是这样做的:
from Tkinter import *
rows = ["A few lines", "of text", "for our example"]
def callback(row):
print "you picked row # %s which has this data: %s" % (row, rows[row])
rows = ["A few lines", "of text", "for our example"]
root = Tk()
t = Text(root)
t.pack()
t.insert(END, '\n'.join(rows))
for i in range(len(rows)):
line_num = i + 1 # Tkinter text counts from 1, not zero
tag_name = "tag_%s" % line_num
t.tag_add(tag_name, "%s.0" % line_num, "%s.end" % line_num)
t.tag_bind(tag_name, "<Button-1>", lambda e, row=i: callback(row))
root.mainloop()