问题
I'm scratching me head here. I'm very new at Tkinter. I'm trying to figure out something as basic as placing a label within a frame. The problem I'm having is when the label is displayed, it doesn't inherit the size of the parent. In fact, it actually changes the size of the frame in which it is placed. what am I doing wrong? In the end I want to add more labels and buttons in the different frames without the BG color in them.
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)
回答1:
From my experience, if you are placing multiple frames within your main window and want them to fill the rows / columns where you put them, you need to configure the rows/columns of your main window using grid_rowconfigure
and grid_columnconfigure
and give them a weight.
I have re-formatted your example above to include the configuration lines to show how I use them.
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 - I have removed your specified heights and widths - this is not necessary as you are telling the frame to fill all the space in the configured row / column in which it is 'gridded'.
Lastly, your first frame was defined as a 'LabelFrame' which im not fully sure is necessary in this example.
Hope this helps! Luke
来源:https://stackoverflow.com/questions/39761155/label-within-a-frame-tkinter