首页 > 解决方案 > 如何配置已在该按钮上使用参数的功能中单击的按钮?

问题描述

我需要能够配置在函数内单击的按钮,同时将函数用于多个按钮

我见过人们使用参数来调用函数中按钮的名称,但是我已经将参数用于我的代码的必要部分,所以我无法做到这一点

clicked = 0
def click_place(position):

    while clicked < 6:
        clicked += 1
        place_positions.append(position)
        .config(bg="yellow") #where I need help


#placement buttons
place_buttons = Frame(window)

place_positions = []

but1 = Button(place_buttons, height = 2, width = 5, command= lambda:click_place('A1'))
but1.grid(row = 0, column = 0)

but2 = Button(place_buttons, height = 2, width = 5, command= lambda:click_place('A2'))
but2.grid(row = 0, column = 2)


place_buttons.place(x=250, y=500, anchor=CENTER) 

标签: pythonpython-3.xfunctiontkinterlambda

解决方案


最简单的方法是使用'A1''A2'作为键将按钮存储在字典中

buttons = {
    'A1': but1,
    'A2': but2,
}

然后,鉴于position将设置为'A1'or ,您可以使用'A2'引用按钮。positionbuttons[position]

另一种解决方案是将按钮作为参数传递:

def click_place(position, button):
    ...
...
but1 = Button(place_buttons, height = 2, width = 5)
but1.configure(command= lambda:click_place('A1', but1))
...

推荐阅读