[Tkinter-discuss] tag_bind

Michael Lange klappnase at web.de
Tue Mar 28 13:12:09 CEST 2006


On Mon, 27 Mar 2006 18:54:05 +0200
Pavel Kosina <geon at post.cz> wrote:


> >   
> In fact, I tried this too, but the same effect. I got the impression 
> from the documentation that this should be the right method. With 
> binding canvas I do not know, how to bind more than one player,  so that 
> each one could be moved separately.
> 
> 

Hi Pavel,

maybe you could use Canvases as Players. Just for fun I wrote a little "Player" class that
seems to do what you want:

from Tkinter import *

class Player(Canvas):
    def __init__(self, master, x, y):
        Canvas.__init__(self, master, width=12, height=12, bg='white', bd=0, highlightthickness=0, takefocus=1)
        self.master = master
        self.x = x
        self.y = y
        self.tag = master.create_window(x, y, window=self)
        self.oval = self.create_oval(0, 0, 10, 10, fill='blue')
        
        self.bind('<FocusIn>', self._on_focus_in)
        self.bind('<FocusOut>', self._on_focus_out)
        for key in ('<Up>', '<Down>', '<Left>', '<Right>'):
            self.bind(key, self.move)

    def _on_focus_in(self, event):
        self.itemconfigure(self.oval, fill='red')
    
    def _on_focus_out(self, event):
        self.itemconfigure(self.oval, fill='blue')
    
    def coords(self, x=None, y=None):
        if x == None:
            x = self.x
        if y == None:
            y = self._y
        self.x, self.y = x, y
        self.master.coords(self.tag, x, y)
        return x, y
    
    def move(self, event):
        x, y = self.x, self.y
        k = event.keysym
        if k == 'Up':
            y -= 1
        elif k == 'Down':
            y += 1
        elif k == 'Left':
            x -= 1
        elif k == 'Right':
            x += 1
        self.coords(x, y)

##############################################
# test

master=Tk()
myCanvas=Canvas(master, bg="white")
player1 = Player(myCanvas, 20, 20)
player2 = Player(myCanvas, 50, 50)
myCanvas.pack()
player1.focus_set()
mainloop()


More information about the Tkinter-discuss mailing list