3

I have a window with a fixed shape and put up some text on the GUI. Here is my code:

root = Tk()
root.title('Vocab')
root.geometry('700x400')

text = Text(root)
text.insert(INSERT, word)
text.config(state='disabled')
text.pack()
root.mainloop()

This code by default alligns the text to the left. How to keep it in the middle?

Here is a picture of my window for reference:

(Any idea why I'm getting those 2 lines on the sides?) enter image description here

Harsha
  • 533
  • 3
  • 13
  • Does this answer your question? [how-to-set-justification-on-tkinter-text-box](https://stackoverflow.com/questions/15014980) – stovfl May 22 '20 at 10:19

2 Answers2

3

To center the inserted text, configure a tag with justify='center':

text.tag_configure("center", justify='center')

Then when you insert, add the tag as well:

text.insert(INSERT, "jawbone", "center")

To have you Text widget fill up both sides, use fill="both":

text.pack(fill="both",expand=True)

Putting it all together:

import tkinter as tk

root = tk.Tk()
root.title('Vocab')
root.geometry('700x400')

text = tk.Text(root)
text.tag_configure("center", justify='center')
text.insert("1.0", "jawbone", "center")
text.config(state='disabled')
text.pack(fill="both", expand=True)
root.mainloop()
Henry Yik
  • 22,275
  • 4
  • 18
  • 40
-2

You can get the window width and center the text around the width

root = Tk()
width = root.winfo_screenwidth() 
root.title('Vocab'.center(width))

To edit the text area you can either use the padx option for the Text object or center the text itself by setting the total width and utilizing the value to center the text around the width, for more information in the options refer the following link

https://web.archive.org/web/20190507210123/http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text.html

Also useful would be to understand the layout and grid system to setup the appropriate padding to remove the window padding lines

https://web.archive.org/web/20190429195421/http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/layout-mgt.html

cmidi
  • 1,880
  • 3
  • 20
  • 35