2016-11-12 21 views
2

我想按此網格上的任何方塊,並且我想讓它變成黃色。但我只能使用itemconfig創建黃色的最新塊。我該怎麼辦?如何區分畫布上的python中的對象

from tkinter import * 

master = Tk() 

canv = Canvas(master, width=200, height=100) 
canv.pack() 

def select(event): 
    print("Coordinates:", event.x, ",",event.y) 
    canv.itemconfig(grid,fill="yellow") 

y=1 
for i in range(1,6): 
    for j in range(0,10): 
     grid=canv.create_rectangle(1+(20*j),y,20+(20*j),20+y,fill="red") 
     canv.tag_bind(grid,'<Button-1>',select) 
    y+=20 


mainloop() 

回答

0

一些試驗後,我來到了這個解決方案:

from Tkinter import * 

master = Tk() 

canv = Canvas(master, width=200, height=100) 
canv.pack() 

def select(event, grid): 
    print("Coordinates:", event.x, ",",event.y) 
    canv.itemconfig(grid,fill="yellow") 

y=1 
for i in range(1,6): 
    for j in range(0,10): 
     grid=canv.create_rectangle(1+(20*j),y,20+(20*j),20+y,fill="red") 
     canv.tag_bind(grid, '<Button-1>', lambda event, var=grid: select(event, var)) 
    y+=20 

mainloop()