[Python] Shrink tkinter Text widget to text dimension

Discussão em 'Python' iniciado por Stack, Abril 30, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to shrink a Text widget to the size of the text inside. In fact, if you run the following example code:

    import tkinter as tk

    root = tk.Tk()
    testText = tk.Text(master=root)
    testText.insert(index="1.0", chars="short string")

    testText.tag_configure(tagName="center", justify="center")
    testText.tag_add("center", "1.0", tk.END)

    testText.grid(row=0, column=0, sticky=(tk.N, tk.E, tk.S, tk.W))

    root.mainloop()


    a big Text is created, way bigger than the "short string" inside:

    [​IMG]

    I'm trying to find a way to shrink the Text widget to the size of the text it contains, in order to get a window just a little larger than the text inside it.

    I've tried to solve fixing the dimensions of the Text explicitly specifying width/height and then using grid_propagate(False) and using a "wrapper" Frame containing the Text and then fixing its dimensions (again) explicitly specifying width/height and then using grid_propagate(False) but nothing worked the way I would like it. I didn't manage to get the Text shriking and expanding dinamically based on the text inside.

    Could someone suggest me a good way to do this?

    I thought about using a label, but I have to format the text in a specific way. For example I have to format a word in bold text and the rest of the sentence in standard text. So, as I read in this question I decided to used a Text

    Continue reading...

Compartilhe esta Página