R watt
R watt

Reputation: 77

Trying to set text alignment in python using Tkinter and scrolled text

I am trying to set the text to be placed in the center or a ScrolledText widget. How is this done? I have tried setting justify=center but that gives "Unknown option "-justify" What else can I do. Here is my code if it helps

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

Upvotes: 0

Views: 1509

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 385840

justify is an attribute of a text tag. You can apply a tag to all the text, then set the justify attribute on that tag.

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

By the way, in your code you use the index 0.0 which is an invalid index. Tkinter will accept it, but technically it's invalid. Text indexes are strings, not floating point numbers, and the first line starts at 1 (one), not zero. So, 0.0 should be "1.0".

Upvotes: 2

Related Questions