如何在 Tkinter 文本小部件中居中文本? [英] How do I center text in the Tkinter Text widget?

查看:61
本文介绍了如何在 Tkinter 文本小部件中居中文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Python 并且我正在完成小项目.我已经制作了一个 8 球程序,它几乎完成了.令我烦恼的一件事是输出给用户的文本没有居中.

I am learning python and I'm completing mini projects. I've made an 8-ball program and it is almost done. One thing that is annoying me is that the text output to the user is not centred.

我该怎么做?我已经尝试了以下但仍然没有运气.

How do I do this? I've tried the following but still no luck.

T1.tag_configure("center", justify='center')
T1.tag_add("center", 1.0, "end")

我的代码在这里.感谢您的帮助!

My code is here. Thanks for your help!

推荐答案

Text 小部件最初是空的,所以 T1.tag_add("center", "1.0", "end") 没有效果,但是如果在添加标签之前在小部件中插入文本,则用户之后插入的文本保持居中:

The Text widget is initially empty so the T1.tag_add("center", "1.0", "end") has no effect, but if you insert text inside the widget before adding the tag, then the text inserted afterwards by the user stay centered:

import Tkinter as tk

root = tk.Tk()

T1 = tk.Text(root)
T1.tag_configure("center", justify='center')
T1.insert("1.0", "text")
T1.tag_add("center", "1.0", "end")
T1.pack()

root.mainloop()

由于在您的完整代码中您使用的是一行 Text 小部件,因此您可以使用 Entry 代替:

Since in your full code you use a one line Text widget, you could use an Entry instead:

tk.Entry(root, justify='center')

这篇关于如何在 Tkinter 文本小部件中居中文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆