首页 > 解决方案 > 我似乎无法向按钮网格添加功能 - tkinter

问题描述

我使用循环创建了一个按钮网格。

for i in range(600//25):
    for j in range(1000//25):
        btns = Button(frame_main , height = 1 , width = 2 , bg = "grey" , command = lambda : clicked(btns , check))
        btns.grid(row = i , column = j)

而且我似乎无法为每个单独的按钮添加一个事件,它只将它添加到它的最后一个实例,这是有道理的,但我不知道如何单独引用每个按钮。

这是函数的代码。它并不完整,但我只是想让第一部分首先为每个单独的按钮工作。

check = 0

def clicked(obj , check):
    if selection_var.get() == 2 :
        if check != 0 :
            messagebox.showerror("Error","You have already selected a start point")
        else :
            check += 1
            obj.config(bg = "green")

标签: pythontkinter

解决方案


你可以使用某物。像这样:

def clicked(i,j):
    # do_stuff

然后

class Click:
    def __init__(self, *data):
        self.data = data
    def __call__(self):
        clicked(*self.data)

最后:

for i in range(600//25):
    for j in range(1000//25):
        btns = Button(frame_main , height = 1 , width = 2 , bg = "grey" , command = Click(i,j))
        btns.grid(row = i , column = j)

希望这会有所帮助!


推荐阅读