【问题标题】:button on second window doesnt change text/color第二个窗口上的按钮不会改变文本/颜色
【发布时间】:2021-04-29 09:05:45
【问题描述】:

我正在制作一个 Tkinter GUI,其中包含打开更多窗口的按钮。问题是第二个窗口上的按钮应该更改文本/颜色(指示 LED 关闭/打开的东西)但在窗口关闭并再次打开之前它不会更新。

有人知道如何在不关闭窗口的情况下更新它吗?

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”函数中打开了第二个窗口。 任何帮助表示赞赏

【问题讨论】:

    标签: python windows tkinter button


    【解决方案1】:

    首先你需要在全局范围内初始化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()
    

    【讨论】:

    • 感谢您的帮助,它现在可以工作但我不明白它是如何工作的,您能解释一下您所做的更改以及为什么现在可以工作吗?
    • 首先由于在LED1()函数内部声明了ledstate全局,所以需要在全局范围内定义ledstate,否则会出现ledstate not found错误。其次,您只需在open_relais() 函数内更新一次LED 颜色,如果您想在单击按钮时更改LED 的颜色,则需要在按钮回调LED1() 内更新LED 的颜色.但是LED是一个局部变量,所以需要传递给LED1(),否则在LED1()函数内部无法访问。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-02
    • 2016-11-13
    • 2020-02-15
    相关资源
    最近更新 更多