change text direction right to left

1.5k Views Asked by At

I'm using Tkinter, and I'm trying to change Text widget direction (when user type - it will be RTL) for languages such as Hebrew and Arabic.

How could I allow ctrl + shift so text direction would change rtl & ltr?

Or there is another way to do it?

1

There are 1 best solutions below

0
On

I have a work in progress example for you.

Here I create 2 labels based on a list. We can then change the format of the text with a method that will flip the text. I feel like it should switch back to LTR and anchor back to the left but that part is not working for some reason. I will continue to work on it but if someone knows why that is let me know.

import tkinter as tk


class Example(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.columnconfigure(0, weight=1)
        self.testing_frame = tk.Frame(self)
        self.testing_frame.grid(row=0, column=0, stick="nsew")
        self.testing_frame.columnconfigure(0, weight=1)

        self.list_of_items = ["Word to be reversed!", "Some other words to be reversed!"]
        self.list_of_labels = []
        for ndex, item in enumerate(self.list_of_items):
            self.list_of_labels.append([tk.Label(self.testing_frame, text=item, anchor="w"), "ltr"])
            self.list_of_labels[ndex][0].grid(row=ndex, column=0, sticky="ew")

        self.bind("<Control-Shift_L>", self.flip)

    def flip(self, event):
        for item in self.list_of_labels:
            if item[1] == "ltr":
                item[0].config(text=item[0]["text"][::-1], anchor="e")
                item[0].grid(sticky="ew")
                item[1] = "rtl"
            else:
                item[0].config(text=item[0]["text"][::-1], anchor="w")
                item[0].grid(sticky="ew")
                item[1] = "ltr"


if __name__ == "__main__":
    Example().mainloop()

Results:

enter image description here

enter image description here

Now with weights!

enter image description here

enter image description here