[Python] How can I setup the virtual grid?

Discussão em 'Python' iniciado por Stack, Maio 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make a grid system for my tkinter window. I do not know how to do this correctly. This would be a system where I can enter something like 2,2 and it puts it on the grid (with larger squares in this grid).

    import tkinter as tk

    class Trk:
    def __init__(self,win,blocksx,blocksy,bg="#232627"):
    self.screenwidth = win.winfo_screenwidth()
    self.screenheight = win.winfo_screenheight()
    self.canvas = tk.Canvas(win,width=self.screenwidth,height=self.screenheight,background=bg)
    self.canvas.pack()
    self.background = bg
    self.parent = win
    self.winwidth = win.winfo_width()
    self.winheight = win.winfo_height()
    self.width = self.canvas.winfo_width()
    self.height = self.canvas.winfo_height()
    self.blockx = blocksx
    self.blocky = blocksy
    def coordinate(self,row,col):
    """
    Gets the coordinates
    of a certain block.
    """
    row -= 1
    col -= 1
    if row > self.blockx or col > self.blocky or row < 0 or col < 0:
    "raise positionError"
    x = col * (self.width / self.blockx)
    y = row * (self.height / self.blocky)
    print(f"Coordinates for block ({row}, {col}): ({x}, {y})")
    return x, y
    def addLine(self,row1,col1,row2,col2,color="white",width=0.5):
    row1,col1 = self.coordinate(row1,col1)
    row2,col2 = self.coordinate(row2,col2)
    self.canvas.create_line(row1,col1,row2,col2,fill=color,width=width)
    self.canvas.update()


    The coordinate function should split the window into blockx columns and blocky rows, to make a grid that isn't there psychically but can be used to align items (like using addLine()). It does not split correctly and isn't relative to the windows size and what the Trk class is called with. What is the correct equation? 1,1 would be equal to 0,0 in tkinter coordinates. And Trk.blockx and Trk.blocky would be equal to how many blocks there are, so blockx, blocky would be the bottom-right.

    To debug, use the coordinate function to get the minimum and maximum coordinates:

    from tkinter import *
    from terkinter import *
    parent = tk.Tk()
    canv = Trk(parent,20,40) # these are maximum coordinates
    print(canv.coordinate(1,1)) # should be top-left
    print(canv.coordinate(20,40)) # maximum coordinates, should be bottom right
    # also try adjusting the maximum coordinates to make sure that they can be adjusted.

    parent.mainloop()

    Continue reading...

Compartilhe esta Página