如何使用 Python 和 Tkinter 创建具有两列标签的框架?

How To Create Frame With Two Columns of Labels using Python and Tkinter?

我想创建一个 table 的 n 行和 2 列 header。我知道 TkinterTreeCtrl 但不想使用它。我阅读了网格管理器并编写了一些示例代码,但它根本不符合我的要求。

首先,它显示两行而不是两列。 其次,当我注释掉行 self.sensorTable.pack() 时,我希望只看到退出按钮,因为这两个标签是列的从属,而列又是 sensorTable 的从属。

from Tkinter import *


class Window:

    def __init__(self):
        self.root = Tk()

        self.sensorTable = Frame(master=self.root)
        self.sensorNameColumn = LabelFrame(self.sensorTable, text="Name", padx=5, pady=5).grid(row = 0, column = 0)
        self.sensorValueColumn = LabelFrame(self.sensorTable, text="Value", padx=5, pady=5).grid(row = 0, column = 1)

        w = Label(master=self.sensorNameColumn, text="Hello")
        w.pack()

        w2 = Label(master=self.sensorValueColumn, text="World")
        w2.pack()

        #self.sensorTable.pack() # commenting this out should mean that the two entries are not seen on the window but they are for some reason

        quit_button = Button(self.root, text="Quit", command=self.quit)
        quit_button.pack(side=BOTTOM)

    def begin(self):
        mainloop()

    def quit(self):
        self.root.quit()     # stops mainloop
        self.root.destroy()


if __name__=="__main__":
    Window().begin()

gridpack 方法 return None。您需要将小部件创建语句和 grid-调用语句分开。

self.sensorTable = Frame(master=self.root)
self.sensorNameColumn = LabelFrame(self.sensorTable, text="Name", padx=5, pady=5)
self.sensorNameColumn.grid(row = 0, column = 0)
self.sensorValueColumn = LabelFrame(self.sensorTable, text="Value", padx=5, pady=5)
self.sensorValueColumn.grid(row = 0, column = 1)

否则,self.sensorNameColumnself.sensorValueColumn变为None;导致 ww2 成为 root 的 children;这就是为什么不管 self.sensorTable.pack().

都会显示这些标签的原因