Kivy:在我的代码中正确实现“单选按钮”。 Python 3

时间:2020-02-20 16:26:39

标签: python kivy kivy-language

我的应用程序具有3个屏幕,可通过“ ActionBar”进行浏览。我在kv文件中命名了每个屏幕,一个是“跟踪”另一个是“ pess”。这是我需要帮助的两个。

我在“ pess”屏幕类中创建了一个单选按钮小部件(下图),因此可以添加电子邮件地址。

在“跟踪”屏幕课程中,我拥有了要通过电子邮件发送的所有数据,但是我认为事情已经变得过于复杂了。我想将活动的单选按钮从“ pess”屏幕链接到“ track”屏幕def发送功能...

我的Main.py看起来像这样

{{ product.featured_image | img_url | img_tag }}

kv文件

class ScreenGenerator(ScreenManager):
    pass

class PessQuestions(Screen):
    email = {}
    path = ''

    def loadEmails(self, *args):
        self.path = App.get_running_app().user_data_dir + '/'
        try:
            with open(self.path + 'email.json', 'r') as data:
                self.email = json.load(data)
        except FileNotFoundError:
            pass

    def saveEmails(self, *args):
        print(self.ids.name.text, type(self.ids.name.text))
        print(self.ids.address.text, type(self.ids.address.text))
        self.email[self.ids.name.text] = self.ids.address.text

        self.path = App.get_running_app().user_data_dir + '/'
        with open(self.path + 'email.json', 'w') as email_address_json:
            json.dump(self.email, email_address_json)
            print('saveEmails')
        self.ids.address.text = ''
        self.ids.name.text = ''

        self.ids.info.clear_widgets()
        self.on_pre_enter() # refresh screen

    def delete_email(self, check):
        address = check.ids.who_name.text
        del self.email[address]

        self.ids.info.remove_widget(check)
        self.saveEmails()

##########################################################
########### PRE ENTER ####################################
    def on_pre_enter(self):
        self.ids.info.clear_widgets()
        self.loadEmails()
        try:
            for name, mail in self.email.items():
                self.ids.info.add_widget(Checkboxes(name=name, mail=mail, email=self.email))
        except ValueError:
            print('VALUE ERROR: Label.text accept only "str"')

        self.ids.pess_date.text = strftime('[b]%A[/b], %B %Y') # time and date

##########################################################
########### PRE LEAVE ####################################
    def on_pre_leave(self):
        self.ids.info.clear_widgets()
        self.saveEmails()

class Checkboxes(BoxLayout):
    def __init__(self, name='', mail='', email='', **kwargs):
        super().__init__(**kwargs)
        self.ids.who_name.text = name
        self.ids.who_email.text = mail

    def on_checkbox_Active(self, checkboxInstance, isActive):
        address = ''
        if isActive:
            '''
            Email is used for recipient
            '''
            name = self.ids.who_name.text
            email = self.ids.who_email.text
            print('Email Set!')
            return email
        else:
            '''
            Nothing happens, email is not used
            '''


##########################################################
######## TRACKERS WINDOWS ################################
##########################################################
class Trackers(Screen):
    email = {'davi': 'example@gmail.com'}
    storage = {}
    pess_storage = {}
    path = ''

    def on_pre_enter(self):
        self.path = App.get_running_app().user_data_dir + '/'
        self.loadData()
        for tracker, num in self.storage.items():
            self.ids.track.add_widget(Tracker(text=tracker, number=num))

    def on_pre_leave(self):
        self.ids.track.clear_widgets()
        self.saveData()

    def saveData(self, *args):
        with open(self.path + 'data.json', 'w') as data:
            json.dump(self.storage, data)

    def loadData(self, *args):
        try:
            with open(self.path + 'data.json', 'r') as data:
                self.storage = json.load(data)
                print(self.storage)
        except FileNotFoundError:
            pass

    def savePESS(self, PESS):
        self.pess_storage['physical'] = PESS.ids.phy_text.text
        self.pess_storage['emotional'] = PESS.ids.emo_text.text
        self.pess_storage['spiritual'] = PESS.ids.spi_text.text
        self.pess_storage['sexual'] = PESS.ids.sex_text.text
        self.pess_storage['comment'] = PESS.ids.comment.text

    def save_text(self, tracker, text_input, *args):
        tracker.ids.label.text = text_input.text
        self.storage[text_input.text] = '0'
        self.saveData()
        self.loadData()
        print('testing')

    def send(self, PESS):
        self.path = App.get_running_app().user_data_dir + '/'
        with open(self.path + 'bat', 'r') as bat:
            login = bat.read()
            davi = self.email['davi']
            mail = PESS.ids.who_email.text
            #kevin = self.email['kevin'] # instead of this I'd like to have this variable linked to 
            gmail = GMail(davi, login)

            day = strftime("%a, %b %d, %Y")
            tracker_message = 'PESS\n'
            subject_message = f"Subject: PESS {day}"

            for pess, txt in self.pess_storage.items():
                tracker_message += f"\t{pess.title()}: {txt}\n"

            for tracker, numbers in self.storage.items():
                tracker_message += f"\n{numbers} ---> {tracker}\n"

            message = f"{subject_message}\n\n{tracker_message}"
            msg = Message(f'PESS | {day}', to=mail, text=message)
            gmail.send(msg)

            self.sent_confirmation(f'{self.ids.who_name.text}: {mail}')

    def sent_confirmation(self, recipient):
        box = BoxLayout(orientation='vertical', padding=40, spacing=5)
        pop = Popup(title='Email Sent', content=box, size_hint=(None,None), size=(self.width, self.width/2))
        info = Label(text=f'Congrats, {recipient} has recieved an email.')
        box.add_widget(info)
        pop.open()
        self.saveData()


class Tracker(BoxLayout):
    def __init__(self, text='', number='', **kwargs):
        super().__init__(**kwargs)
        self.ids.label.text = text
        self.ids.count_add.text = number


class Pess(App):
    def build(self):
        Config.set('graphics', 'width', '600')
        Config.set('graphics', 'height', '800')
        from kivy.core.window import Window
        Window.clearcolor = get_color_from_hex('#262829')

        return ScreenGenerator()


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

我的代码运行得很好,但是所有发送信息的电子邮件都是硬编码的。我想为用户提供输入电子邮件地址并将其发送到该地址的选项。

我添加了Checkboxes类,每次添加名称和电子邮件地址并单击“ Save Email”时都会创建该复选框。它被分组,因此它们是单选按钮。

我似乎无法将电子邮件地址连接到Trackers类上的send函数...我希望所有这些都有意义。我可能为我自己使事情变得过于复杂。我可以帮忙。谢谢。

Tracker Screen

Pess Screen

0 个答案:

没有答案