如何在填充整个单元格时左对齐 Python tkinter 网格列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30550774/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:37:41  来源:igfitidea点击:

How to left justify Python tkinter grid columns while filling entire cell

pythonpython-3.xtkintergrid

提问by Ryan

I'm trying to write a python class to display data in a tabular format. I'm sure there are classes out there already to do the same thing, however, I'm using this exercise as a way to teach myself Python and tkinter. For the most part, I have the class working the way I want it to, however I cannot get the header and data cells to fill their entire cell, while being aligned left. Here is what my class currently generates for a table:

我正在尝试编写一个 python 类来以表格格式显示数据。我确信已经有一些课程可以做同样的事情,但是,我正在使用这个练习作为自学 Python 和 tkinter 的一种方式。在大多数情况下,我让类按照我希望的方式工作,但是我无法让标题和数据单元格填充整个单元格,同时向左对齐。这是我的班级当前为表生成的内容:

How the table currently looks

表格目前的样子

I went ahead and changed the sticky on the cells to be (W,E) rather than just W, in order to show how I want the table to look, except each cell left justified. Below is what I'm shooting for:

我继续将单元格上的粘性更改为 (W,E) 而不仅仅是 W,以显示我希望表格的外观,除了每个单元格左对齐。以下是我拍摄的内容:

How I want the table to look

我希望桌子看起来如何

Based on the research I've done, it would seem I need to be using the weightattribute of grid_columnconfigureand grid_rowconfigure, however every way I have tried using them I cannot, get it to work.

根据我所做的研究,似乎我需要使用and的weight属性,但是我尝试使用它们的每一种方式我都不能,让它工作。grid_columnconfiguregrid_rowconfigure

Here is the code for my class (I am using Python 3.4):

这是我的课程的代码(我使用的是 Python 3.4):

from tkinter import *
from tkinter import ttk
from tkinter import font

class TableData:

    def __init__(self,parent,attributes,columns,data):
        self.parent = parent
        self.tableName = StringVar()
        self.tableName.set(attributes['tableName'])
        self.columns = columns
        self.columnCount = 0
        self.borderColor = attributes['borderColor']
        self.titleBG = attributes['titleBG']
        self.titleFG = attributes['titleFG']
        self.titleFontSize = attributes['titleFontSize']
        self.headerBG = attributes['headerBG']
        self.headerFG = attributes['headerFG']
        self.headerFontSize = attributes['headerFontSize']
        self.dataRowColor1 = attributes['dataRowColor1']
        self.dataRowColor2 = attributes['dataRowColor2']
        self.dataRowFontSize = attributes['dataRowFontSize']
        self.dataRowFG = attributes['dataRowFG']
        self.data = data
        self.tableDataFrame = ttk.Frame(self.parent)
        self.tableDataFrame.grid(row=0,column=0)
        self.initUI()

    def countColumns(self):
        cnt = 0
        for i in self.columns:
            cnt += 1

        self.columnCount = cnt

    def buildTableTitle(self):
        tableTitleFont = font.Font(size=self.titleFontSize)
        Label(self.tableDataFrame,textvariable=self.tableName,bg=self.titleBG,fg=self.titleFG,font=tableTitleFont, highlightbackground=self.borderColor,highlightthickness=2).grid(row=0,columnspan=self.columnCount,sticky=(W,E), ipady=3)

    def buildHeaderRow(self):
        colCount = 0
        tableHeaderFont = font.Font(size=self.headerFontSize)
        for col in self.columns:
            Label(self.tableDataFrame,text=col,font=tableHeaderFont,bg=self.headerBG,fg=self.headerFG,highlightbackground=self.borderColor,highlightthickness=1).grid(row=1,column=colCount,sticky=W, ipady=2, ipadx=5)
            colCount += 1

    def buildDataRow(self):
        tableDataFont = font.Font(size=self.dataRowFontSize)
        rowCount = 2
        for row in self.data:
            if rowCount % 2 == 0:
                rowColor = self.dataRowColor2
            else:
                 rowColor = self.dataRowColor1
            colCount = 0
            for col in row:
                Label(self.tableDataFrame,text=col,bg=rowColor,fg=self.dataRowFG,font=tableDataFont,highlightbackground=self.borderColor,highlightthickness=1).grid(row=rowCount,column=colCount,sticky=W,ipady=1, ipadx=5)
                colCount += 1
            rowCount += 1

    def initUI(self):
        self.countColumns()
        self.buildTableTitle()
        self.buildHeaderRow()
        self.buildDataRow()

Here is a test file referencing the TableData class:

这是一个引用 TableData 类的测试文件:

from tkinter import *
from tkinter import ttk
from tableData import TableData
import sqlite3

root = Tk()
root.geometry('1000x400')

mainframe = ttk.Frame(root).grid(row=0,column=0)

attributes = {}
attributes['tableName'] = 'Title'
attributes['borderColor'] = 'black'
attributes['titleBG'] = '#1975D1'
attributes['titleFG'] = 'white'
attributes['titleFontSize'] = 16
attributes['headerBG'] = 'white'
attributes['headerFG'] = 'black'
attributes['headerFontSize'] = 12
attributes['dataRowColor1'] = 'white'
attributes['dataRowColor2'] = 'grey'
attributes['dataRowFontSize'] = 10
attributes['dataRowFG'] = 'black'

columns = ['Col 1', 'Column 2', 'Column 3','Column    4']

results = [('1','Key','Desc','Attribute'),('2','Key Column','Description Column','AttributeColumn')]

table = TableData(mainframe,attributes,columns,results)

root.mainloop()

Thanks in advance for any insight. Please, let me know if there is any other info that would be helpful.

提前感谢您的任何见解。请让我知道是否还有其他有用的信息。

采纳答案by Bryan Oakley

If you want the text in a label to be left-aligned, use the anchor option. It takes a string representing a point on a compass (eg: "w" = "west", meaning the text is anchored to the left):

如果您希望标签中的文本左对齐,请使用锚选项。它需要一个表示指南针上一个点的字符串(例如:“w” = “west”,表示文本定位在左侧):

for col in row:
    Label(..., anchor="w").grid(...)

回答by WoodyP

Try to set the columnspanattribute when griding:

尝试columnspan在网格化时设置属性:

self.tableDataFrame.grid(row=0, column=0, columnspan=2)

2 may not be the correct size, try 'til you get it like you want it.

2 可能不是正确的尺寸,请尝试直到得到想要的为止。

回答by xjfengck

For any grid of geometry, add option sticky="W", for example,

对于任何几何网格,添加 option sticky="W",例如,

self.tableDataFrame.grid(sticky="W", row=0, column=0)

回答by khan

You are not defining the width of your label so tkinter sets the width of Label equal to the width of the text. Thats why your labels do not occupy entire width of the cell. To make them occupy all the available width use stickey = E+W

您没有定义标签的宽度,因此 tkinter 将 Label 的宽度设置为等于文本的宽度。这就是为什么您的标签不会占据单元格的整个宽度。为了让它们占据所有可用的宽度,使用stickey = E+W

    Label(self.tableDataFrame,text=col,font=tableHeaderFont,bg=self.headerBG,fg=self.headerFG,highlightbackground=self.borderColor,highlightthickness=1).grid(row=1,column=colCount,sticky=W+E, ipady=2, ipadx=5)