【问题标题】:How to Show DB Query Response in Tkinter如何在 Tkinter 中显示数据库查询响应
【发布时间】:2011-03-12 19:55:15
【问题描述】:

我是 Tkinter 的新手,所以请原谅我缺乏远见。我想要完成的是:为用户提供 3 个可查询字段的文本字段、一个执行查询的提交按钮以及一种显示结果的方式。就 DB 查询而言,我完全可以使用 SQL 和 Python。不过,这方面的难点在于,我希望用户能够单击结果并为该结果触发补充查询以检索额外信息。问题是我想不出一种干净的方法来识别用户在可滚动文本框中单击的记录。

我应该使用不同的小部件而不是可滚动文本框来显示单个记录,以便当用户点击时我知道他们点击的是哪一个?你是怎么解决这个问题的?

【问题讨论】:

    标签: python sql text tkinter record


    【解决方案1】:

    假设每条记录是一行,为每一行创建一个标签(从 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()
    

    【讨论】:

      【解决方案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()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-22
        • 2021-01-09
        • 1970-01-01
        相关资源
        最近更新 更多