Tkinter按钮在for循环中具有相同的命令功能但位置不同

时间:2020-07-28 12:47:47

标签: python loops user-interface button tkinter

我正在尝试创建五个按钮,其中每个按钮调用相同的功能,以更新您所按按钮的图像(实际上是五个相同的按钮,但位置不同)。但是,只有最后创建的按钮才能在GUI中实际工作。这与thisthis密切相关。我尝试了这些线程中给出的答案,但由于某些原因它们无法正常工作。

我觉得我错过了一件非常简单的事情,通常是这样。

这是代码:

def drawCard():

    global cards
    global last_card
    img = Image.open(cards_path + "/" + cards[0])
    img = ImageTk.PhotoImage(img)
    del cards[0]

    last_card = img



def createFiveButtons():

    global last_card
    buttons = []

    def updateCard(n):
    
        print("Updated")
        drawCard()
        buttons[n].configure(image = last_card)

    for i in range(2):
        drawCard()
        buttons.append(tk.Button(root, text = "Draw a card", fg = "white", bg = "#263042", image = last_card, command = lambda n = i: updateCard(n)))
        buttons[i].place(relx = locations[i], rely = 0.5)

cards变量是一个全局列表,可使用drawCard()函数从中“绘制”卡片。

0 个答案:

没有答案