[英]center text in cell and adjust cell width
基本上我有两个问题,我目前无法自行解决,因此我正在寻求帮助!
我正在寻找一种将文本置于表格单元格中的方法。 目前我正在使用 grid() 来构建我的表格,但还没有找到一种方法来将生成的单元格中的文本居中。
我的单元格的宽度是静态的,但我想让它动态调整到列标题的宽度。 我已经尝试计算每列标题的字符数,但不幸的是,这并没有以正确的方式解决。
n_rows = df.shape[0]
n_cols = df.shape[1]
column_names = df.columns
i=0
for j, col in enumerate(column_names):
text = Text(ausgabe, width=26, height=1.2, bg = "#9BC2E6")
text.config(font=("Arial", 20))
text.grid(row=i,column=j)
text.insert(INSERT, col)
for i in range(n_rows):
for j in range(n_cols):
text = Text(ausgabe, width=26, height=1.2)
text.config(font=("Arial", 20))
text.grid(row=i+1, column=j)
text.insert(INSERT, df.loc[i][j])
要在Text
小部件中居中文本,您需要配置tag
的justify
选项并使用tag
签插入文本:
text.tag_config('center', justify='center') # config a tag
text.insert(INSERT, ..., 'center') # specify the tag
要设置列的宽度,请使用len()
找到宽度并将sticky='ew'
添加到所有.grid(...)
。
下面是修改后的代码:
for j, col in enumerate(column_names):
text = Text(ausgabe, width=len(col), height=1.2, bg="#9BC2E6")
text.config(font=("Arial", 20))
text.grid(row=0, column=j, sticky='ew') # added sticky option
text.tag_config('center', justify='center') # config a tag
text.insert(INSERT, col, 'center') # use the tag
for i in range(n_rows):
for j in range(n_cols):
value = df.loc[i][j]
text = Text(ausgabe, width=len(str(value)), height=1.2)
text.config(font=("Arial", 20))
text.grid(row=i+1, column=j, sticky='ew')
text.tag_config('center', justify='center')
text.insert(INSERT, value, 'center')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.