问题
I would like to put an entry and a text label one under the other and with the same width.
Here is my code :
from tkinter import *
root = Tk()
title = StringVar()
title_entry = Entry(root, textvariable=title, width=30)
title_entry.pack()
content_text = Text(root, width=30)
content_text.pack()
root.mainloop()
But my 2 widgets don't have the same width. Any idea to solve it ?
回答1:
The widgets are different sizes probably because they have different default fonts. If they have the same fonts and the same widths, they should have the same natural width. However, the actual width can be affected by how they are placed in the window, and there are often good reasons to use different fonts for these widgets.
The simplest solution in your case is to have each widget fill the container in the x axis. This makes sure that, regardless of their natural width, they will expand to fill the window from edge to edge:
title.pack(fill="x")
content_text.pack(fill="x")
If these are your only two widgets you'll want to go a step further and specify additional options to get proper resize behavior:
title.pack(fill="x")
content_text.pack(fill="both", expand=True)
回答2:
The width for the Text and Entry widgets is set by the amount of characters. I think, possibly the default font sizes are different for Text and Entry. You may have to set the font sizes in your argument??
回答3:
You simply need to add a single argument to your .pack attribute. Just put this in:
.pack (fill=X)
Put this in and both widgets will stretch all the width of your window.
来源:https://stackoverflow.com/questions/16645990/set-the-same-width-to-an-entry-and-text-tkinter-label