mrksharif
mrksharif

Reputation: 89

Dynamically Adjustable Tkinter Text Widget

I'm trying to create a a text widget that its height adjusts dynamically to fit the content as the user types. My code is:

import tkinter as tk

def update_text_height(event):
    # Update the height of the text widget to fit the content
    root.after(10, lambda: text_widget.configure(height=int(text_widget.index('end').split('.')[0])))


root = tk.Tk()

text_widget = tk.Text(root, wrap='word', height=1, background='black', foreground='white')
text_widget.grid(row=0, column=0, sticky='ew')

label_widget = tk.Label(root, text="Label Widget")
label_widget.grid(row=1, column=0, sticky='w')

text_widget.bind('<KeyRelease>', update_text_height)

root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

text_widget.grid_propagate(False)

root.mainloop()

But the problem is that the height of the widget is only increased when inserting a new line by new line character, and it cannot take into account the display lines resulted by wrapping the text. How can I solve this?

Upvotes: 0

Views: 74

Answers (1)

acw1668
acw1668

Reputation: 47085

You can use Text.count() to get the displaylines instead:

def update_text_height(event):
    # Update the height of the text widget to fit the content
    lines = text_widget.count("1.0", "end", "displaylines")[0]
    root.after(10, lambda: text_widget.configure(height=lines))

Refer to the document on Text.count() for details.

Upvotes: 2

Related Questions