第二个按钮 window 没有改变 text/color

button on second window doesnt change text/color

我正在制作一个 Tkinter GUI,其中涉及打开更多的按钮 windows。问题是第二个 window 上的按钮应该更改 text/color(表明 LED 是 off/on)但它不会更新,直到 window 关闭和打开再次.

有谁知道如何在不关闭 window 的情况下更新它?

def open_relais():
    relais = Toplevel()
    relais.title('first window')
    relais.geometry('800x480')
    LED = Button(relais,text='LED',command=LED1,bg='grey89',fg='black',padx=10,pady=10)
    LED.pack(pady=50)
    #led knop kleur
    if ledstate == 0:
        LED.config(bg='red')
    else:
        LED.config(bg='green')
    close_button = Button(relais, text='close window', command=relais.destroy).pack()


def LED1():
        global ledstate
        if ledstate == 0:
            ledstate = 1
            bus.write_byte_data(DEVICE,OLATA,ledstate)
            print(ledstate)
        else:
            ledstate = 0
            bus.write_byte_data(DEVICE,OLATA,ledstate)
            print(ledstate)


button1=Button(menu,text='item 1 in horizontal',command=open_relais,bg='grey89',fg='black',padx=10,pady=10)
button1.grid(row=0,column=0,padx=23,pady=15,sticky='nsew')

问题可能是我在 'def' 函数中打开了第二个 window。 任何帮助表示赞赏

首先您需要在全局范围内初始化 ledstate。其次,您需要通过将 LED 传递给 LED1().

来更新 LED1() 函数中的 LED
ledstate = 0

def LED1(LED):
    global ledstate
    ledstate = 1 - ledstate
    print(ledstate)
    LED.config(bg="green" if ledstate else "red")
    bus.write_byte_data(DEVICE,OLATA,ledstate)

def open_relais():
    relais = Toplevel()
    relais.title('first window')
    relais.geometry('800x480')
    LED = Button(relais,text='LED',command=lambda: LED1(LED),fg='black',padx=10,pady=10)
    LED.pack(pady=50)
    LED.config(bg="green" if ledstate else "red")
    Button(relais, text='close window', command=relais.destroy).pack()