You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中SQLite数据输出至TextBox的顺序调整及插入位置问题

Fixing TextBox Append Order for SQLite Query Results

The issue here is straightforward: when you use self.text.insert(0.0, ...), you’re telling the Tkinter Text widget to add each new row at the very beginning of the text box. That’s why your results show up in reverse order—each new row pushes the previous ones down.

The Simple Fix: Append to the End Instead

Instead of inserting at position 0.0, use the special keyword "end" (or "1.end"—they’re equivalent for this purpose) to add each row to the bottom of the TextBox. Also, it’s a good idea to format each row into a readable string (with a newline) so entries don’t run together.

Here’s your corrected function:

def favorite_store(self):
    self.text.delete("1.0", "end")
    cursor = con.execute("""SELECT lastName, firstName FROM person JOIN stores ON (favoriteStore = stores.storeID) where storeName = 'Total Wine'""")
    for row in cursor:
        # Format the row into a readable string with a newline
        entry = f"{row[1]} {row[0]}\n"  # First name followed by last, adjust as needed
        self.text.insert("end", entry)
    # Keep any additional code (like self.text.i...) here as originally intended

Why This Works:

  • "end" always refers to the current end of the Text widget’s content, so each new row gets added after the last one, preserving the exact order from your SQLite query.
  • Adding a \n at the end of each entry ensures each person’s name appears on its own line, making the output far easier to read.

Alternative (If You Really Need to Insert at the Start):

If for some reason you want to keep inserting at the top but maintain the correct order, you could reverse the cursor results first. Note this is less efficient than just appending to the end, but here’s how it would look:

def favorite_store(self):
    self.text.delete("1.0", "end")
    cursor = con.execute("""SELECT lastName, firstName FROM person JOIN stores ON (favoriteStore = stores.storeID) where storeName = 'Total Wine'""")
    # Reverse the rows before iterating to preserve query order when inserting at start
    for row in reversed(list(cursor)):
        entry = f"{row[1]} {row[0]}\n"
        self.text.insert(0.0, entry)

内容的提问来源于stack exchange,提问作者James Lockhart

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:22:14