Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3934304
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 19, 20262026-05-19T23:42:02+00:00 2026-05-19T23:42:02+00:00

I am new to Tkinter and am writing a simple tile flipping game to

  • 0

I am new to Tkinter and am writing a simple tile flipping game to learn the basics. The idea is that when I start the app i get a “start new game” button, quit button and a grid size slider. I can then select a grid size and hit start which brings up a n*n grid of red or green buttons (tiles) . By clicking on one i change the colour of the tile and each of the 4-way connected tiles. Once all of the tiles are green, the tiles should disappear. Allowing me to start a new game.

So here’s the problem, when I win a game and start a new one or start a new game while one is in progress, the new tiles come up but when I click on one of them i get the following :

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1413, in __call__
    return self.func(*args)
  File "/home/adejong/workspace/test2/view.py", line 116, in on_click
    self.view.update()
  File "/home/adejong/workspace/test2/view.py", line 84, in update
    button.set_colour(View.UP)
  File "/home/adejong/workspace/test2/view.py", line 112, in set_colour
    self.gridButton.config(bg=colour)
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1205, in configure
    return self._configure('configure', cnf, kw)
  File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1196, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
TclError: invalid command name ".33325424.33325640.33327872"

I’m pretty sure its something to do with how I am clearing the grid but I can’t figure out what the problem is. I originally could not get the buttons to show when I started a new game, so it may be something to to with that.

Here’s the module where it’s happening:

# @todo make wrappers for all Tkinter widgets
from Tkinter import *
from observerPattern import Observer
# USE Grid to organise widgets into a grid
class View(Observer):
    UP = "red"
    DOWN = "green"

    ## @brief initialises the GUI
    # @param master ie the root
    #@ model, a pointer to the model
    def __init__(self, master, model):

        View.instance = self
        self.model = model
        self.master = master

        self.frame = Frame(self.master)
        self.frame.grid() #size frame to fit the given text, and make itself visibl
        self.optionsGrid = Frame(self.frame)
        self.gameGrid = Frame(self.frame)
        self.optionsGrid.grid(row = 0, column = 0)
        self.gameGrid.grid(row = 1, column = 0)

        self.gridSizeScale = Scale(self.optionsGrid, label = "grid size", from_ = 2, to = 20, bigincrement = 1, 
                                   showvalue = True, orient = HORIZONTAL) 

        self.quit = Button(self.optionsGrid, text="QUIT", fg="red", command=self.frame.quit)


        self.newGame = Button(self.optionsGrid, text="Start New Game", command=self.init_game)
        self.objective = Label(self.optionsGrid, text="Make all the tiles green")

        self.newGame.grid(row=0, column=0)
        self.quit.grid(row=0, column=3)
        self.gridSizeScale.grid(row=0, column=1, columnspan=2)
        self.objective.grid(row=1, column=1, columnspan=2)
        self.gameButtons = []
        self.update()

    # start a new game by re building the grid
    def init_game(self):
        size = self.gridSizeScale.get()
        self.model.init_model(size)
        self.objective.config(text = "Make all the tiles green")
        print "MODEL INITIALISED"

        #for i in range(len(self.gameButtons)):
        #    self.gameButtons[i].grid_forget()
        for button in self.gameButtons:
                #button.destroy()
                #self.gameGrid.grid_forget(button)
                button.__del__()

        for button in range(size * size):
            buttonRow = int(button / size)
            buttonCol = button % size

            state = self.model.getTileState(buttonRow, buttonCol)
            if state == self.model.UP:
                initialColour = View.UP
            else:
                initialColour = View.DOWN

            newButton = GridButton(self.gameGrid, butRow = buttonRow, butCol = buttonCol, initColour = initialColour, model = self.model, view = self )

            self.gameButtons.append(newButton)
            print self.gameButtons
        self.gameGrid.grid()




    ## @brief gets the only View instance. A static method. Dont really need this
    # @param None
    # @returns the singleton View object     
    @staticmethod
    def getInstance():
        if hasattr(View, 'instance') and View.instance != None:
            return View.instance
        else:
            return View()

    # make sure the tiles are the right colour etc    
    def update(self):
        for button in self.gameButtons:
            state = self.model.getTileState(button.row, button.col)
            if state == self.model.UP:
                button.set_colour(View.UP)
            else:
                button.set_colour(View.DOWN)
        if self.model.check_win() == True and self.model.tilesInitialised:
            for button in self.gameButtons:
                #button.destroy()
                #self.gameGrid.grid_forget(button)
                button.__del__()

            #self.gameGrid.grid_forget()
            print "slaves", self.gameGrid.grid_slaves()
            self.objective.config(text = "You Win!")
            self.master.update()
            print "YOU WIN!"

# a wrapper i made so i could pass parameters into the button commands
class GridButton(Button):

    def __init__(self, master, butRow, butCol, initColour, model, view, *args, **kw):
        Button.__init__(self, master)
        self.gridButton = Button(master, command=self.on_click, *args, **kw)
        self.gridButton.grid(row = butRow, column = butCol )
        self.set_colour(initColour)
        self.row = butRow
        self.col = butCol
        self.model = model
        self.view = view

    def set_colour(self, colour):
        self.gridButton.config(bg=colour)

    def on_click(self):
        self.model.flip_tiles(Row = self.row, Col = self.col)
        self.view.update()

    def __del__(self):
       self.gridButton.destroy()
       del self

Here’s the reset for completion

from Tkinter import *
from model import Model
from view import View
from controller import Controller
import sys

root = Tk() #enter the Tkinter event loop


model = Model()
view = View(root, model)
#controller = Controller(root, model, view)
root.mainloop()

from Tkinter import *
import random

class Model:
    UP = 1
    DOWN = 0
    def __init__(self, gridSize=None):
        Model.instance = self
        self.init_model(gridSize)

    def init_model(self, gridSize):
        self.size = gridSize
        self.tiles = []
        self.won = False
        self.tilesInitialised = False
        if gridSize != None:
            self.init_tiles()


    ## @brief gets the only Model instance. A static method
    # @param None
    # @returns the singleton Model object     
    @staticmethod
    def getInstance(gridSize = None):
        if hasattr(Model, 'instance') and Model.instance != None:
            return Model.instance
        else:
            return Model(gridSize)

    #initially init tile vals randomly but since not all problems can be solved
        # might want to start with a soln and work backwards

    def init_tiles(self):
        # i should also make sure they're not all 0 to start with
        self.tiles = []
        for row in range(self.size):
            rowList = []
            for col in range(self.size):
                rowList.append(random.randint(Model.DOWN, Model.UP))
            self.tiles.append(rowList)
        self.check_win()
        if self.won == True:
            self.init_tiles()
        self.tilesInitialised = True

    # tile indexing starts at 0            
    def flip_tiles(self, selected = None, Row = None, Col = None):
        if selected == None and (Row == None and Col == None):
            raise IOError("Need a tile to flip")
        elif selected != None:
            neighbours = self.get_neighbours(selected)

            for r in neighbours:
                for c in r:
                    if self.tiles[r][c] == Model.DOWN:
                        self.tiles[r][c] = Model.UP
                    elif self.tiles[r][c] == Model.UP:
                        self.tiles[r][c] = Model.DOWN

        else:
            selectedTile = Row, Col
            neighbours = self.get_neighbours(selectedTile)
            for tile in neighbours:
                    r = tile[0]
                    c = tile[1]
                    if self.tiles[r][c] == Model.DOWN:
                        self.tiles[r][c] = Model.UP
                    elif self.tiles[r][c] == Model.UP:
                        self.tiles[r][c] = Model.DOWN

    # selected is a tuple (row, column)  
    # returns a list of tuples of tiles to flip 
    def get_neighbours(self, selected):
        row = selected[0]
        col = selected[1]
        tilesToFlip = []
        for modifier in range(-1,2):
            rowIndex = row + modifier

            if rowIndex < 0:
                pass
            elif rowIndex > self.size - 1 :
                pass
            else:
                final = rowIndex, col
                tilesToFlip.append(final)


        for modifier in range(-1,2):   
            colIndex = col + modifier

            if colIndex < 0:
                pass
            elif colIndex > self.size - 1:
                pass
            else:
                final = row, colIndex
                tilesToFlip.append(final)


        neighbours = set(tilesToFlip)
        return neighbours


    def check_win(self):
        self.won = True
        #everytime a tile is selected
        for row in range(len(self.tiles)):
            for col in range(len(self.tiles)):

                if self.tiles[row][col] == Model.UP:
                    self.won = False
                    break

        return self.won

    def getTileState(self, buttonRow, buttonCol):
        return self.tiles[buttonRow][buttonCol]

Any help would be greatly appreciated

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-19T23:42:03+00:00Added an answer on May 19, 2026 at 11:42 pm

    It looks like you aren’t resetting self.game_buttons. You set it to the empty list in __init__ when you probably should be doing that in init_game. Because it’s not reset, the second time you run the game self.view.update() iterates over a list that contains the buttons from both games. Since half of those buttons are missing, you get an error the first time you try to change the color of a now-deleted button.

    By the way: a real easy way to manage this is to put all the buttons as children of an inner frame. Doing that you can simply delete the frame to delete all of its children. As a side benefit, you don’t need a list of buttons because you can ask the frame (with winfo_children) for all of its children.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm new to python and Tkinter. I'm looking for a small GUI app which
I'm new to Python and I'm trying to create a simple GUI using Tkinter.
Okay, I'm completely new to this. I created a python script that imports tkinter
I'm experimenting with the new ttk Tile enhancements that ship with Python 2.7. Windows
When opening a new tkinter window, I only want the user to be able
new to c#. I'm trying to make a simple system where I can search
I was working on a program,that I need to support new additions. Hmmm. Let
I'm trying to write a simple Arkanoid with the help of Python and Tkinter.
Im running into this error that I can't work out Im writing some code
I'm new to Tkinter and I have some problems getting the desired layout. Here's

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.