如何保持标签中每秒显示变化多端的实时数据?

How to keep displaying the changeable real-time data in label every second?

在我的代码中,它使用 pyaudio 来获取用户的音高和音量。 它每秒在终端中不断显示数值。

问题是当我使用 Stringproperty 或 ids 方法将它们显示在标签中时,它没有显示任何内容。

但是,代码中断后,它显示的数据是标签中的最后一个音量和音高。

如何在标签中显示每秒的实时数据?

这是我的示例代码.py:

while True:
    
        data = stream.read(1024)
        samples = num.fromstring(data,
            dtype=aubio.float_type)
        pitch = pDetection(samples)[0]
        # Compute the energy (volume) of the
        # current frame.
        volume = num.sum(samples**2)/len(samples)
        # Format the volume output so that at most
        # it has six decimal numbers.
        volume = "{:.6f}".format(volume)
        print(pitch)
        print(volume)
        
        #self.ids.pitchs.text= str(pitch)
        self.ids.volumes.text= volume 
        self.pitchs1 = str(pitch) 
      
            
        if keyboard.is_pressed('1'):  # if key '1' is pressed 
                break  # finishing the[1] loop
        

这里是 .kv 文件:

<Genereate>
 GridLayout:
     cols: 1
 GridLayout:
     size: root.width, root.height
     cols:2
     Label:
         id: pitchs
         text: root.pitchs1
         color: 1,0,1,1
    
     Label:
         id: volumes
         text: "Volume"
         color: 1,0,1,1
 Button:
     text: "Submit"
     size_hint: .5, .6
     on_release: root.pitches() 

问题是 while 循环会 运行 非常快,用户不会注意到任何更改使用 kivy 时钟模块的解决方案,如下所示 创建一个方法来处理计算

def streaming(self, *args):
    data = stream.read(1024)
    samples = num.fromstring(data,
                             dtype=aubio.float_type)
    pitch = pDetection(samples)[0]
    # Compute the energy (volume) of the
    # current frame.
    volume = num.sum(samples ** 2) / len(samples)
    # Format the volume output so that at most
    # it has six decimal numbers.
    volume = "{:.6f}".format(volume)
    print(pitch)
    print(volume)

    # self.ids.pitchs.text= str(pitch)
    self.ids.volumes.text = volume
    self.pitchs1 = str(pitch
            
        

现在你应该使用时钟方法每隔一秒或任何其他周期调用一次


def run_stream(self,):
    schedule=Clock.schedule_interval(streaming, 1)
    # you can stop the steaming like this 
    if keyboard.is_pressed('1'):  # if key '1' is pressed 
        schedule.cancle()