0

Here i have a code and i want to have different column width to different columns,is there a way to do this? Here the width is 120 but i dont want all columns to have 120 width jus a specific column and i want others columns to have different wdith? Any suggestion? Thanks in advance :)

Code :

def all_logs():
    log = Toplevel(root)
    log.transient(root)
    log.title('View all Visitors')

    # setup treeview
    columns = ('ID', 'S_ID', 'S_NAME', 'B_NAME', 'Date_Taken', 'Due_Date','Date_Returned', 'Status')
    tree = ttk.Treeview(log, height=20, columns=columns, show='headings')
    tree.grid(row=0, column=0, sticky='news')

    # setup columns attributes
    for col in columns:
        tree.heading(col, text=col)
        tree.column(col, width=120, anchor=tk.CENTER)

    # fetch data
    con = mysql.connect(host='localhost', user='root', password='*****', database='DB')
    c = con.cursor()
    c.execute('SELECT * FROM library')
    

    # populate data to treeview
    for rec in c:
        tree.insert('', 'end', value=rec)

    # scrollbar
    sb = tk.Scrollbar(log, orient=tk.VERTICAL, command=tree.yview)
    sb.grid(row=0, column=1, sticky='ns')
    tree.config(yscrollcommand=sb.set)
    a = tree.item(tree.focus())['values']

    btn = tk.Button(log, text='Close', command=log.destroy, width=20, bd=2, fg='red')
    btn.grid(row=1, column=0, columnspan=2)
    con.close()
2
  • You can use columns = (('ID', 100), ...) instead. Then update the for loop to cater the change. Commented May 19, 2020 at 23:42
  • u mean tht i vl have to edit this part out? for col in columns: tree.heading(col, text=col) tree.column(col, width=120, anchor=tk.CENTER) ? or something else? could you be give a code to it? Commented May 20, 2020 at 3:39

1 Answer 1

1

You can put the required widths alongside with the column names:

columns = (
    ('ID', 50),
    ('S_ID', 50),
    ('S_NAME', 120),
    ('B_NAME', 120),
    ('Date_Taken', 100),
    ('Due_Date', 100),
    ('Date_Returned', 100),
    ('Status', 50),
)

Then you need to extract the column names when creating the treeview:

tree = ttk.Treeview(log, height=20, columns=[x[0] for x in columns], show='headings')

And configure the column headings and widths:

for col, width in columns:
    tree.heading(col, text=col)
    tree.column(col, width=width, anchor=tk.CENTER)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.