【问题标题】:Kivy progress bar value updates, but progress bar does notKivy进度条值更新,但进度条不更新
【发布时间】:2020-11-05 09:12:31
【问题描述】:

我的 kivy 应用中有一个 ProgressBar。我相信我需要使用Clock.create_trigger 来确保从循环内部更新进度条。

我已尝试将 Progress bar in kivy can't update using loopKivy How can i create time counter with progressbar? 的解决方案调整为我的解决方案,但是,直到最后该栏仍未更新。

以下代码是出于可重复性目的的淡化版本。

ProgressBar 类

from kivy.clock import Clock
from kivy.uix.progressbar import ProgressBar


class MyProgressBar(ProgressBar):
    def __init__(self, *args, **kwargs):
        super(MyProgressBar, self).__init__(*args, **kwargs)
        # self.update_bar_trigger = Clock.create_trigger(self.update_bar)
        self.update_bar_trigger = Clock.create_trigger(lambda dt: self.update_bar(), 1)

    def update_bar(self, step):
        if self.value <= 100:
            self.value += step
            self.update_bar_trigger()

主类:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.core.window import Window
from kivy.properties import ObjectProperty
from MyProgressBar import MyProgressBar

from kivy.lang import Builder
Builder.load_file('style.kv')


class Main_app(BoxLayout):
    # Progress bars
    loading_pb = MyProgressBar()

    def dummy(self):
        pb_increment = 10

        for i in range(10):
            time.sleep(2)
            self.loading_pb.update_bar(pb_increment)
            print(self.loading_pb.value)


class Stacked(App):
    def build(self):
        Window.clearcolor = (1, 1, 1, 1)
        Window.size = (1000, 700)

        return Main_app()

if __name__ == '__main__':
    Stacked().run()

KV 文件

<Main_app>:
    loading_pb: load_pb

    GridLayout:
        rows: 2
        MyProgressBar:
            id: load_pb
            value: 0
            min: 0
            max: 100

        Button:
            text: 'Start Progress Bar'
            on_press:
                root.dummy()

这个例子展示了 loading_pb.value 在按钮被点击后随着代码循环的变化。

ProgressBar.value 打印输出

10.0
20.0
30.0
40.0
50.0
60.0
70.0
80.0
90.0
100.0

问题 进度条 value 似乎确实按预期增加了,但实际进度条直到循环结束时才会立即发生变化。

相关

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:
        for i in range(10):
            time.sleep(2)
            self.loading_pb.update_bar(pb_increment)
            print(self.loading_pb.value)
    

    这段代码会阻塞 gui 直到它返回,所以正常的 gui 绘制不会发生。相反,使用Clock.schedule_interval 和/或Clock.schedule_once 来安排循环的每次迭代。这些将函数调用插入到 kivy 自己的事件循环中,并避免阻塞该循环。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-08
      • 1970-01-01
      • 1970-01-01
      • 2014-04-09
      相关资源
      最近更新 更多