How it works...

First, we initialize the Entry instance with its StringVar variable and the Canvas widget:

        self.var = tk.StringVar()
self.entry = tk.Entry(self, textvariable=self.var)
self.canvas = tk.Canvas(self, bg="white")

Then, we place the widgets by calling the methods for the Pack geometry manager. Note the importance of calling update() on the root window, because we want to force Tkinter to process all the pending changes, in this case rendering the widgets before the __init__ method continues its execution:

        self.entry.pack(pady=5)
self.canvas.pack()
self.update()

We did this because the next step will be to calculate the canvas dimensions, and until the geometry manager has displayed the widget, it will not have the real values of its width and height.

After this, we can safely retrieve the canvas dimensions. Since we want to align the text item with the center of the canvas, we divide the values of width and height by half.

These coordinates determine the position of the item, and together with the styling options, are passed to the create_text() method. The text keyword argument is a common option used here, but we will omit it because it will be dynamically set when StringVar changes its value:

        w, h = self.canvas.winfo_width(), self.canvas.winfo_height()
options = { "font": "courier", "fill": "blue",
"activefill": "red" }
self.text_id = self.canvas.create_text((w/2, h/2), **options)
self.var.trace("w", self.write_text)

The identifier returned by create_text() is stored in the text_id field. It will be used on the write_text() method to reference the item, which is invoked by the tracing mechanism on write operations of the var instance.

To update the text option inside the write_text() handler, we call the canvas.itemconfig() method with the item identifier as the first argument, and then the configuration options.

In our case, we use the text_id field that we stored while initializing our App instance and the contents of StringVar via its get() method:

    def write_text(self, *args):
self.canvas.itemconfig(self.text_id, text=self.var.get())

We defined our write_text() method so that it can receive a variable number of arguments even though we do not need them, because the trace() method of Tkinter variables passes them to the callback functions.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset