如何使用 Python 3 在 Tkinter 中将标签居中?

Ano*_* 55 1 python label tkinter center python-3.x

我开始使用 tkinter 创建一个简单的游戏并遇到了问题。我在互联网上搜索但找不到答案。我的问题是我无法弄清楚如何在 tkinter 中将标签居中。这是我的代码:

from tkinter import * #Imports TK Interface
import time #Imports Time Module
welcome = Tk() #Opens the Welcome window
welcome.title("Start Up") #Names the Wqelcome window 'StartUp'
welcome.config(bg = "gray") #Changes the Welcome windows background color to beige
nameLabel = Label(welcome, text="Welcome", bg="gray", fg="white")#Creates the welcome label
Run Code Online (Sandbox Code Playgroud)

如果您知道如何在 tkinter 中居中标签,请回答。谢谢!

Bry*_*ley 5

如果将单个小部件放置在另一个小部件的中心,place是最佳选择。它可以选择相对于另一个小部件定位一个小部件(通常但不一定是相对于其父部件)。

在您的情况下,您希望标签的中心位于其父标签的中心。您可以使用相对 X 坐标 0.5、相对 Y 坐标 0.5 和anchor“center”,这意味着小部件的中心放置在给定的坐标处。

例子:

nameLabel.place(relx=.5, rely=.5, anchor="center")
Run Code Online (Sandbox Code Playgroud)