Leero11 Leero11 - 3 months ago 24
Python Question

Python/Tkinter - Using multiple classes, causes infinite loop when inheriting

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.

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

Here is an example 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()


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

Thanks for the help

Answer

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

BTW, method is a confusing name for a class. Also, class names in Python are conventionally written in CamelCase.


Here's a modified version of your code that illustrates what I mean.

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()
Comments