Home > Net >  center text in cell and adjust cell width
center text in cell and adjust cell width

Time:07-13

Basically I've got two problems which I'm currently not able to solve properly on my own and therefore I am looking for help!

  1. I am looking for a way to center the text in the cells of my table. Currently I am using grid() to build my table, but haven't found a way to center the text in the generated cells.

  2. The width of my cells is static, but I'd like to have it dynamically adjusting to the width of the column headline. I've tried counting characters of my headlines for each column, but unfortunatly that didnt work out in the correct way.

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])
   

CodePudding user response:

To center the text in a Text widget, you need to configure the justify option of a tag and insert the text using the tag:

text.tag_config('center', justify='center') # config a tag
text.insert(INSERT, ..., 'center') # specify the tag

To set the width of a column, find the width using len() and add sticky='ew' to all .grid(...).

Below is the modified code:

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')

Below is the result with sample data: enter image description here

  • Related