Search code examples
pythontkintertkinter-canvas

The workspace in Tkitner Canvas is smaller than the widget


I'm trying to output some rectangles with text in a grid. But the second column is not drawn all the way through.

from tkinter import Tk, Canvas, Frame, BOTH

class Flowchart(Frame):
    def __init__(self):
        super().__init__()
        self.pack(fill=BOTH, expand=1)
        self.canvas = Canvas(self)
        self.canvas.pack()

    def rec_with_text(self, x1: int, y1: int, text: str):
        # x1 = x1-50
        my_test = self.canvas.create_text(x1+1, y1, text=text, width=100, anchor="nw")
        coords_text = self.canvas.bbox(my_test)
        print(coords_text)
        self.canvas.create_rectangle(x1, y1, x1+100, coords_text[3], width=2)

def main():
    root = Tk()
    root.geometry("600x600+100+100")
    ex = Flowchart()
    ex.master.title("Рисуем линии 2")
    ex.rec_with_text(100, 100, "There will also be a tex0")
    ex.rec_with_text(300, 100, "There will also be a tex1")
    ex.rec_with_text(300, 200, "There will also be a tex2")
    root.mainloop()

if __name__ == '__main__':
    main()

enter image description here

I am trying to create my own class that will help me to work comfortably with tkinter.Canvas methods. I want the parameters I pass to root.geometry("600x600+100+100") to correspond to the workspace, not the width and height of the widget.


Solution

  • In this case, the problem is the opposite: the canvas is smaller than the workspace. The problem is that you aren't instructing pack to fill the frame with the canvas, so the canvas stays at its original size. You can easily visualize this by temporarily giving the canvas a distinctive background color.

    The simple solution is to do this:

    self.canvas.pack(fill="both", expand=True)
    #                ^^^^^^^^^^^^^^^^^^^^^^^^