尝试使用Tkinter和滚动文本在python中设置文本对齐方式

时间:2017-11-07 15:12:53

标签: python tkinter

我正在尝试将文本设置在中心或ScrolledText小部件中。这是怎么做到的? 我试过设置justify = center但是给出了“未知选项”-justify“ 我还可以做些什么。如果有帮助,这是我的代码

#Gui
import tkinter as tk
import tkinter.scrolledtext as tkst
from tkinter import *
def center_window(width=300, height=200):
    # get screen width and height
    screen_width = root.winfo_screenwidth()
    screen_height = root.winfo_screenheight()

    # calculate position x and y coordinates
    x = (screen_width/2) - (width/2)
    y = (screen_height/2) - (height/2)
    root.geometry('%dx%d+%d+%d' % (width, height, x, y))



root=Tk()
root.title("Writing is hard!") 
center_window(1200,600)

heading = Label(root, text="Welcome to the app which checks your content for you!", font=("arial",30,"bold"), fg="steelblue")
label1=Label(root, text="Please type in your article: ", font=("arial",20,"bold"), fg="lightgreen")
ArticleTextBox = tkst.ScrolledText(width=100, height=20, justify='CENTER')
def do_it():
    article=ArticleTextBox.get(0.0,tk.END)
    print("Hello "+name.get())
    print(article)
work= Button(root, text="work", width=30,height=5,bg="lightblue",command=do_it)

#Puts everything on screen
heading.pack()
label1.pack()
ArticleTextBox.pack()
work.pack()
root.mainloop()

1 个答案:

答案 0 :(得分:1)

justify是文本标记的属性。您可以将标记应用于所有文本,然后在该标记上设置justify属性。

ArticleTextBox.insert("end", "hello\nworld!", ("centered",))
ArticleTextBox.tag_configure("centered", justify="center")

顺便说一句,在您的代码中,您使用的索引0.0是无效的索引。 Tkinter会接受它,但从技术上讲它是无效的。文本索引是字符串,而不是浮点数,第一行从1(一)开始,而不是零。因此,0.0应为"1.0"