Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
185 views
in Technique[技术] by (71.8m points)

python - tkinter returning all database columns in one column

I am trying to use tkinter to display information from a MongoDB database. However all of the different db columns are being returned in a single column rather than the correct db column. The column headings are displayed correctly and all of the data is there when I expand the column it is displayed in. Here is the relevant code:

    columns = list(df.columns.values)
    tree = ttk.Treeview(window, columns=columns, show='headings')
    for column in columns:
        tree.heading(column, text=column)
    for row in rows:
        tree.insert("", tk.end, values=row)

If I change the insert line to this I then get the column headings being displayed recursively in each column but no actual row data:

    tree.insert("", tk.END, values=list(row))

I have looked and looked but cant work out what I am doing wrong and most examples don't involve getting data from a MongoDB database.

If I change the code to this below and miss out the database connection this works fine:

    columns = ('BUSINESS ID', 'BUSINESS NAME', 'ORDERS')
    tree = ttk.Treeview(window, columns=columns, show='headings')
    for column in columns:
        tree.heading(column, text=column)
    rows = []
    for n in range(1, 100):
        rows.append((f'id {n}', f'name {n}', f'orders {n}'))
    for row in rows:
        tree.insert('', tk.END, values=row)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Since rows looks like a list of dict, therefore you need to insert the values of each row (a dict item) using list(row.values()):

for row in rows:
    tree.insert("", tk.END, values=list(row.values()))

As your code have a dataframe df, you can use it as below:

for _, row in df.iterrows():
    tree.insert("", tk.END, values=list(row.values))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...