pythontkinterwidthdata-entry

Set width of entry object in an optimal way the string is fully visible


I have following code:

from tkinter import *
from tkinter import simpledialog

def resize(lbl):
    USER_INP = simpledialog.askstring(title="User input",
                                  prompt="Please enter your message here:")
    lbl['state'] = 'normal'
    lbl.insert(0, f"Text was \'{USER_INP}\'.")
    lbl['state'] = 'readonly'
    lbl['width'] = 50



top = Tk()
lbl_entry = Entry(top, state="readonly", justify='center', width=10)
lbl_entry.grid(column=0, row=1)


bt_adjust = Button(top, text = "Resize Entry", command=lambda:resize(lbl_entry))
bt_adjust.grid(column=0, row=0)

top.mainloop()

After pressing the button bt_adjust the width of the Entry object is adjusting automatically. Is their a way to set the width dynamically in that way the text is fully displayed on the Entry element but if the width would be a little smaller the text wouldn't be fully displayed anymore?


Solution

  • Does this help? By using len() to adjusting automatically resizing.

    After pressing the button bt_adjust the width of the Entry object is adjusting automatically.

    code in line 10:

    lbl['width'] = f'{len(USER_INP)}
    

    Screenshot before resizing:

    enter image description here

    AScreenshot after resizing:

    enter image description here