框架内的标签 (Tkinter)

Label within a Frame (Tkinter)

我在这里挠头。我是 Tkinter 的新手。我试图弄清楚一些像在框架内放置标签一样基本的东西。我遇到的问题是显示标签时,它不会继承父级的大小。事实上,它实际上改变了放置它的框架的大小。我究竟做错了什么?最后我想在不同的框架中添加更多的标签和按钮,而不是其中的 BG 颜色。

main = Tk()

main.geometry('1024x768+0+0')

fm1 = LabelFrame(main, width = 1024, height = 68, bg = 'RED')
fm1.grid(row = 0, columnspan = 2)

label = Label(fm1, text = 'test')
label.grid(row = 0, sticky = N+E+S+W)

fm2 = Frame(main, width = 1024, height = 200, bg = 'BLUE')
fm2.grid(row = 1, columnspan = 2)

fm3 = Frame(main, width = 512, height = 300, bg = 'GREEN')
fm3.grid(row = 2, column = 0)

fm4 = Frame(main, width = 512, height = 300, bg = 'BLACK')
fm4.grid(row = 2, column = 1)

fm5 = Frame(main, width = 1024, height = 200, bg = 'YELLOW')
fm5.grid(row = 3, columnspan = 2)

根据我的经验,如果您在主 window 中放置多个框架并希望它们填充放置它们的行/列,则需要配置主 rows/columns window 使用 grid_rowconfiguregrid_columnconfigure 并给它们一个权重。

我已重新格式化您上面的示例以包含配置行以展示我如何使用它们。

main = Tk()
main.geometry('1024x768+0+0')

# Congigure the rows that are in use to have weight #
main.grid_rowconfigure(0, weight = 1)
main.grid_rowconfigure(1, weight = 1)
main.grid_rowconfigure(2, weight = 1)
main.grid_rowconfigure(3, weight = 1)

# Congigure the cols that are in use to have weight #
main.grid_columnconfigure(0, weight = 1)
main.grid_columnconfigure(1, weight = 1)


# Define Frames - use sticky to fill allocated row / column #
fm1 = Frame(main, bg = 'RED')
fm1.grid(row = 0, columnspan = 2, sticky='news')

fm2 = Frame(main, bg = 'BLUE')
fm2.grid(row = 1, columnspan = 2, sticky='news')

fm3 = Frame(main, bg = 'GREEN')
fm3.grid(row = 2, column = 0, sticky='news')

fm4 = Frame(main, bg = 'BLACK')
fm4.grid(row = 2, column = 1, sticky='news')

fm5 = Frame(main, bg = 'YELLOW')
fm5.grid(row = 3, columnspan = 2, sticky='news')

# Notice 'pack' label - fine to use here as there are no conflicting grid widgets in this frame #
lab = Label(fm1, text = 'TEST LABEL')
lab.pack()

main.mainloop()

PS - 我已经删除了你指定的高度和宽度 - 这不是必需的,因为你告诉框架填充配置的行/列中的所有 space 'gridded'.

最后,您的第一帧被定义为 'LabelFrame',我不确定在这个例子中是否有必要。

希望对您有所帮助! 卢克