Sephixx
Sephixx

Reputation: 167

tkinter shifting canvas when reinitialised

I am trying to create a grid board in tkinter and whenever I press a restart button I want it to create a new grid board on the same position. Instead of redrawing the board I am reinitialising the class.

Problem I have is that it does create a new board for me but the board is shifted down by 50% and I can't figure out why. Below is the code I use, and some images to illustrate my problem. Thanks in advance.

import tkinter as tk
from tkinter import ttk, Tk


class GUI(tk.Frame):    
    def __init__(self):
        super().__init__()
        self.pack(fill=tk.BOTH, expand=True)
        self.canvas = tk.Canvas(self)
        self.create_board()

    def create_board(self):
        for y in range(3):
            for x in range(3):
                x1 = x * 150 + 30
                x2 = x1 + 150
                y1 = y * 150 + 30
                y2 = y1 + 150
                self.canvas.create_rectangle(x1, y1, x2, y2, outline="#090808", fill="#fffdfd")
                self.canvas.pack(fill=tk.BOTH, expand=True)
        button = ttk.Button(self.canvas, text='Restart', command=self.restart)
        button.place(x=150*3/2, y=150*3+50)

    def restart(self):
        self.canvas.destroy()
        self.__init__()


def main():
    root = Tk()
    GUI()
    root.geometry("550x550")
    root.mainloop()


if __name__ == '__main__':
    main()

First time creating the board

When I click restart button

Upvotes: 0

Views: 61

Answers (1)

JacksonPro
JacksonPro

Reputation: 3275

you shouldn't keep calling __init__() method. Instead, it is to be used only during initializing for the first time. One way to get around it is by creating another method and reinitializing it.

Here is the corrected code:

import tkinter as tk
from tkinter import ttk, Tk


class GUI(tk.Frame):    
    def __init__(self):
        super().__init__()
        self.reinitialize()

    def reinitialize(self):
        self.pack(fill=tk.BOTH, expand=True)
        self.canvas = tk.Canvas(self)
        self.create_board()
        
    
    def create_board(self):
        print()
        for y in range(3):
            for x in range(3):
                x1 = x * 150 + 30
                x2 = x1 + 150
                y1 = y * 150 + 30
                y2 = y1 + 150
               
                self.canvas.create_rectangle(x1, y1, x2, y2, outline="#090808", fill="#fffdfd")
                self.canvas.pack(fill=tk.BOTH, expand=True)
        button = ttk.Button(self.canvas, text='Restart', command=self.restart)
        button.place(x=150*3/2, y=150*3+50)

    def restart(self):
        self.canvas.destroy()

        self.reinitialize()
        #self.__init__()



def main():
    root = Tk()
    GUI()
 
    root.geometry("550x550")
    root.mainloop()


if __name__ == '__main__':
    main()

Upvotes: 2

Related Questions