简体   繁体   English

Tkinter Label 中心文本设置文本从左上角开始

[英]Tkinter Label center text set text to start from top left

I'm creating a GUI for my application with Tkinter, and when I create a Label, the text is always at the center of the label, is there a way to set the text to start from the top left?我正在使用 Tkinter 为我的应用程序创建 GUI,当我创建 Label 时,文本始终位于 label 的中心,有没有办法从顶部开始设置?

big_text_area = Label(self.master, text='Hello, World!', width=70, height=25, bg='white', foreground='black')
big_text_area.place(x=380, y=30)

Example:例子:

在此处输入图像描述

I believe the position of your label is determined by the .place() function.我相信您的 label 的 position 由.place() function 确定。 So if you want the label to be at the top left, you should do:因此,如果您希望 label 位于左上角,您应该这样做:

big_text_area.place(x = 0, y = 0)

Tutorialspoint and effbot have a documentation for the .place( ) function and the arguments it takes. Tutorialspointeffbot有一个关于.place( ) function 和 arguments 的文档。 Most have default values so keep that in mind.大多数都有默认值,所以请记住这一点。

Another thing I would point out is that the width and height keyword arguments do not change the size of your text.我要指出的另一件事是widthheight关键字 arguments 不会改变文本的大小。 Rather, they change the rectangular box around your text.相反,它们会更改文本周围的矩形框。 This might be the reason why your text is still in the middle even if you set its positions to the top left.这可能是即使您将其位置设置为左上角,您的文本仍位于中间的原因。 effbot again has the details on the Label widget. effbot再次具有Label小部件的详细信息。

Just a quick working example: (Python 3.7)只是一个快速工作的例子:(Python 3.7)

from tkinter import *

master = Tk()

master.geometry("200x200") 

# to change text size, use font=("font name", size)
w = Label(master, text="Hello, world!", font=("Helvetica", 22))

# explicitly set the text to be at the top left corner
w.place(anchor = NW, x = 0, y = 0)

mainloop()

Font question is also answered in this post: How do I change the text size in a Label widget?这篇文章还回答了字体问题: 如何更改 Label 小部件中的文本大小?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM