如何将2个按钮放在一起?

sou*_*urD 6 python tkinter button

b = Button(root, text="Enter", width=10, height=2, command=button1)
b.config()
b.pack(side=LEFT)

c = Button(root, text="Clear", width=10, height=2, command=clear)
c.pack(side=LEFT)


scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text.config(width=35, height=15)
text.pack(side=RIGHT, fill=Y)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
Run Code Online (Sandbox Code Playgroud)

如何将这两个按钮放在文本小部件的顶部?当我设置"side = LEFT"时,它只是将2个按钮放在文本小部件旁边

Bry*_*ley 15

这类问题通常有两种解决方案.在所有情况下或在这个特定的例子中,两者都不比另一个好.两种解决方案都完全可以接

解决方案1:使用两个容器(通常是框架).一个用于存放水平物品,一个用于存放垂直物品.在这种情况下,根窗口可以用作垂直堆叠项目的容器.将两个按钮放在水平框架中(使用pack(side = LEFT)),然后将该框架放在文本小部件上方(使用pack(side = TOP)).

解决方案2:使用网格几何管理器,它在网格中布置您的UI.将按钮放在单元格0,1和0,2中,将文本小部件放在1,1跨两列中.

通常,使用网格需要更多的前期规划.您必须确定哪些项目需要跨越列或行,哪些列或行应该随着窗口小部件的重新调整而增长和缩小等.包解决方案是"最简单的"(对于某些"简单"的定义,无论如何)对于非常简单的布局,例如这个.

使用框架来包含小部件组的一般技术是一个很好的技术.它可以轻松地将整个小部件组作为一个组进行管理.并混合和匹配从左到右的小部件组和从上到下的小部件组.

这就是我使用多帧技术的方法.请注意我如何创建小部件作为root的子级而不是内部框架的子级.这使得将来修改布局变得容易一些,因为您所要做的就是创建或删除各种框架而无需修改窗口小部件层次结构.

# create the main sections of the layout, 
# and lay them out
top = Frame(root)
bottom = Frame(root)
top.pack(side=TOP)
bottom.pack(side=BOTTOM, fill=BOTH, expand=True)

# create the widgets for the top part of the GUI,
# and lay them out
b = Button(root, text="Enter", width=10, height=2, command=button1)
c = Button(root, text="Clear", width=10, height=2, command=clear)
b.pack(in_=top, side=LEFT)
c.pack(in_=top, side=LEFT)

# create the widgets for the bottom part of the GUI,
# and lay them out
text = Text(root, width=35, height=15)
scrollbar = Scrollbar(root)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
scrollbar.pack(in_=bottom, side=RIGHT, fill=Y)
text.pack(in_=bottom, side=LEFT, fill=BOTH, expand=True)
Run Code Online (Sandbox Code Playgroud)

下面是使用网格的简单实现.它有不同的调整大小行为,可能是您想要的,也可能不是.这实际上取决于你想要的调整大小行为.通常我将使用框架管理一行控件,然后使用网格将其与其他窗口小部件一起布局.在这个例子中,我将只使用网格.

请注意,除了管理窗口小部件所在的行和列之外,还必须确定行和列的加权因子.至少你需要选择一行和一列来"拾取松弛",这通常意味着主要小部件所在的列(读取:通常是文本,画布或其他帧).

b = Button(root, text="Enter", width=10, height=2, command=button1)
c = Button(root, text="Clear", width=10, height=2, command=clear)
b.grid(row=0,column=0, sticky=W)
c.grid(row=0,column=1, sticky=W)

textframe = Frame(root)
textframe.grid(in_=root, row=1, column=0, columnspan=3, sticky=NSEW)
root.columnconfigure(0, weight=1)
root.rowconfigure(1, weight=1)

text = Text(root, width=35, height=15)
scrollbar = Scrollbar(root)
scrollbar.config(command=text.yview)
text.config(yscrollcommand=scrollbar.set)
scrollbar.pack(in_=textframe, side=RIGHT, fill=Y)
text.pack(in_=textframe, side=LEFT, fill=BOTH, expand=True)
Run Code Online (Sandbox Code Playgroud)

在这个特定的情况下,我会选择第一种方法,即包装方法.对于更复杂的设计,我几乎总是使用网格和包的混合.使用pack来自然地水平或垂直堆叠的项目(例如工具栏).使用网格进行更复杂的布局(例如整个应用程序,带滚动条的小部件,对话框等).您不能同时使用grid和pack作为同一个容器,但是您可以将pack用于一个容器,将grid用于另一个容器等.