[Python] How can a tkinter button dynamical control the content of other buttons?

Discussão em 'Python' iniciado por Stack, Novembro 28, 2024.

  1. Stack

    Stack Membro Participativo

    I try to create some buttons and the content (picture) of these buttons is controlled by another button, dynamically.

    E.g.

    Button A and Button B are controlled by Button C and D.

    If I press C, then A is 'Pic1' and B is 'Pic2' and if I press button D then A is 'Pic3' and B is 'Pic4' and also back to A is 'Pic1' and B is 'Pic2' if I press Button C again.

    I already tried to code the button explicitly like this:

    def my_command(value):
    print (value)
    return

    button= Button(win, image=tes[0],command= lambda: my_command(1),borderwidth=0)
    button.grid(row=0,column=0)
    button= Button(win, image=tes[1],command= lambda: my_command(2),borderwidth=0)
    button.grid(row=0,column=1)


    This one works fine pressed 1 my_command(1) returns Button:1 if pressed 2 my_command(2) returns Button:2)

    BUT when I put it in a for-loop like this:

    j=0
    for i in f1:
    # file up a list of pic from files, f1 is a list of valid file names
    click_btn1= PhotoImage(file=i)
    tes.append(click_btn1)
    #set the image of the button
    img_label= Label(image=tes[j])
    # assign button and command
    button= Button(win, image=tes[j],command= lambda j=j:
    my_command(j),borderwidth=0)
    button.grid(row=0,column=j)
    j +=1


    The buttons are displayed and I can click them but my_command(j) returns "Button:2" all the time, no matter which button I press (1 or 2)

    Continue reading...

Compartilhe esta Página