Friday, July 15, 2022

Grid on Tkinter Canvas

 (.env) boris@boris-All-Series:~/GRIDHYPER$ cat gridTkinterCanvas.py

from tkinter import *

from random import *

window = Tk()

window.title('Grid on Tkinter Canvas')

def create_grid(window):

  width = 800 

  height = 600 

  canvas = Canvas(window, background='orange', width=width, height=height)

  for line in range(0, width, 15): # range(start, stop, step)

     canvas.create_line([(line, 0), (line, height)], fill='black', tags='grid_line_w')

  for line in range(0, height, 15):

     canvas.create_line([(0, line), (width, line)], fill='black', tags='grid_line_h')

  canvas.grid(row=0, column=0)

create_grid(window)

window.mainloop()





























(.env) boris@boris-All-Series:~/GRIDHYPER$ cat gridTkinterCanvas1.py
import tkinter as tk

def create_grid(event=None):
    w = c.winfo_width() # Get current width of canvas
    h = c.winfo_height() # Get current height of canvas
    c.delete('grid_line') # Will only remove the grid_line
    # Creates all vertical lines at intevals of 15
    for i in range(0, w, 15):
        c.create_line([(i, 0), (i, h)], tag='grid_line')
    # Creates all horizontal lines at intevals of 15
    for i in range(0, h, 15):
        c.create_line([(0, i), (w, i)], tag='grid_line')

root = tk.Tk()
c = tk.Canvas(root, height=600, width=800, bg='light blue')
c.pack(fill=tk.BOTH, expand=True)
c.bind('<Configure>', create_grid)
root.mainloop()































No comments:

Post a Comment