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

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


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 tkclass 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()