Search code examples
pythonpython-3.xtkintertkinter-scrolledtext

How can I align scrolled text to the right?


The problem is simple. The scrolled text box will be written into it in Arabic. So I need to align the text whenever I type to the right of the box. There isn't any attribute, such as justify. Also I used a tag, but I couldn't do it.

show_note = scrolledtext.ScrolledText(canvas, width=int(monitorWidth / 65), height=int(monitorHeight / 130),
                                      font=("Times New Roman", 14))

canvas.create_window(cord(0.45, 0.65), window=show_note, anchor="ne")

Is there an alternative to the scrolled text control, but that has these attributes (width, height, justify and can write into multiple lines)?


Solution

  • I did some searching and could not find any other way to do this, than to bind each keypress to a function, that adds/edits the tag to select all the item from the text box:

    from tkinter import *
    from tkinter import scrolledtext
    
    root = Tk()
    
    def tag(e):
        text.tag_add('center','1.0','end')
    
    text = scrolledtext.ScrolledText(root)
    text.pack()
    text.tag_config('center',justify='right')
    
    text.bind('<KeyRelease>',tag)
    
    root.mainloop()
    

    You can also make your custom widget that does this, instead of repeating code for each file, so a more better form would be:

    from tkinter import *
    from tkinter import scrolledtext
    
    root = Tk()
    
    class JustifyText(scrolledtext.ScrolledText):
        def __init__(self,master,*args,**kwargs):
            scrolledtext.ScrolledText.__init__(self,master,*args,**kwargs)
            self.tag_config('center',justify='right')
            
            self.bind('<KeyRelease>',self.tag)
    
        
        def tag(self,e):
            text.tag_add('center','1.0','end')
    
    text = JustifyText(root)
    text.pack()
    
    
    root.mainloop()
    

    And yes you can make this more perfect by taking the current width of text box and shifting the insertion cursor to that point, to make it start from that point.