Python tkinter Canvas Not Doing Anything

Viewed 52

I'm trying to make a grid with a canvas using tkinter and after I made some change the lines stopped being drawn. I'm not sure what I did but it might have to do with how the Canvas object is nested in the Frame object, but it was working just fine like that at one point.

I also tried using shapes and couldn't get them to draw.

    from tkinter import *
    
    class Application(Frame):
        def __init__(self):
            super().__init__()
            self.initUI()
            
        def initUI(self):
            self.canvas = CanvasClass()
    
    class CanvasClass(Canvas):
        def __init__(self):
            super().__init__()
            self.CanvasHeight = 600
            self.CanvasWidth = 800
            self.c = Canvas(width=self.CanvasWidth, height=self.CanvasHeight)
            self.CreateBackground(20)
            self.c.pack(expand=True)
                
        def CreateBackground(self, d):
            print(self.CanvasHeight)
            print(self.CanvasWidth)
            for x in range(d, self.CanvasWidth, d):
                print(x)
                self.create_line(x, 0, x, self.CanvasHeight)
    
    
    
    root = Tk()
    root.title = "TESTING"
    
    app = Application()
    app.canvas.create_polygon(50,200,50,200)
        
    root.mainloop()
1 Answers
from tkinter import *

class Application(Frame):
    def __init__(self,p):
        super().__init__(p)
        self.initUI()
        
    def initUI(self):
        self.canvas = CanvasClass(self)
        self.canvas.pack()#1

class CanvasClass(Canvas):
    def __init__(self,p):#2
        super().__init__(p)
        self.CanvasHeight = 600
        self.CanvasWidth = 800
        self.c = Canvas(width=self.CanvasWidth, height=self.CanvasHeight)
        self.CreateBackground(20)
        self.c.pack(expand=True)            
    def CreateBackground(self, d):
        print(self.CanvasHeight)
        print(self.CanvasWidth)
        for x in range(d, self.CanvasWidth, d):
            print(x)
            self.create_line(x, 0, x, self.CanvasHeight)
root = Tk()
root.title = "TESTING"
app = Application(root)
app.canvas.create_polygon(50,200,50,200)
app.pack()#3
root.mainloop()

you forgot to add the parent and insert it into the window I have used pack() you can change if you want. and I got grids of lines in the window at the bottom when I execute after packing

Related