Home > Mobile >  How to make Text widgets adaptive in Tkinter?
How to make Text widgets adaptive in Tkinter?

Time:05-01

Ok so let's say I've got a Text object. How can I make it so that it gets an extra line (or height 1) whenever I fill in the current line? like when it starts hiding the left of the line to show you the end?

CodePudding user response:

I couldn't understand your question very well, But I assume that you have problem with wrapping a text. For instance when you reduce the window size, the text should break into multi lines. Here is as example:

import tkinter as tk


class MainWindow(tk.Tk):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.my_label = tk.Label(
            self, text="Helllllooooooooooooooooooooooooo")

        self.my_label.bind('<Configure>',
                           lambda e: self.my_label.config(
                               wraplength=self.my_label.winfo_width()
                           ))

        self.my_label.pack()

        self.mainloop()


if __name__ == '__main__':
    window = MainWindow()

CodePudding user response:

Line breaking, also known as word wrapping, is breaking a section of text into lines so that it will fit into the available width of a page, window or other display area, Read more.

Solution

Tkinter's Text widget have this feature already built in. wrap is the option that will do it.

From the docs:

This option controls the display of lines that are too wide. With the default behavior, wrap=tk.CHAR, any line that gets too long will be broken at any character.

Set wrap=tk.WORD and it will break the line after the last word that will fit.

Example

import tkinter as tk

root = tk.Tk()

text = tk.Text(root, wrap=tk.WORD)
text.pack(fill=tk.BOTH, expand=1)

root.mainloop()
  • Related