[英]How to center widgets vertically and horizontally in window with Tkinter?
I need to center 3 labels vertically within the window. 我需要在窗口中垂直居中放置3个标签。 The labels are centered on-top of each other, but they are fixed at the top of the window. 标签在彼此的顶部居中,但它们固定在窗口的顶部。
What do I need to do to have them sit right in the middle of the window, (vertically and horizontally)? 要使它们正好位于窗口中间(垂直和水平),该怎么办?
Here is my code: 这是我的代码:
from tkinter import *
root = Tk()
root.geometry("200x200")
root.title("Question 2")
root.configure(background="green")
Label(root, text = "RED", fg="red", bg="black").pack()
Label(root, text = "WHITE", fg="white", bg="black").pack()
Label(root, text = "BLUE", fg="blue", bg="black").pack()
root.mainloop()
I think that in this case you can simply use a Frame
widget as the parent of the labels and then pack the frame by setting the expand
option to True
: 我认为在这种情况下,您可以简单地使用Frame
小部件作为标签的父级,然后通过将expand
选项设置为True
来打包框架:
from tkinter import *
root = Tk()
root.geometry("200x200")
root.title("Question 2")
root.configure(background="green")
parent = Frame(root)
Label(parent, text = "RED", fg="red", bg="black").pack(fill="x")
Label(parent, text = "WHITE", fg="white", bg="black").pack(fill="x")
Label(parent, text = "BLUE", fg="blue", bg="black").pack(fill="x")
parent.pack(expand=1) # same as expand=True
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.