如何在同一行中显示一系列小部件?

1 投票
1 回答
2998 浏览
提问于 2025-04-16 05:28

我刚开始学习tkinter,想知道能不能把一系列的控件放在同一行,而不是一个接一个地放在一列里。

我现在是用框架来放我的组件,不过如果我在一个框架里有好几个按钮,我更希望能直接把按钮放在我想要的位置,而不是再创建额外的小框架。

1 个回答

6

你可以使用几何管理器来安排容器内的小部件。Tkinter的几何管理器有 gridpackplace

grid 让你可以把小部件放在行和列中。pack 让你可以把小部件放在一个框的边上(非常适合做单一的水平或垂直列)。place 让你可以使用绝对和相对的位置。实际上,place 很少被使用。

在你的情况下,你想创建一排水平的按钮,通常是通过创建一个框架来表示这一排,然后使用 pack 把小部件并排放置。不要害怕使用子框架来布局——这正是它们的用途。

例如:

import Tkinter as tk

class App:
    def __init__(self):
        self.root = tk.Tk()
        # this will be the container for a row of buttons
        # a background color has been added just to make
        # it stand out.
        container = tk.Frame(self.root, background="#ffd3d3")

        # these are the buttons. If you want, you can make these
        # children of the container and avoid the use of "in_" 
        # in the pack command, but I find it easier to maintain
        # code by keeping my widget hierarchy shallow.
        b1 = tk.Button(text="Button 1")
        b2 = tk.Button(text="Button 2")
        b3 = tk.Button(text="Button 3")

        # pack the buttons in the container. Since the buttons
        # are children of the root we need to use the in_ parameter.
        b1.pack(in_=container, side="left")
        b2.pack(in_=container, side="left")
        b3.pack(in_=container, side="left")

        # finally, pack the container in the root window
        container.pack(side="top", fill="x")

        self.root.mainloop()

if __name__ == "__main__":
    app=App()

撰写回答