Python 3 Tkinter - Create Text Widget covering 100% Width with Grid

后端 未结 1 976
后悔当初
后悔当初 2021-01-06 22:08

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()
text         


        
相关标签:
1条回答
  • 2021-01-06 22:31

    Using grid requires these steps:

    • 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.

    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.

    You code would look like this:

    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()
    

    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.

    0 讨论(0)
提交回复
热议问题