Python 3 Tkinter - 使用网格创建覆盖 100% 宽度的文本小部件
问题描述
我知道您可以使用 Pack Geometry Manager 轻松创建覆盖 100% 宽度的 Tkinter Text 小部件:
I know that you can easily create a Tkinter Text widget that covers 100% of the width using the Pack Geometry Manager:
from tkinter import *
root = Tk()
textWidget = Text(root)
textWidget.pack(side=TOP, fill=X)
root.geometry('600x1000')
root.mainloop()
但我想知道,如何使用带有 grid_columnconfigure 的网格几何管理器完成同样的任务?
But I was wondering, how do I accomplish this same task using the Grid Geometry Manager with grid_columnconfigure?
解决方案
使用网格需要这些步骤:
Using grid requires these steps:
- 使用文本小部件的
grid
方法,为其指定行和列.在这种情况下您可以使用 0,0. - 也可以使用
grid
方法,定义您是否希望小部件粘贴"它被分配到空间的两侧.在你的情况下,你这样做,所以你可以给字符串nsew"(北、南、东、西). - 将小部件所在的行配置为权重为 1(一).这样做
grid_rowconfigure
.这将导致该行垂直扩展以填充任何额外的空间 - 将小部件所在的列配置为权重为 1(一).这样做
grid_columnconfigure
.这将导致列水平扩展以填充任何额外的空间.
- use the
grid
method of the text widget, giving it a row and column. In this case you can use 0,0. - also with the
grid
method, define whether or not you want the widget to "stick" to the sides of the space it was given. In your case you do, so you can give the string "nsew" (north, south, east, west). - configure the row that the widget is in to have a weight of 1 (one). Do this with
grid_rowconfigure
. This will cause the row to expand vertically to fill any extra space - configure the column that the widget is in to have a weight of 1 (one). Do this with
grid_columnconfigure
. This will cause the column to expand horizontally to fill any extra space.
注意 grid_rowconfigure
和 grid_columnconfigure
是在包含文本小部件的小部件,而不是文本小部件本身.grid
方法是在文本小部件上调用,因为您正在告诉文本小部件它应该放在哪里本身在其父项中.
Note that grid_rowconfigure
and grid_columnconfigure
are methods to be called on the
widget that contains the text widget, not on the text widget itself. The grid
method is
called on the text widget, because you are telling the text widget where it should place
itself in its parent.
您的代码将如下所示:
from tkinter import *
root = Tk()
textWidget = Text(root)
textWidget.grid(row=0, column=0, sticky="nsew")
root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)
root.geometry('600x1000')
root.mainloop()
当你有一个小部件来填充分配给它的所有空间时,我推荐 pack
只是因为你可以用一行代码而不是三行代码来完成所有事情.pack
非常适合这类问题.grid
更适合创建小部件网格,正如其名称一样.话虽如此,两者都是完全可以接受的.您可以在同一个程序中混合和匹配 grid
和 pack
,但不能将它们同时用于共享一个共同父级的小部件.
When you have a single widget that is to fill all of the space allotted to it, I recommend pack
simply because you can do everything with one line of code rather than three. pack
is perfect for this type of problem. grid
is more suited to creating a grid of widgets, as its name applies. That being said, either is perfectly acceptable. You can mix and match grid
and pack
within the same program, though you can't use them both for widgets that share a common parent.
相关文章