python输出文本居中_如何在Tkinter文本小部件中居中文本?
这是你的代码和修改指示,以便它做你想要的。这是通过添加一个名为insert_centered()的新函数并在文本小部件的内容发生更改时调用它来实现的。
注意,新函数是传递给文本小部件的,而不是硬编码全局变量的名称。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('', 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()
为了方便其他读者,下面是一个可用于测试的图像: