开发者

How to Show DB Query Response in Tkinter

I'm a really rookie to Tkinter so excuse my lack of vision here. What I'm trying to accomplish is the following: give the user 3 text fields that are queryable fields, a submit button to execute the query, and a way to display the results. As far as the DB query goes, I'm totally fine with SQL and Python. The hard part about this though, is that I want the user to be able to click a result and have a supplementary query get fired for that result to retrieve extra information. The problem is that I can't think of a clean way to identify which record the user is cli开发者_JAVA技巧cking in a scrollable text box.

Is there a different widget I should be using instead of a scrollableText box to display individual records so that when the user clicks I know which one they clicked on? How have you solved this problem?


Assuming each record is one line, create a tag for each line (from line_num.0 to line_num.end). For each tag, use text.tag_bind and bind your tag to '<Button-1>' to detect mouse click. Use a lambda in the callback to return your row number to the event handler.

Here's a toy example that does just that:

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


Here's how you could do it with a 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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜