Search code examples
pythonpython-3.xcanvastkintertext-widget

Tkinter: How to set relwidth of a Text widget in a Canvas?


In Tkinter, when you place a Text widget in the main window, you can set the relation between the Text widget's width and the main window's width:

text.place(x = 10, y = 10, relwidth = 0.5)

Is it posible to do the same if the Text widget's parent window is a Canvas widget? I tried to use the Canvas itemconfig() method, but it doesn't work:

text = Text(canvas)
canvas.create_window(10, 10, anchor = NW, window = text)
canvas.itemconfig(text, relwidth = 0.5)

Thanks in advance for your help.


Solution

  • No, explicitly setting a relative width is only available when using place. If you are creating an object on a canvas, it is up to you to do the math to configure the width of the object.

    It's fairly simple to recompute the width of a text widget by binding to the <Configure> event of the canvas, since that event fires whenever the canvas changes size (among other reasons).

    Here's an example that places a text widget on a canvas, and keeps its width at half the width of the canvas. Run the code, and notice that as you resize the window, the text widget is kept at 50% of the width of the canvas.

    import tkinter as tk
    
    class Example():
        def __init__(self):
            self.root = tk.Tk()
            self.canvas = tk.Canvas(self.root, background="bisque")
            self.canvas.pack(fill="both", expand=True)
    
            self.text = tk.Text(self.canvas)
            print("feh:", str(self.text))
            self.canvas.create_window(10, 10, anchor="nw", window=self.text, tags=("text",))
    
            self.canvas.bind("<Configure>", self._canvas_resize)
    
        def _canvas_resize(self, event):
            relwidth = event.width / 2
            self.canvas.itemconfigure("text", width=relwidth)
    
    e = Example()
    tk.mainloop()