如何使用Python和Tkinter创建带有两列标签的框架?
我想创建一个包含n行和2列并带有标题的表。我知道TkinterTreeCtrl,但不想使用它。我阅读了grid manager,并编写了一些示例代码,但它根本不能满足我的需要 首先,它显示两行而不是两列。 其次,当我注释掉行如何使用Python和Tkinter创建带有两列标签的框架?,python,tkinter,Python,Tkinter,我想创建一个包含n行和2列并带有标题的表。我知道TkinterTreeCtrl,但不想使用它。我阅读了grid manager,并编写了一些示例代码,但它根本不能满足我的需要 首先,它显示两行而不是两列。 其次,当我注释掉行self.sensorTable.pack()时,我希望只看到退出按钮,因为这两个标签是列的从属,而列又是sensorTable的从属 from Tkinter import * class Window: def __init__(self):
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()
grid
,pack
方法返回None
。您需要将小部件创建语句和网格调用语句分开
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.sensorNameColumn
,self.sensorValueColumn
变为None
;使w
,w2
成为root
的子级;这就是为什么不管self.sensorTable.pack()如何显示这些标签的原因。