简体   繁体   English

如何在 tkinter 中将文本 label 居中?

[英]How to center the text label in tkinter?

I have a window with a fixed shape and put up some text on the GUI.我有一个形状固定的 window 并在 GUI 上放置了一些文本。 Here is my code:这是我的代码:

root = Tk()
root.title('Vocab')
root.geometry('700x400')

text = Text(root)
text.insert(INSERT, word)
text.config(state='disabled')
text.pack()
root.mainloop()

This code by default alligns the text to the left.默认情况下,此代码将文本向左对齐。 How to keep it in the middle?如何保持在中间?

Here is a picture of my window for reference:这是我的 window 的图片供参考:

(Any idea why I'm getting those 2 lines on the sides?) (知道为什么我要在两边加上那两条线吗?) 在此处输入图像描述

To center the inserted text, configure a tag with justify='center' :要使插入的文本居中,请使用justify='center'配置标签:

text.tag_configure("center", justify='center')

Then when you insert, add the tag as well:然后,当您插入时,也添加标签:

text.insert(INSERT, "jawbone", "center")

To have you Text widget fill up both sides, use fill="both" :要让您的Text小部件填充两侧,请使用fill="both"

text.pack(fill="both",expand=True)

Putting it all together:把它们放在一起:

import tkinter as tk

root = tk.Tk()
root.title('Vocab')
root.geometry('700x400')

text = tk.Text(root)
text.tag_configure("center", justify='center')
text.insert("1.0", "jawbone", "center")
text.config(state='disabled')
text.pack(fill="both", expand=True)
root.mainloop()

You can get the window width and center the text around the width您可以获得 window 宽度并将文本围绕宽度居中

root = Tk()
width = root.winfo_screenwidth() 
root.title('Vocab'.center(width))

To edit the text area you can either use the padx option for the Text object or center the text itself by setting the total width and utilizing the value to center the text around the width, for more information in the options refer the following link要编辑文本区域,您可以使用文本 object 的padx选项或通过设置总width并利用该值将文本围绕宽度居中来居中文本本身,有关选项中的更多信息,请参阅以下链接

https://web.archive.org/web/20190507210123/http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text.html https://web.archive.org/web/20190507210123/http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text.html

Also useful would be to understand the layout and grid system to setup the appropriate padding to remove the window padding lines了解布局和网格系统以设置适当的填充以删除 window 填充线也很有用

https://web.archive.org/web/20190429195421/http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/layout-mgt.html https://web.archive.org/web/20190429195421/http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/layout-mgt.html

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

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