在Python中有没有更好的方法来管理Tkinter中的place?

2024-04-16 22:01:16 发布

您现在位置:Python中文网/ 问答频道 /正文

现在我只使用方法place()来操作对象。像这样:

self.s_date_label = Label(self, text = 'Start Date: ')
self.s_date_label.place(x=0,y=0)
self.start_date = Entry(self, bd=1)
self.start_date.place(x=70,y=0)   
self.s_date_label2 = Label(self, text = 'example: 20160101'
self.s_date_label2.place(x=130,y=0)

然而,我相信这是一个愚蠢的方式。你知道吗

因为当我必须控制同一条线上的很多物体时。我只能通过place()中的参数x来控制它们。你知道吗

有没有更好的方法来管理对象的位置?你知道吗


Tags: 对象方法textselfdateexampleplacestart
2条回答

两种选择是使用gridpack

网格

如果需要使用行和列的类似于表的布局,那么grid是最佳选择。您可以指定特定的单元格,并且项目可以跨多行和/或多列。你知道吗

例如:

l1 = tk.Label(parent, text="Username:")
l2 = tk.Label(parent, text='Password:")
username_entry = tk.Entry(parent)
password_entry = tk.Entry(parent)

l1.grid(row=1, column=0, sticky="e")
username_entry.grid(row=1, column=1, sticky="ew")
l2.grid(row=2, column=0, sticky="e")
password_entry.grid(row=2, column=1, sticky="ew")

parent.grid_rowconfigure(3, weight=1)
parent..grid_columnconfigure(1, weight=1)

有关详细信息,请参见http://effbot.org/tkinterbook/pack.htm

包装

pack非常适合在水平或垂直组中布局对象。{< CD2> }对于工具栏来说是非常棒的,并且通常是我在整体布局中使用的工具,其中顶部有工具栏,底部是状态栏,中间是内容。你知道吗

例如:

toolbar_frame = tk.Frame(root)
statusbar_frame = tk.Frame(root)
content_frame = tk.Frame(root)

toolbar_frame.pack(side="top", fill="x")
statusbar_frame.pack(side="bottom", fill="x")
content_frame.pack(side="top", fill="both", expand=True)

有关详细信息,请参见http://effbot.org/tkinterbook/pack.htm

混合包装和网格

您可以(也应该)在同一个应用程序中同时使用gridpack。但是,不能在共享一个公共父级的小部件上同时使用这两种方法。你知道吗

这不起作用,因为toolbarstatusbar具有相同的父级:

toolbar = tk.Frame(root)
sstatusbar = tk.Frame(root)

toolbar.grid(...)
statusbar.pack(...)

这是可行的,因为toolbarsave_button有不同的父母。你知道吗

toolbar = tk.Frame(root)
save_button = tk.Button(toolbar, ...)

toolbar.pack(side="top", fill="x")
save_button.pack(side="left")

使用grid()方法将对象放置在布局中。你知道吗

在填充(padxpady)的帮助下,您还可以将对象隔开。你知道吗

有关详细信息,请查看:gridsample

相关问题 更多 >