首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >异步程序中的AttributeError

异步程序中的AttributeError
EN

Stack Overflow用户
提问于 2022-11-15 12:33:33
回答 1查看 48关注 0票数 1

请你帮我修一下这个程序,这样它就不会显示属性错误了。我是异步编程的新手,我对所发生的事情几乎一无所知。

以下是代码:

代码语言:javascript
复制
"""Example shows the recommended way of how to run Kivy with the Python built
in asyncio event loop as just another async coroutine.
"""
import asyncio

from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.widget import Widget

Builder.load_string('''BoxLayout:
    orientation: 'vertical'
    BoxLayout:
        ToggleButton:
            id: btn1
            group: 'a'
            text: 'Sleeping'
            allow_no_selection: False
            on_state: if self.state == 'down': label.status = self.text
        ToggleButton:
            id: btn2
            group: 'a'
            text: 'Swimming'
            allow_no_selection: False
            on_state: if self.state == 'down': label.status = self.text
        ToggleButton:
            id: btn3
            group: 'a'
            text: 'Reading'
            allow_no_selection: False
            state: 'down'
            on_state: if self.state == 'down': label.status = self.text
    Label:
        id: label
        status: 'Reading'
        text: 'Beach status is "{}"'.format(self.status)''')

class MainLayout(Widget):

    other_task = None

    def app_func(self):
        """This will run both methods asynchronously and then block until they
        are finished
        """
        self.other_task = asyncio.ensure_future(self.waste_time_freely())

        async def run_wrapper():
            # we don't actually need to set asyncio as the lib because it is
            # the default, but it doesn't hurt to be explicit
            await self.async_run(async_lib='asyncio')
            print('App done')
            self.other_task.cancel()

        return asyncio.gather(run_wrapper(), self.other_task)

    async def waste_time_freely(self):
        """
        This method is also run by the asyncio loop and periodically prints
        something.
        """
        try:
            i = 0
            while True:
                if self.root is not None:
                    status = self.root.ids.label.status
                    print('{} on the beach'.format(status))

                    # get some sleep
                    if self.root.ids.btn1.state != 'down' and i >= 2:
                        i = 0
                        print('Yawn, getting tired. Going to sleep')
                        self.root.ids.btn1.trigger_action()

                i += 1
                await asyncio.sleep(2)
        except asyncio.CancelledError as e:
            print('Wasting time was canceled', e)
        finally:
            # when canceled, print that it finished
            print('Done wasting time')

class AsyncApp(App):

    def build(self):
        return MainLayout()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(MainLayout().app_func())
    loop.close()

这是显示的错误

请您为我修复属性错误,以及如何消除所有的弃用警告?

谢谢。

EN

回答 1

Stack Overflow用户

发布于 2022-11-16 18:51:19

如果您想要达到目的的方法,而不是对异步的修正,我冒昧地以我所知道的方式编写了一些东西:线程。

当我运行代码时,它没有很好地显示按钮,所以我将顶层更改为BoxLayout,并根据顶级类名'MainLayout‘在构建字符串中命名为顶层

Kivy还提供了一种使用kivy.clock来调度任务的方法,我偶尔在我的kivy应用程序中使用它,但更常见的是使用线程。

代码语言:javascript
复制
"""Example shows the recommended way of how to run Kivy with the Python built
in Threading
"""
import time
import threading
from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.boxlayout import BoxLayout


Builder.load_string('''<MainLayout>:
    orientation: 'vertical'
    BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            orientation: 'vertical'
            ToggleButton:
                id: btn1
                group: 'a'
                text: 'Sleeping'
                allow_no_selection: False
                on_state: if self.state == 'down': label.status = self.text
            ToggleButton:
                id: btn2
                group: 'a'
                text: 'Swimming'
                allow_no_selection: False
                on_press: root.kv_swim(self, my_argument = 'anything')
                on_state: if self.state == 'down': label.status = self.text
            ToggleButton:
                id: btn3
                group: 'a'
                text: 'Reading'
                allow_no_selection: False
                state: 'down'
                on_press: root.kv_read(self, my_argument = 'anything')
                on_state: if self.state == 'down': label.status = self.text
    Label:
        id: label
        status: 'Reading'
        text: 'Beach status is "{}"'.format(self.status)''')


class MainLayout(BoxLayout):

    other_task = None
    started_reading = False
    started_swimming = False

    def waste_time(self, task: str):
        while True:
            print(f"the task {task} is {time.time():.1f}")
            time.sleep(1.2)

    def kv_read(self, my_button, my_argument: str = "default_value"):
        print(f"you can send information from the button {my_argument}")
        if not self.started_reading:
            threading.Thread(target=self.waste_time, args=("read", ), daemon=True).start()
            self.started_reading = True
        else:
            print("don't start again")

    def kv_swim(self, my_button, my_argument: str = "default_value"):
        print(f"you can send information from the button {my_argument}")
        if not self.started_swimming:
            threading.Thread(target=self.waste_time, args=("swim", ), daemon=True).start()
            self.started_swimming = True
        else:
            print("don't start again")


class ThreadedApp(App):

    def build(self):
        return MainLayout()


if __name__ == '__main__':
    mine = ThreadedApp()
    mine.run()
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74445708

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档