how can I show please wait gif image before the process is complete

2024/11/20 1:39:45

I want to show "please wait gif" image from img() class before the ListApp() class process is complete and then as soon as the process of that class is completed the screeen of ListApp should be displayed.

I was trying the following code but it is not starting the process of ListApp() class

run1.py file

from kivy.lang import Builder
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from Option import OptionApp
import sys, time, threading
from kivy.uix.screenmanager import ScreenManager, Screen
from datetime import datetime
import pandas_datareader.data as web
import pandas as pd
from kivymd.uix.screen import Screen
from kivymd.uix.list import MDList,ThreeLineListItem,ThreeLineAvatarIconListItem
from kivymd.uix.list import IconLeftWidget,ImageLeftWidget
from kivy.uix.scrollview import ScrollView
from kivy.uix.button import Button
from kivymd.app import MDApp
from kivy.app import App
from kivy.properties import ObjectProperty
import csv
from os import path
from kivy.uix.image import Image
from kivy.app import App
from kivy.uix.textinput import TextInput
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import NumericProperty, ListProperty, BooleanProperty, ObjectProperty, StringProperty
from kivy.uix.recycleview import RecycleView
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.label import Label
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
import pandas as pdkv = Builder.load_file("run1.kv")class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,RecycleBoxLayout):''' Adds selection and focus behaviour to the view. '''class SelectableLabel(RecycleDataViewBehavior, Label):''' Add selection support to the Label '''index = Noneselected = BooleanProperty(False)selectable = BooleanProperty(True)txt_input1 = ObjectProperty(None)txt_input = ObjectProperty(None)def refresh_view_attrs(self, rv, index, data):''' Catch and handle the view changes '''self.index = indexreturn super(SelectableLabel, self).refresh_view_attrs(rv, index, data)def on_touch_down(self, touch):''' Add selection on touch down '''if super(SelectableLabel, self).on_touch_down(touch):return Trueif self.collide_point(*touch.pos) and self.selectable:return self.parent.select_with_touch(self.index, touch)def apply_selection(self, rv, index, is_selected):''' Respond to the selection of items in the view. '''self.selected = is_selectedif is_selected:# self.root.ids.txt_input1.text = str(rv.data[index].get("text"))App.get_running_app().root.widget_1.ids.txt_input1.text = str(rv.data[index].get("text"))class RV(RecycleView):def __init__(self, **kwargs):super(RV, self).__init__(**kwargs)class DropDownWidget(BoxLayout):txt_input = ObjectProperty()rv = ObjectProperty()txt_input1 = ObjectProperty()class MyTextInput(TextInput):txt_input = ObjectProperty()txt_input1 = ObjectProperty(None)flt_list = ObjectProperty()word_list = ListProperty()# this is the variable storing the number to which the look-up will startstarting_no = NumericProperty(3)suggestion_text = ''def __init__(self, **kwargs):super(MyTextInput, self).__init__(**kwargs)def on_text(self, instance, value):# find all the occurrence of the wordself.parent.ids.rv.data = []matches = [self.word_list[i] for i in range(len(self.word_list)) ifself.word_list[i][:self.starting_no] == value[:self.starting_no]]# display the data in the recycleviewdisplay_data = []for i in matches:display_data.append({'text': i})self.parent.ids.rv.data = display_data# ensure the size is okayif len(matches) <= 10:self.parent.height = (50 + (len(matches) * 20))else:self.parent.height = 240def keyboard_on_key_down(self, window, keycode, text, modifiers):if self.suggestion_text and keycode[1] == 'tab':self.insert_text(self.suggestion_text + ' ')return Truereturn super(MyTextInput, self).keyboard_on_key_down(window, keycode, text, modifiers)class Body(Screen):def __init__(self, **kwargs):super(Body, self).__init__(**kwargs)f = pd.read_csv("stoploss.csv")fl = len(f.index)file = pd.DataFrame(f, columns=['Stock Symbol', 'Purchase Price', 'Stock Name', 'Stop Loss(%)'])j = 0wl = []for i in range(fl):for index in range(1):columnSeriesObj = file.iloc[:, 2]# pp = iter(columnSeriesObj.values)# pp1 = next(pp)# print(pp1)wl.append(columnSeriesObj.values[i])tp = tuple(wl)print(str(tp))self.widget_1 = DropDownWidget(pos_hint={'center_x': .5, 'center_y': .5},size_hint=(None, None), size=(600, 60))self.widget_1.ids.txt_input.word_list = wlself.widget_1.ids.txt_input.starting_no = 3self.add_widget(self.widget_1)class signin(Screen):user_name = ObjectProperty(None)def btn(self):username = self.user_name.textprint(username)sm.current = 'option_screen'class option(Screen):def btn_addstock(self):sm.current = 'body_screen'def btn_stoplosslist(self):sm.canvas.clear()sm.current = 'Stoploss_ip'class stockinput(Screen):stock_name = ObjectProperty(None)stock_symbol = ObjectProperty(None)purchase_price = ObjectProperty(None)stop_loss = ObjectProperty(None)def btn(self):end = datetime.today().date()start = end.year - 10start = datetime(start, datetime.today().month, datetime.today().day).date()uname = input("Enter user name: ")print("Stock Name:", self.stock_name.text, "Stock Symbol:", self.stock_symbol.text)print("Purchase Price:",self.purchase_price.text,"Stop Loss(%):",self.stop_loss.text)#write data to csv file# if path.exists("stoploss.csv"):#     myFile = open('stoploss.csv', 'a')# else:#     myFile = open('stoploss.csv', 'w')file_name = stockinput.uname + "_stoploss.csv"if path.exists(file_name):with open(file_name, "a+", newline='')as newFile :fieldnames = ["Stock Name", "Stock Symbol", "Purchase Price", "Stop Loss(%)"]newFileWriter = csv.DictWriter(newFile, fieldnames=fieldnames)newFileWriter.writerow({"Stock Name" : self.stock_name.text,"Stock Symbol" : self.stock_symbol.text,"Purchase Price" : self.purchase_price.text,"Stop Loss(%)" : self.stop_loss.text})else:myFile = open(file_name, 'w+')myData = [["Stock Name", "Stock Symbol", "Purchase Price", "Stop Loss(%)"],[self.stock_name.text, self.stock_symbol.text, self.purchase_price.text, self.stop_loss.text]]with myFile:writer = csv.writer(myFile)writer.writerows(myData)df = web.DataReader(self.stock_symbol.text, 'yahoo', start, end,)print(df.tail())self.stock_name.text = ""self.stock_symbol.text = ""self.purchase_price.text = ""self.stop_loss.text = ""f = pd.read_csv("stoploss.csv")
file = pd.DataFrame(f, columns=['Stock Symbol','Purchase Price','Stock Name','Stop Loss(%)'])class img(Screen):def build(self,**kwargs):super(img, self).__init__(**kwargs)screen = selfimage = Image(source='please_wait.gif')screen.add_widget(image)class ListApp(Screen):# def imgpr(self,**kwargs):#     super(ListApp, self).__init__(**kwargs)##         time.sleep(0.1)# t = threading.Thread(target=imgpr)# t.start()def build(self,**kwargs):super(ListApp, self).__init__(**kwargs)flag = Truescreen = self# if flag:###     sm.add_widget(ListApp(name='Stoploss_ip'))end = datetime(2020, 12, 14)start = datetime(2020, 12, 14)btn = Button(text="Back",font_size="20sp",background_color=(255/255, 229/255, 204/255, 1),color=(1, 1, 1, 1),size=(12, 12),size_hint=(.1, .05),pos=(600, 500))btn.bind(on_press=lambda *args: setattr(sm, 'current', "option_screen"))scroll = ScrollView()list_view = MDList()scroll.add_widget(list_view)i = 0fl = len(file.index)try:for index in range(fl):for index in range(1):columnSeriesObj2 = file.iloc[:, 0]df = web.DataReader(columnSeriesObj2.values[i],'yahoo', start, end,retry_count=3)print(df.head())Objname = file.iloc[:, 2]columnSeriesObj = df.iloc[:, 3]columnSeriesObj1 = file.iloc[:, 1]ObjStoploss = file.iloc[:, 3]cp = iter(columnSeriesObj.values)pp = iter(columnSeriesObj1.values)pp1 = next(pp)cp1 = columnSeriesObj.values[0]sl = columnSeriesObj1.values[i] - (columnSeriesObj1.values[i] * (ObjStoploss.values[i]/100))if cp1 <= sl:image = ImageLeftWidget(source='loss.png')items = ThreeLineAvatarIconListItem(text="Alert sale " + Objname.values[i], secondary_text='Close price: '+str(cp1),tertiary_text='Stoploss: ' + str(sl))items.add_widget(image)list_view.add_widget(items)i=i+1else:image = ImageLeftWidget(source='profit.jpg')items = ThreeLineAvatarIconListItem(text="Chill " + Objname.values[i],secondary_text='Close price: ' + str(cp1),tertiary_text='Stoploss: ' + str(sl))items.add_widget(image)list_view.add_widget(items)i=i+1except ConnectionAbortedError:print("Check your Internet connection")except ConnectionRefusedError:print("Check your Internet connection")except ConnectionError:print("Check your Internet connection")except ConnectionResetError:print("Check your Internet connection")except TimeoutError:print("Timeout!!!!...Check your Internet connection")except KeyError:passexcept:print("Something went wrong")print("Done")# flag = False# if flag ==False:screen.add_widget(scroll)screen.add_widget(btn)# return screenclass WindowsManager(ScreenManager):passsm = ScreenManager()
sm.add_widget(signin(name='signin_screen'))
sm.add_widget(option(name='option_screen'))
sm.add_widget(stockinput(name='stockinput_screen'))
sm.add_widget(img(name='image_screen'))
sm.add_widget(ListApp(name='Stoploss_ip'))
sm.add_widget(Body(name='body_screen'))class run1(MDApp):def build(self):return smif __name__ == "__main__":run1().run()

run1.kv file

<WindowsManager>:signin:option:stockinput:ListApp:Body:<Body>:name: 'body_screen'canvas.before:Color:rgba: 188/255, 143/255, 145/255, 1Rectangle:pos: self.possize: self.size<DropDownWidget>:id: DropDownWidgetcanvas:Color:rgba:(1, 1, 1, 1)Rectangle:# pos: self.possize: self.size# orientation: 'vertical'spacing: 20txt_input: txt_inputrv: rvtxt_input1: txt_input1MyTextInput:id: txt_input1pos: 400,300size_hint_y: Noneheight: 50MyTextInput:id: txt_inputhint_text:'Enter here'size_hint_y: Noneheight: 50RV:id: rv<MyTextInput>:id: MyTextInputreadonly: Falsemultiline: False<SelectableLabel>:id: SelectableLabel# Draw a background to indicate selectioncolor: 0,0,0,1canvas.before:Color:rgba: (0, 0, 1, .5) if self.selected else (1, 1, 1, 1)Rectangle:# pos: self.possize: self.size<RV>:canvas:Color:rgba: 0,0,0,.2Line:rectangle: self.x +1 , self.y, self.width - 2, self.height -2bar_width: 10scroll_type:['bars']viewclass: 'SelectableLabel'SelectableRecycleBoxLayout:default_size: None, dp(20)default_size_hint: 1, Nonesize_hint_y: Noneheight: self.minimum_heightorientation: 'vertical'multiselect: False
<signin>:canvas.before:Color:rgba: 164/255, 66/255, 220/255, 1Rectangle:pos: self.possize: self.sizename: 'signin_screen'user_name: user_nameGridLayout:pos_hint: {'center_x': .75, 'center_y': .15}row_force_default : Truerow_default_height : 50col_force_default : Truecol_default_width : 400spacing: '15dp'cols: 1TextInput:id: user_namemultiline:Falsesize_hint: 5.0 ,.1hint_text: "Email_ID"Button:text:"Submit"font_size: 20color:0,0,0,1size_hint: .5 ,.3background_normal: ''background_color: (255/255, 153/255, 71/255, 1)on_press : root.btn()Label:text:"Please Do not change the Email_ID. Data will be saved as per your Email_ID"pos: 180,80<option>:canvas.before:Color:rgba: 138/255, 104/255, 175/255, 1Rectangle:pos: self.possize: self.sizename: 'option_screen'GridLayout:pos_hint: {'center_x': .83, 'center_y': .18}row_force_default : Truerow_default_height : 100col_force_default : Truecol_default_width : 250spacing: '20dp'cols:1Button:text:"Add Stock"color:0,0,0,1font_size: 18size_hint: .1 ,.1pos: 150,150background_normal: ''background_color: (204/255, 0, 204/255, 1)on_press : root.manager.current = 'body_screen'Button:text:"Check Stoploss"color:0,0,0,1font_size: 18size_hint: .1 ,.1pos: 250,120background_normal: ''background_color:(127/255, 193/255, 184/255, 1)on_press : root.manager.current = 'Stoploss_ip'<stockinput>:canvas.before:Color:rgba: 188/255, 143/255, 145/255, 1Rectangle:pos: self.possize: self.sizename: 'stockinput_screen'stock_name: stock_namestock_symbol: stock_symbolpurchase_price: purchase_pricestop_loss: stop_lossGridLayout:pos_hint: {'center_x': .67, 'center_y': .2}row_force_default : Truerow_default_height : 40col_force_default : Truecol_default_width : 250spacing: '10dp'cols:2#            pos_hint: {'center_x': .53, 'center_y': .12}
#            row_force_default : True
#            row_default_height : 30
#            col_force_default : True
#            col_default_width : 250
#            spacing: '20dp'Label:text: "Stock Name: "TextInput:id: stock_namemultiline:FalseLabel:text: "Stock Symbol: "TextInput:id: stock_symbolmultiline:FalseLabel:text: "Purchase Price: "TextInput:id: purchase_pricemultiline:FalseLabel:text: "Stop Loss(%): "TextInput:id: stop_lossmultiline:FalseButton:text:"Submit"color:102/255, 204/255, 0, 1font_size:18background_color: (204/255, 0, 102/255, 1)on_press: root.btn()Button:text:"Back"color:0,0,0,1font_size:18background_normal: ''background_color: (204/255, 102/255, 0, 1)on_press: root.manager.current = 'option_screen'<img>:name: 'image_screen'on_enter:root.build()<ListApp>:name: 'Stoploss_ip'on_enter:root.build()

**update I tried adding 2 lines in build() method and its showing the images now.I think its preloading the images and saving them in cache.

class ListApp(Screen):def build(self):self.popup = Popup(title='Calculating Stoploss', content=Image(source='please_wait.gif'))self.profit = ImageLeftWidget(source='profit.jpg')self.loss = ImageLeftWidget(source='loss.png')self.popup.open()# Clock.schedule_once(partial(self.actual_build))threading.Thread(target=self.actual_build).start()def actual_build(self):screen = selfend = datetime.today().date()start = endbtn = Button(text="Back",font_size="20sp",background_color=(255/255, 229/255, 204/255, 1),color=(1, 1, 1, 1),size=(12, 12),size_hint=(.1, .05),pos=(600, 500))btn.bind(on_press=lambda *args: setattr(sm, 'current', "option_screen"))scroll = ScrollView()list_view = MDList()scroll.add_widget(list_view)i = 0fl = len(file.index)try:for index in range(fl):for index in range(1):columnSeriesObj2 = file.iloc[:, 0]df = web.DataReader(columnSeriesObj2.values[i],'yahoo', start, end,retry_count=3)print(df.head())Objname = file.iloc[:, 2]columnSeriesObj = df.iloc[:, 3]columnSeriesObj1 = file.iloc[:, 1]ObjStoploss = file.iloc[:, 3]cp = iter(columnSeriesObj.values)pp = iter(columnSeriesObj1.values)pp1 = next(pp)cp1 = columnSeriesObj.values[0]sl = columnSeriesObj1.values[i] - (columnSeriesObj1.values[i] * (ObjStoploss.values[i]/100))if cp1 <= sl:image = ImageLeftWidget(source='loss.png')items = ThreeLineAvatarIconListItem(text="Alert sale " + Objname.values[i], secondary_text='Close price: '+str(cp1),tertiary_text='Stoploss: ' + str(sl))items.add_widget(image)list_view.add_widget(items)i=i+1else:image = ImageLeftWidget(source='profit.jpg')items = ThreeLineAvatarIconListItem(text="Chill " + Objname.values[i],secondary_text='Close price: ' + str(cp1),tertiary_text='Stoploss: ' + str(sl))items.add_widget(image)list_view.add_widget(items)i=i+1except ConnectionAbortedError:print("Check your Internet connection")except ConnectionRefusedError:print("Check your Internet connection")except ConnectionError:print("Check your Internet connection")except ConnectionResetError:print("Check your Internet connection")except TimeoutError:print("Timeout!!!!...Check your Internet connection")except KeyError:passexcept:pass# print("Something went wrong")print("Done")# screen.add_widget(screen.scroll)# screen.add_widget(btn)Clock.schedule_once(partial(screen.finish_build, scroll, btn))screen.popup.dismiss()def finish_build(self, scroll, btn, dt):screen = selfscreen.add_widget(scroll)screen.add_widget(btn)
Answer

Since you are triggering the build() method by using the on_enter attribute, you can accomplish what you want by using that method.

First, you are calling:

super(ListApp, self).__init__(**kwargs)

from the build() method. You should not call that super method except from within an __init__() method override. So that line should be removed. Since you have not written an __init__() method for ListApp, there is no need to call the super class __init__().

I suggest renaming your build() method to actual_build() like this:

def actual_build(self, *args):

and define a new build() method as:

def build(self, **kwargs):self.popup = Popup(title='Preparing ListApp', content=Image(source='please_wait.gif', anim_delay=0.05))self.popup.open()threading.Thread(target=self.actual_build).start()

The above method displays the animated gif, and starts the actual_build() method (formerly named build()).

Then, modify the actual_build() method as:

def actual_build(self, *args):# super(ListApp, self).__init__(**kwargs)flag = Truescreen = self# if flag:###     sm.add_widget(ListApp(name='Stoploss_ip'))end = datetime(2020, 12, 14)start = datetime(2020, 12, 14)btn = Button(text="Back",font_size="20sp",background_color=(255/255, 229/255, 204/255, 1),color=(1, 1, 1, 1),size=(12, 12),size_hint=(.1, .05),pos=(600, 500))btn.bind(on_press=lambda *args: setattr(sm, 'current', "option_screen"))scroll = ScrollView()list_view = MDList()scroll.add_widget(list_view)i = 0fl = len(file.index)try:for index in range(fl):for index in range(1):columnSeriesObj2 = file.iloc[:, 0]df = web.DataReader(columnSeriesObj2.values[i],'yahoo', start, end,retry_count=3)print(df.head())Objname = file.iloc[:, 2]columnSeriesObj = df.iloc[:, 3]columnSeriesObj1 = file.iloc[:, 1]ObjStoploss = file.iloc[:, 3]cp = iter(columnSeriesObj.values)pp = iter(columnSeriesObj1.values)pp1 = next(pp)cp1 = columnSeriesObj.values[0]sl = columnSeriesObj1.values[i] - (columnSeriesObj1.values[i] * (ObjStoploss.values[i]/100))if cp1 <= sl:image = ImageLeftWidget(source='loss.png')items = ThreeLineAvatarIconListItem(text="Alert sale " + Objname.values[i], secondary_text='Close price: '+str(cp1),tertiary_text='Stoploss: ' + str(sl))items.add_widget(image)list_view.add_widget(items)i=i+1else:image = ImageLeftWidget(source='profit.jpg')items = ThreeLineAvatarIconListItem(text="Chill " + Objname.values[i],secondary_text='Close price: ' + str(cp1),tertiary_text='Stoploss: ' + str(sl))items.add_widget(image)list_view.add_widget(items)i=i+1except ConnectionAbortedError:print("Check your Internet connection")except ConnectionRefusedError:print("Check your Internet connection")except ConnectionError:print("Check your Internet connection")except ConnectionResetError:print("Check your Internet connection")except TimeoutError:print("Timeout!!!!...Check your Internet connection")except KeyError:passexcept:print("Something went wrong")# flag = False# if flag ==False:# screen.add_widget(scroll)# screen.add_widget(btn)# schedule the code that must be run on the main threadClock.schedule_once(partial(self.finish_build, scroll, btn))# dismiss the animated gifself.popup.dismiss()

The above actual_build() method does everything that the original build() method did, except for the actual changes to the GUI (that must be done on the main thread). At the end of this method, a call to finish_build() is scheduled, and the animated gif Popup is dismissed.

Finally, add a finish_build() method that does the actual GUI changes:

def finish_build(self, scroll, btn, dt):screen = selfscreen.add_widget(scroll)screen.add_widget(btn)
https://en.xdnf.cn/q/118471.html

Related Q&A

TypeError: list of indices must be integers, not str

What is wrong in my code to give me the error:TypeError: List of indices must be integers, not strHere is my code:print("This programe will keep track of your TV schedule.") Finish = False Sh…

Assignment in conditional not permitted in Python?

Why is code like if a = "hello":passinvalid in Python? The a = "Hello" is just a expression whose value is the Rvalue. Its valid in most languages like C or php. Some opinions?

Django - Join two Table without Foreign key

I have two tables and want to join them.. but I cant do that without rawQueryset and raw SQL. how can i join two models without foreign key? The columns for JOIN is not unique so it cant be PK and For…

Understanding lambda functions

Well I did try to read about Lambda functions but did not get across any link which explains few questions about its flow and the way it is handled by python interpretor or may be I could not understan…

JSON to Python dataframe: mapping values from another API

I have an API with student data like this, for every student id there will be a corresponding API link with mark details. for example: https://api.school.com/2020/students.json {"Students": […

Create a cycle out of scattered points

I know this sounds trivial, but my head is refusing to give an algorithm for this.I have a bunch of points scattered on a 2-D plane and want to store them in a list such that they create a ring. The po…

Python Dictionary w/ 2 Keys?

Can I have a python dictionary with 2 same keys, but with different elements?

Tkinter throwing a KeyError when trying to change frames

Im learning tkinter off of the Sentdex tutorials and I into a problem when trying to change pages. My compiler throws something about a KeyError that it doesnt give whenever I change the button on the …

How to send messages to other clients only in the sequence of adding clients?

https://github.com/kakkarotssj/ChatApplication/blob/master/GroupChat/sever.pyhttps://github.com/kakkarotssj/ChatApplication/blob/master/GroupChat/client.pyWhen server starts, and suppose three clients …

Dictionary keeps getting overwritten in each iteration of for-loop

import randomo=[,,!,@,#,$,%,^,&,*,(,),,_,=,+,/,[] q=[1,2,3,4,5,6,7,8,9,0]for i in top_25:wordDic ={i: random.choice(o)+random.choice(q)} print(wordDic)(top_25 is an array of words, and the random.c…