A Label in a Frame in a window won't stretch, why?

时光毁灭记忆、已成空白 提交于 2021-02-10 16:42:52

问题


I would like to display

  • a window
  • with a single Frame
  • and a Label in the Frame which would stretch to the whole width of the window

The following code

import Tkinter as tk

root = tk.Tk()
root.geometry("100x100")
# first column of root will stretch
root.columnconfigure(0, weight=1)

# a frame in root
upper_frame = tk.Frame(root)
# first column of upper_frame will stretch
upper_frame.columnconfigure(0, weight=1)
upper_frame.grid(row=0, column=0)

# a label in upper_frame, which should stretch
mylabel = tk.Label(upper_frame)
mylabel.grid(row=0, column=0)
mylabel.configure(text="hello", background="blue")

root.mainloop()

displays

enter image description here

Why isn't the Label stretching to the whole width of the window but is just as wide as the text?


回答1:


Specifying sticky option when you call grid (e = east, w = west). Otherwise the widget in the cell is center-aligned.

upper_frame.grid(row=0, column=0, sticky='ew')
..
mylabel.grid(row=0, column=0, sticky='ew')

enter image description here



来源:https://stackoverflow.com/questions/24596354/a-label-in-a-frame-in-a-window-wont-stretch-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!