sajjad
sajjad

Reputation: 17

How to give different widths to different columns in entry widget in tkinter based on text length

I am fetching data from MS SQL and displaying it in Python using tkinter entry widget for the GUI. However, setting the width in the parameter gives all columns the same width so columns containing ID/Keys have unnecessary space while columns that require more width have their text truncated.

Here is my code:

class Table: 
      
    def __init__(self, root, totalRows, totalColoumns, rows): 
          
        # code for creating table 
        for i in range(totalRows): 
            for j in range(totalColoumns): 
                  
                self.e = tkinter.Entry(root, width=50, fg='blue', 
                               font=('Arial', 12)) 
                  
                self.e.grid(row=i, column=j) 
                self.e.insert(tkinter.END, rows[i][j]) 

here the parameters root, totalRows, totalColoumns, rows are provided by a function that is calling the above piece of code.

This is the output of all the columns generated where the first two columns are primary key and foreign key: Output

Upvotes: 0

Views: 406

Answers (1)

j_4321
j_4321

Reputation: 16169

I am assuming here that the two first columns can be small, e.g. of width 10, while all the other ones will be larger, e.g. of width 80.

There are plenty of ways to change the for loop creating the table to achieve this. For instance you can create a list of widths:

widths = [10, 10] + [80]*(totalColoumns - 2)

# code for creating table 
for i in range(totalRows): 
    for j in range(totalColoumns): 
          
        self.e = tkinter.Entry(root, width=widths[j], fg='blue', 
                       font=('Arial', 12)) 
          
        self.e.grid(row=i, column=j) 
        self.e.insert(tkinter.END, rows[i][j]) 

Upvotes: 2

Related Questions