为什么justify和anchor不适用于pythontkin的标签

2024-06-09 09:42:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用以下代码,并尝试在标签上居中显示文本:

from tkinter import * 
root = Tk()
llist = ["first:","second label:","a really long label:","fourth:","fifth:"]
nrow = 0
for i in range(len(llist)):
    # Label(root, text=llist[i], justify='right').grid(row=nrow, column=0) # does not work
    # Label(root, text=llist[i], justify=RIGHT).grid(row=nrow, column=0) # does not work
    # Label(root, text=llist[i], anchor=E).grid(row=nrow, column=0) # does not work
    # Label(root, text=llist[i], anchor=E, justify=RIGHT).grid(row=nrow, column=0) # does not work
    Label(root, text=llist[i]).grid(row=nrow, column=0, sticky=E) # WORKS; 
    Entry(root).grid(row=nrow, column=1)
    nrow += 1
root.mainloop()

文本保留在center中,其中有我提到的不适用于上述代码的选项:

enter image description here

只有在grid()中使用sticky选项,它才能正常工作:

enter image description here

为什么justifyanchor选项在上面的代码中不起作用,即使它们在http://effbot.org/tkinterbook/label.htm等多个地方提到过?如何使用justifyanchor对齐标签中的文本?在


Tags: 代码text文本notcolumnrootlabelgrid
1条回答
网友
1楼 · 发布于 2024-06-09 09:42:24

这是因为您没有为Label设置width,如果不设置,Label将适合其内容。所以简而言之,Label内的文本使用anchor选项,但是Label的长度与文本的长度相同。位于center的不是text,而是Label。在

如果手动设置宽度:

Label(root, text=llist[i], anchor="e", width=20).grid(row=nrow, column=0)

它可以工作,但是很难手动指定Label的长度,因此使用grid的{}选项更好。在

相关问题 更多 >