pythontkintercanvas

How can i resize a canvas in tkinter when rescaling the window?


I want to dynamically resize my canvas in tkinter whenever the window is resized(when dragging a corner or pressing fullscreen button). The issue is whenever i try to do so, it seems to cause an infinite loop as trying to change the size of the canvas still calls the resize function.

I am forced to use a wrapper made by my professor, and so cannot create my own canvas class as that would most likely break the rest of the wrapper and cause problems when grading.

I tried to bind a custom onResize function to the configure event of the canvas. The issue, as previously mentioned, is that i need to call __canvas.configure() inside the onresize funtion which causes an infinite loop.

import SimpleGraphics as SG

def onResize(event):
    if event.height and event.width:
        SG.__canvas.config(width=event.width, height=event.height)
        SG.clear()

def main():
    root = SG.__master
    root.bind("<Configure>", onResize)

if __name__ == "__main__":
    main()

Solution

  • The highlightthickness of Canvas is set to 2 (pixels) by default.

    If the width and height of the canvas are set to the same as the window, the final width and height of the window will be width+4 and height+4 respectively and so the resize event will be triggered again.

    You can set the highlightthickness of Canvas to 0:

    def main():
        SG.__canvas.config(highlightthickness=0)
        ...