0

I've started my adventure with Python only recently, so please go easy on me :D

I've been working on my 2nd program with a gui in tkinter for a couple of days now, and it looks like I've run into a wall.

It's a game that creates a 2D map by making a 2D list.

Each element of the list is created as a Button tkinter object instance with a tile_basic_off image. So far so good.

Should I try to bind each of these buttons to 2 functions for mouse over/mouse leave things go south...

It should work like:

mouse over -> change image to tile_basic_on

mouse leave -> change tile_basic_off

However, once code below is run (there is a function that draws it by .grid() method) everything is the same, with tiles not changing image at mouse over or mouse leave.

Here is the question-wise important piece of code. (note that redMagenta is a var holding an RGB, not a typo)

from tkinter import * #Python 3.4 here


def createMap (): #creates rows x columns 2D list - a map
    global rowsEntryVar, columnsEntryVar, mapList
    mapList = []
    for row in range(rowsEntryVar):
        tempList = []
        for column in range(columnsEntryVar):
            tempList.append(Button(root, bd=0, bg=redMagenta, activebackground=redMagenta))
        mapList.append(tempList)
setTilesProperties()


tileBasicOffImage = PhotoImage(file="Resources/Tile/Tile_basic_off.png")
tileBasicOnImage = PhotoImage(file="Resources/Tile/Tile_basic_on.png")

def turnTileOn (row, column): #changes tile image to On
    global mapList
    mapList[row][column].configure(image=tileBasicOnImage)
    mapList[row][column].image = tileBasicOnImage

def turnTileOff (row, column): #changes tile image to Off
    global mapList
    mapList[row][column].configure(image=tileBasicOffImage)
    mapList[row][column].image = tileBasicOffImage

def setTilesProperties (): #sets basic properties that apply to all tiles
    global mapList, tileBasicOffImage
    for row in range(len(mapList)):
        for column in range(len(mapList[row])):
            mapList[row][column].configure(image=tileBasicOffImage)
            mapList[row][column].bind("<Enter>", turnTileOn(row, column))
            mapList[row][column].bind("<Leave>", turnTileOff(row, column))

What is wrong with my code?

Thanks for help and for not TLDRing this. ;]

  • 1
    This is a very common mistake. See http://stackoverflow.com/q/5767228/7432 – Bryan Oakley Jul 27 '15 at 12:46
  • As Bryan points out, you're actually calling your event handlers when you try to `mapList[row][column].bind()` them. A related issue will be passing them the required arguments because event handlers are only have a single argument passed to them, the event that triggered them, not something like `row, column`. – martineau Jul 27 '15 at 13:09
  • Oh, I see! I did know that I can't include additional parameters in parenthesis in command option, but failed to realise that the same applies to the bind method. Thanks :) – CyberGeneticist Jul 27 '15 at 21:50

0 Answers0