如何根据文本长度为tkinter中entry小部件中的不同列指定不同的宽度

2024-10-03 15:24:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从MS SQL获取数据,并使用GUI的tkinter entry小部件在Python中显示数据。但是,在参数中设置宽度会使所有列具有相同的宽度,因此包含ID/键的列具有不必要的空间,而需要更大宽度的列的文本会被截断

这是我的密码:

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

这里参数roottotalRowstotalColoumnsrows由调用上述代码段的函数提供

这是生成的所有列的输出,其中前两列是主键和外键: Output


Tags: inselfforsql参数宽度tkinterrange
1条回答
网友
1楼 · 发布于 2024-10-03 15:24:21

我在这里假设前两列可以很小,例如宽度为10,而其他所有列都会更大,例如宽度为80

有很多方法可以改变for循环来创建表来实现这一点。例如,您可以创建宽度列表:

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

相关问题 更多 >