python-tkinter-用矩形制成的网格中的矩形着色问题

前端之家收集整理的这篇文章主要介绍了python-tkinter-用矩形制成的网格中的矩形着色问题 前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在尝试在python中编写寻路算法.用户应该通过将鼠标悬停在字段上并按s来选择起点.现在,该字段应更改颜色.

但是,我无法弄清楚我的代码出了什么问题.我只能为左上角到右下角的字段上色.在代码中,我在控制台中打印出了objectID,这表明我创建矩形的方式可能存在问题.

我在Window类的draw_grid方法中创建矩形,并在select_start_node方法中为字段着色.

import tkinter as tk


class Window:
    def __init__(self):
        self.height = 600
        self.width = 600
        self.grid_list = {x for x in range(0,600)}
        self.grid = []
        self.grid_dict = {}
        self.root = tk.Tk()
        self.root.geometry("600x600")
        self.root.resizable(False,False)
        self.canvas = tk.Canvas(self.root,width=self.width,height=self.height,background="white")
        self.canvas.bind("s",self.select_start_node)
        self.canvas.bind("<1>",lambda event:
        self.canvas.focus_set())

    def draw_grid(self):
        print(self.grid)
        for x in self.grid_list:
            if x % 30 == 0:
                self.grid.append(x)
            else:
                pass
        print(self.grid)

        for x in self.grid:
            for y in self.grid:
                print(x,y+30)
                rec = self.canvas.create_rectangle(x,x,y+30,y+30)

        self.canvas.pack()

    def select_start_node(self,event):
        print(event.x,event.y)
        x = self.canvas.canvasx(event.x)
        y = self.canvas.canvasy(event.y)
        item = self.canvas.find_closest(x,y)
        p = self.canvas.coords(item)
        print(item)
        print(p)
        self.canvas.create_rectangle(p[0],p[0],p[0]+30,fill="red")


def main():
    node_list = []
    cord_list = []
    window = Window()
    window.draw_grid()
    window.root.mainloop()

if __name__ == "__main__":
    main()
最佳答案
我不了解您的游戏整体设计,但建议您在矩形网格方面做些不同的事情.在下面的代码中,self.grid是二维列表列表,每个条目都是Canvas矩形对象.这使得相对应地选择和更改其中之一,因为canvas.find_closest(x,y)将直接为您提供关联的矩形对象的对象ID,这使得更改其填充颜色变得微不足道.

因此,我也对其进行了更改,因此您只需单击一个矩形即可对其进行更改,而无需移动鼠标光标然后按任意键.

还要注意,我也摆脱了大部分在各处使用的硬编码数字常量,这使代码更加灵活,以防您以后决定更改其中一个.

import tkinter as tk


class Window:
    def __init__(self):
        self.cell_size = 30
        self.height = 600
        self.width = 600
        self.hz_cells = self.width // self.cell_size  # Number of horizontal cells.
        self.vt_cells = self.height // self.cell_size  # Number of vertical cells.

        # Preallocate 2D grid (list-of-lists).
        self.grid = [[None for _ in range(self.hz_cells)] 
                               for _ in range(self.vt_cells)]
        self.root = tk.Tk()
        self.root.geometry("%sx%s" % (self.width,self.height))
        self.root.resizable(False,background="white")
        self.canvas.pack()
        self.canvas.bind("<1>",self.select_start_node)

#        You can still do it this way if you want.
#        self.canvas.bind("s",self.select_start_node)
#        self.canvas.bind("<1>",lambda event: self.canvas.focus_set())    

    def draw_grid(self):
        """ Fill Canvas with a grid of white rectangles. """
        for i in range(self.hz_cells):
            x = i * self.cell_size
            for j in range(self.vt_cells):
                y = j * self.cell_size
                self.grid[i][j] = self.canvas.create_rectangle(
                    x,y,x+self.cell_size,y+self.cell_size,fill="white")

    def select_start_node(self,event):
        """ Change the color of the rectangle closest to x,y of event. """
        x = self.canvas.canvasx(event.x)
        y = self.canvas.canvasy(event.y)
        selected_rect = self.canvas.find_closest(x,y)
        if selected_rect:
            self.canvas.itemconfigure(selected_rect,fill="red")  # Change color.


def main():
    node_list = []
    cord_list = []
    window = Window()
    window.draw_grid()
    window.root.mainloop()

if __name__ == "__main__":
    main()
原文链接:https://www.f2er.com/python/533246.html

猜你在找的Python相关文章