tags:

views:

47

answers:

1

In a simple LightsOut game, when I click on a light I need to toggle the image on a button. I'm doing this with Tkinter, so I thought I'd just check and see what image is currently on the button (either 'on.gif' or 'off.gif') and set it to the other one, like this:

def click(self,x,y):
    if self.buttons[x][y].image == self.on:
        self.buttons[x][y].config(image=self.off)
        self.buttons[x][y].image == self.off
    else:
        self.buttons[x][y].config(image=self.on)
        self.buttons[x][y].image == self.on

This ends up always being True - I can turn a lgiht off, but never turn it back on. Did some research, realized that I should probably be using cmp:

def click(self,x,y):
    if cmp(self.buttons[x][y].image,self.on) == 0:
        self.buttons[x][y].config(image=self.off)
        self.buttons[x][y].image == self.off
    else:
        self.buttons[x][y].config(image=self.on)
        self.buttons[x][y].image == self.on

But that gave me the exact same result. Both self.on and self.off are PhotoImage objects. Aside from keeping a separate set of lists which tracks what type of light is in each position and redrawing them every click, is there a way to directly compare two PhotoImage objects like this?

+2  A: 

Pointers

  1. self.buttons[x][y].image == self.off, are you sure you want "==" instead of "="

  2. Comparing images to get what state you are in is not a good way, instead use a variable e.g self._isLightOn and toggle it when you change states, based on this variable set correct images, or text or whatever.

Anurag Uniyal
No, should be using the =. So, this was a simple should have had more coffee this morning problem.
Kyle Schmidt
Also, what's wrong with comparing images to determine state?
Kyle Schmidt
@Kyle Schmidt, comparing images is wrong because image is not state, you may have 10 images in animation for same state, or same image in two states with different text, but more importantly it is better to compare simple objects whose comparison you can predict, otherwise you can have two images which looks same but are not == identical
Anurag Uniyal