Search code examples
pythontkinter

Dynamic sizing Tkinter canvas text


I am talking specific to python Tkinter, I have text along with a button in-lined and I am using pixel coordinates. Now my text string is changing dynamically, but if the text string is long then it overflows.

So I want if there any way if I can change the coordinates based on text length

For example:

canvas.create_text(20, 30, anchor=W, font="Purisa",
    text="Most relationships seem so transitory")

If I use something like this

canvas.create_text(20+len(text), 30, anchor=W, font="Purisa",
    text="Most relationships seem so transitory")

I am very new to tkinter and got a code to debug which is very tight, so I cannot change it dynamically in first place


Solution

  • You can pass the "width" in create_text to avoid overflow.

    width=Maximum line length. Lines longer than this value are wrapped. Default is 0 (no wrapping).
    

    so it will be something like this

    canvas.create_text(20, 30, anchor=W, font="Purisa",
         text="Most relationships seem so transitory", width=0)
    

    you can calculate the width based on the text size or make it fix, then if it is longer than it will be wrapped and there won't be any overflow.