开发者

Python Tkinter comparing PhotoImage objects

开发者 https://www.devze.com 2022-12-27 07:32 出处:网络
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 (ei

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 light 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号