如何根据串行读取实时更改bg颜色?

问题描述

这是我的第一个GUI

enter image description here

,我想实时更改Button的bg颜色。 也许像这样令人困惑,但是我不确定放在哪里。.:(

 b = ser.read()
 
    if b == b'1': 
        start_forButton.configure(bg='red') 
    else:
        start_forButton.configure(bg='white')

    if b == b'2':  
        start_backButton.configure(bg='red')  
    else:
        start_backButton.configure(bg='white')

enter image description here

也许具有after函数,因为我现在拥有的代码正在改变颜色,但是有一个延迟,不是实时的。

解决方法

您可以使用按钮小部件中的命令来调用函数以更改颜色...

from tkinter import *

root = Tk()

def move_forward_pressed():
    button1.configure(bg='red')
def stop_pressed():
    button1.configure(bg='green')

button1 = Button(root,text='move forward',bg='green',command=move_forward_pressed)
button1.pack()
button2 = Button(root,text='stop',command=stop_pressed)
button2.pack()

root.mainloop()
,

这可行,我在ser.read commmand之后添加了ser.flusInput和StartLogger,以便该记录仪每100毫秒读取一次串行端口。

现在按钮正在实时更改bg颜色(延迟100毫秒):

  def warning():
         b = ser.read()
         ser.flushInput()
         print(b)

         if b == b'1': 
         start_forButton.configure(bg='red')  

         if b == b'2': 
         start_backButton.configure(bg='red')  
         
         if b==b'0':
         start_forButton.configure(bg='white')
         start_backButton.configure(bg='white')

    def startLogger():
             while True:
                 warning()
                 sleep(0.1)