在 tkinter 的树视图中更改单个列的宽度 [英] Changing individual column width in treeview in tkinter
本文介绍了在 tkinter 的树视图中更改单个列的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这里我有一个代码,我想为不同的列设置不同的列宽,有没有办法做到这一点?这里的宽度是 120,但我不希望所有列的宽度都是 120,只是特定的列,我希望其他列具有不同的宽度?有什么建议吗?提前致谢:)
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 :)
代码:
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='monkey123', database='BOOK')
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()
推荐答案
您可以将所需的宽度与列名放在一起:
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),
)
然后需要在创建treeview时提取列名:
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')
并配置列标题和宽度:
for col, width in columns:
tree.heading(col, text=col)
tree.column(col, width=width, anchor=tk.CENTER)
这篇关于在 tkinter 的树视图中更改单个列的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文