Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
205 views
in Technique[技术] by (71.8m points)

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

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 pd

kv = 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 = None
    selected = 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 = index
        return 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 True
        if 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_selected
        if 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 start
    starting_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 word
        self.parent.ids.rv.data = []
        matches = [self.word_list[i] for i in range(len(self.word_list)) if
                   self.word_list[i][:self.starting_no] == value[:self.starting_no]]
        # display the data in the recycleview
        display_data = []
        for i in matches:
            display_data.append({'text': i})
        self.parent.ids.rv.data = display_data
        # ensure the size is okay
        if len(matches) <= 10:
            self.parent.height = (50 + (len(matches) * 20))
        else:
            self.parent.height = 240

    def keyboard_on_key_down(self, window, keycode, text, modifiers):
        if self.suggestion_text and keycode[1] == 'tab':
            self.insert_text(self.suggestion_text + ' ')
            return True
        return 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 = 0
        wl = []
        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 = wl
        self.widget_1.ids.txt_input.starting_no = 3

        self.add_widget(self.widget_1)
    





class signin(Screen):

    user_name = ObjectProperty(None)

    def btn(self):

        username = self.user_name.text
        print(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 - 10
        start = 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 = self
        image = 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 = True


        screen = 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 = 0
        fl = 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+1


                    else:
                        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+1
        except ConnectionAbortedError:
            print("Check your Internet connection")
        except ConnectionRefusedError:
            print("Check your Internet connection")
        exc

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 = True


    screen = 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 = 0
    fl = 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+1


                else:
                    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+1
    except 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:
        pass

    except:
        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 thread
    Clock.schedule_once(partial(self.finish_build, scroll, btn))

    # dismiss the animated gif
    self.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 = self
    screen.add_widget(scroll)
    screen.add_widget(btn)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...