Advertisement
here2share

# Tk_array_click.py

Sep 28th, 2016
200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.98 KB | None | 0 0
  1. # Tk_array_click.py
  2.  
  3. try:
  4.     # Python2
  5.     from Tkinter import *
  6. except ImportError:
  7.     # Python3
  8.     from tkinter import *
  9. #
  10. r,c=8,8
  11. grid=[[-1]*r  for n in range(c)] # list comprehension
  12. grid[0][0]=1
  13. grid[7][7]=1
  14.  
  15. w=70 # width of each cell
  16.  
  17. root=Tk()
  18. root.geometry('{}x{}+0+0'.format(w*r,w*c)) #.format(root.winfo_screenwidth())
  19. root.title('2D')
  20. canvas=Canvas(root, width=1200, height=1200, background='grey')
  21.  
  22. def draw_grid():
  23.     x,y=0,0 # starting position
  24.  
  25.     for row in grid:
  26.         for col in row:
  27.           color='white'
  28.           if col == 1:
  29.               color='red'
  30.           canvas.create_rectangle(x, y, x+w, y+w, fill=color)
  31.           x+=w
  32.         y+=w
  33.         x=0
  34. #
  35. def mouse(event):
  36.     x,y=event.x/w,event.y/w
  37.     print
  38.     print "clicked at", event.x, event.y, '\t\t',(x,y)
  39.     grid[y][x]=-1 * grid[y][x] # Note: grid[Y][X] not grid[X][Y]
  40.     color='white'
  41.     if grid[y][x] == 1: color='red'
  42.     x*=w
  43.     y*=w
  44.     canvas.create_rectangle(x, y, x+w, y+w, fill=color)
  45. #
  46.  
  47. canvas.bind("<Button-1>", mouse)
  48. draw_grid()
  49. canvas.pack()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement