Python tkinter - 使用嵌套框架时无法定位子框架

问题描述

我正在尝试使用 tkinter,

#创建黑框

frame=Frame(root,width=366,height=559,bg="black")
frame.pack(padx=(0,0),pady=(0,0))

#在黑框上放置灰色框和品红色框

frame2=Frame(frame,width=349,height=57,bg="grey").place(x=8,y=10)
frame3=Frame(frame,width=70,height=473,bg="magenta").place(x=8,y=74)

#Placing Blue frame ON magenta frame,at (0,but this go to the root's (0,0)

frame4=Frame(frame3,width=50,height=50,bg="blue").place(x=0,y=0)

灰色和洋红色框架相对于黑色框架完美放置 但是蓝框转到根窗口的 (0,0)。为什么?我将如何在洋红色框架上放置蓝色框架?

enter image description here

完整代码

from tkinter import *
root = Tk()
root.title("Fee Fie Foe Fum")
frame=Frame(root,0))
frame2=Frame(frame,y=74)
frame4=Frame(frame3,y=0)
root.mainloop()

解决方法

蓝框 frame4 进入根窗口,因为它使用 frame3 作为父窗口。 frame3None,tkinter 将其视为已通过根窗口。

frame3None 的原因是因为 place(以及 packgrid)都返回 None。因此,Frame(...).place(...) 返回 None

恕我直言,最好将小部件创建与小部件布局分开。这导致需要一些临时变量,但使用单一样式(始终将两者分开)比有时使用一种样式有时使用另一种样式更容易管理代码。