Python/Tkinter - Using multiple classes, causes infinite loop when inheriting
<p>I am doing a bigger tkinter application and because the size of the application is quite big I have tried to divide the application to different classes and methods for making it clearer.</p>

<p>The problem is that because the subclasses I have made are inheriting from the main class their initiation function causes an infinite loop.</p>

<p>Here is an example code:</p>

<pre><code>import tkinter as tk
import random

class main_window(object):

    def __init__(self):

        self.root = tk.Tk()

        self.cv = tk.Canvas(self.root, height = 400, width = 400)
        self.cv.pack()

        self.button1 = tk.Button(text="draw line", command=method().draw_line)
        self.Solve_button_window = self.cv.create_window(5, 5, anchor=tk.NW,  window=self.button1)

        self.root.mainloop()

class method(main_window):

    def __init__(self):
        super().__init__() #Sublclassing from main_window class causes an infinite loop

        self.point1 = 0
        self.point2 = 0


    def draw_line(self):

        self.point1 = random.randrange(10, 400)
        self.point2 = random.randrange(10, 400)

        self.cv.create_line(self.point1, self.point2)




main_window()
</code></pre>

<p>How can I change this code that the subclasses won't cause an infinite loop?</p>

<p>Thanks for the help</p>

<p>Your <code>method</code> class shouldn't inherit from the <code>main_window</code> class. Just create an instance of <code>main_window</code> and pass it into the <code>__init__</code> of <code>method</code>.</p>

<p>BTW, <code>method</code> is a confusing name for a class. Also, class names in Python are conventionally written in CamelCase.</p>

<hr>

<p>Here's a modified version of your code that illustrates what I mean.</p>

<pre><code>import tkinter as tk
import random

class MainWindow(object):
    def __init__(self):
        self.root = tk.Tk()

        self.cv = tk.Canvas(self.root, height = 400, width = 400)
        self.cv.pack()

        draw_stuff = DrawStuff(self)

        self.button1 = tk.Button(text="draw line", command=draw_stuff.draw_line)
        self.Solve_button_window = self.cv.create_window(5, 5, anchor=tk.NW,  window=self.button1)

        self.root.mainloop()

class DrawStuff(object):
    def __init__(self, mainwin):
        self.mainwin = mainwin
        self.cv = mainwin.cv

    def draw_line(self):
        self.point1 = (random.randrange(10, 400), random.randrange(10, 400))
        self.point2 = (random.randrange(10, 400), random.randrange(10, 400))
        self.cv.create_line(self.point1, self.point2)

MainWindow()
</code></pre>

python inheritance tkinter infinite-loop subclassing