Tatli
Tatli

Reputation: 13

Python 3 binding not working

Somehow only 2 of my bindings work(left and right mousebutton). I've done quite a few bindings in my previous programmes, but still, I have no idea why this doesn't work. Could somebody help me?

class Window:
    def __init__(self):
        self.win=Tk()
        self.can=Canvas(self.win, height=800, width=800, bg="grey90")
        self.can.grid(row=0, column=0)

class Player:
    def __init__(self, bind1, bind2):
        win.can.bind(bind1, self.moveleft)
        win.can.bind(bind2, self.moveright)
    def moveleft(event, self):
        print("left")
    def moveright(event, self):
        print("right")

class Manage:
    def __init__(self, numofplayers):
        self.numofplayers=numofplayers
        self.players=[]
        self.bindings1=["<Left>", "<Button-1>", "<a>", "<m>"]
        self.bindings2=["<Right>", "<Button-3>", "<s>", "<n>"]
        self.start()
    def start(self):
        for i in range(self.numofplayers):
            self.players.append(Player(self.bindings1[i], self.bindings2[i]))

Upvotes: 1

Views: 151

Answers (1)

Lafexlos
Lafexlos

Reputation: 7735

Focus is on Tk() window so canvas doesn't catch key presses. To make canvas catch key presses, you need to focus_set() on canvas.

class Window(object):
    def __init__(self):
        self.wind=Tk()
        self.can=Canvas(self.wind, height=800, width=800, bg="grey90")
        self.can.grid(row=0, column=0)
        self.can.focus_set()

I put there just to demonstrate. You should choose appropriate place depending on your code.

Upvotes: 2

Related Questions