【问题标题】:How to center the text label in tkinter?如何在 tkinter 中将文本标签居中?
【发布时间】:2020-05-22 01:18:04
【问题描述】:

我有一个形状固定的窗口,并在 GUI 上放置了一些文本。这是我的代码:

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

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

默认情况下,此代码将文本左对齐。如何保持在中间?

这是我的窗口图片供参考:

(知道为什么我要在两边加上那两条线吗?)

【问题讨论】:

标签: python tkinter


【解决方案1】:

要使插入的文本居中,请使用justify='center' 配置标签:

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

然后在插入的时候也加上标签:

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

要让Text 小部件填满两边,请使用fill="both"

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

把它们放在一起:

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()

【讨论】:

    【解决方案2】:

    您可以获取窗口宽度并将文本围绕宽度居中

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

    要编辑文本区域,您可以使用 Text 对象的 padx 选项,或者通过设置总 width 并利用该值使文本围绕宽度居中,使文本本身居中,有关详细信息,请参阅选项参考以下链接

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

    了解布局和网格系统以设置适当的填充以删除窗口填充线也很有用

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

    【讨论】:

    • 我需要将“文本”小部件内的文本居中,而不是窗口的标题。
    猜你喜欢
    • 1970-01-01
    • 2011-07-15
    • 2018-07-21
    • 1970-01-01
    • 2011-03-03
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2016-09-16
    相关资源
    最近更新 更多