如何在kivymd中的函数开始时显示加载屏幕?

2024-03-28 20:22:42 发布

您现在位置:Python中文网/ 问答频道 /正文

在从web获取数据期间,我想在Kivymd应用程序中使用加载屏幕。但当我运行代码时,获取数据后会出现加载屏幕

我想显示加载屏幕,从web获取一些数据,然后在新屏幕上显示结果。
这是我的get_data函数的一部分。此功能在用户单击按钮时运行

def get_data(self):
    self.root.ids.MainScreen.pos_hint = {"center_x": .5, "center_y": 50} # Hide main screen
    self.root.ids.LoadingScreen.pos_hint = {"center_x": .5, "center_y": .5} # Show loading screen
    requests.get("https//.....")
    # Code more

装载几乎需要10秒钟。我将屏幕移动代码放在函数的顶部,但为什么屏幕移动代码在函数之后运行?如何解决这个问题

我正在使用Windows10和Python3.8


Tags: 函数代码posselfweb应用程序idsdata
2条回答

在所有请求工作完成之前,您可以使用threadingClock.schedule移动到加载屏幕。查看更多详细信息here

def get_data(self):
    self.root.ids.MainScreen.pos_hint = {"center_x": .5, "center_y": 50} # Hide main screen
    self.root.ids.LoadingScreen.pos_hint = {"center_x": .5, "center_y": .5} # Show load screen
    Clock.schedule_once(function_to_get_data)
def function_to_get_data(self, *args):
    #code to get data

更新: 以下是带参数的线程代码:

def get_data(self):
    self.root.ids.MainScreen.pos_hint = {"center_x": .5, "center_y": 50} # Hide main screen
    self.root.ids.LoadingScreen.pos_hint = {"center_x": .5, "center_y": .5} # Show load screen
    threading.Thread(target = function_to_get_data, args=(param,))
def function_to_get_data(self, param):
    #code to get data

你可以使用窗口管理器。如果没有完整的代码,很难说,但类似于:

    from kivy.uix.screenmanager import ScreenManager, Screen
    from kivy.core.window import Window
    
class MainScreen(Screen):
...
    def get_data(self):
        self.parent.current = 'LoadingWindow'
        get your data
        wait for it to return
        self.parent.current = 'MainWindow'
...
class LoadingScreen(Screen):
    pass
...
class WindowManager(ScreenManager):
    pass

这假设a.o.get_数据在MainScreen类中,LoadingScreen和MainScreen定义为窗口管理器中的屏幕,例如(单位:千伏)

WindowManager:
    LoadingScreen:
    MainScreen:

<MainScreen>:
    id: mainWindow
    ...

<LoadingScreen>:
    id: LoadingWindow
    ...

相关问题 更多 >