简体   繁体   中英

How do I center text in the Tkinter Text widget?

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!

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

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

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

Here's your code with the modification indicated so it does what you want. This was accomplished by adding a new function named insert_centered() and calling it everywhere the contents of the text widget is changed.

Notice that the new function is passed the text widget rather than hardcoding the name of a global variable into it.

import random
import PIL.ImageTk
import PIL.Image
from Tkinter import *


def thinking():
#    T1.insert(INSERT, 'Thinking...')  # REMOVED
    insert_centered(T1, 'Thinking...')  # ADDED
    T1.after(3000, empty_textbox)


def empty_textbox():
    T1.delete("1.0", END)


def new_question(event=None):
    empty_textbox()
    if len(entry.get()) == 0:
#        T1.insert(END, 'Ask a question')  # REMOVED
        insert_centered(T1, 'Ask a question')  # ADDED
    else:
        thinking()
        T1.after(3000, give_answer)


def give_answer():
    answers = ['Signs point to yes.',
               'Yes.',
               'Reply hazy',
               'try again.',
               'Without a doubt.',
               'My sources say no.',
               'As I see it, yes.',
               'You may rely on it.',
               'Concentrate and ask again.',
               'Outlook not so good.',
               'It is decidedly so.',
               'Better not tell you now.',
               'Very doubtful.',
               'Yes - definitely.',
               'It is certain.',
               'Cannot predict now.',
               'Most likely.',
               'Ask again later.',
               'My reply is no.',
               'Outlook good.',
               'Don\'t count on it.']
    answer = random.randint(1, 20)
#    T1.insert(END, answers[answer])  # REMOVED
    insert_centered(T1, answers[answer])  # ADDED


def end():
    exit()


def clear():
    entry.delete(0, 'end')
    T1.delete('1.0', END)


def insert_centered(text_widget, text):        # ADDED
    text_widget.delete("1.0", END)             # ADDED
    text_widget.insert("1.0", text, "center")  # ADDED


root = Tk()

load = PIL.Image.open("8-ball.png")
render = PIL.ImageTk.PhotoImage(load)

img = Label(root, image=render)
img.image = render
img.pack()

topFrame = Frame(root)
topFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack(side=BOTTOM)

entry = Entry(root, width=40)
entry.pack()

T1 = Text(root, width=26, height=1)
T1.tag_configure("center", justify='center')
T1.tag_add("center", 1.0, "end")
T1.pack()

root.bind('<Return>', new_question)

button1 = Button(bottomFrame, text="Ask", fg="blue", command=new_question)
button2 = Button(bottomFrame, text="Clear", fg="blue", command=clear)
button3 = Button(bottomFrame, text="Quit", fg="blue", command=end)

button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)

root.mainloop()

For convenience of other readers, here's an image that can be used for testing:

测试图像

There is a simple modification or trick which you can do to get desired result just add a blank space and then use your code it will work. The code is here:-

import tkinter as tk
root = tk.Tk()
T1 = tk.Text(root)
T1.tag_configure("center", justify='center')
T1.insert(1.0, " ")
T1.tag_add("center", "1.0", "end")
T1.pack()
root.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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