簡體   English   中英

如何在 Kivy 代碼中加入我的 Python 方法?

[英]How do I incorporate my Python methods in the Kivy code?

我用 Python 編寫了一個小程序,它在兩個類別之間隨機選擇並相應地對數據幀進行子集化。 完成后,它會選擇一行並提出問題和一個潛在的選擇。 問題和選擇位於兩列不同列下的數據框行中。 到目前為止,它運行良好; 問題是當我嘗試將其與 kivy 合並時。

我不明白動作的順序是如何發生的。 基本上,我希望能夠通過 kivy 文件在屏幕上包含問題和選擇。 到目前為止,我能夠展示它們,但看起來問題中的值與選擇列中的值不匹配。 我的直覺告訴我,我的 kivy 文件運行“Choosing_category”兩次,而不是只運行一次並獲取適當的輸出。 有誰知道我該如何解決這個問題?

這是我到目前為止所擁有的:

嘗試應用程序

import kivy
from kivy.app import App
import pandas as pd
import numpy as np

from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
kivy.require('1.11.1')

class QuestionWindows(Screen):
    def __init__(self,  **kwargs):
        super(QuestionWindows, self).__init__(**kwargs)
        self.prob = ''
        self.word = ''
        self.choice1 = ''
        self.word = ''
        self.df = pd.DataFrame()

    def _get_df(self):
        df = pd.DataFrame([['new', 'What is you favorite color?', 'blue?', 'blue', 0,0,0,0,0],
                           ['familiar', 'What is your favorite fruit?', 'apple?', 'apple', 0,0,0,0,0],
                           ['new', 'What is your favorite vegetable?', 'carrot?', 'carrot',0,0,0,0,0]],
                          columns=['state', 'questions', 'choice1', 'answer', 'cnt', 'count_correct', 'error_count', 'total_error', 'total_correct'])
        return df

    def choosing_category(self):
        # Loading the dataframe
        self.df = self._get_df()

        # Generating the category for which the question/answer will be sampled from
        self.prob = np.random.choice(['new', 'familiar'], 1, p=[0.7, 0.3])
        # Dealing with the condition on whether the state 'familiar' is not found in the data set
        if self.prob not in self.df['state'].values:
            self.prob = ['new']
            self.prob = self.prob
        else:
            self.prob = self.prob
        # Making sure to present a question/answer that hasn't been presented recently
        if len(self.df[(self.df['state'] == self.prob[0]) & (self.df['cnt'] == 0)]) > 0:
            self.tmp_df = self.df[(self.df['state'] == self.prob[0]) & (self.df['cnt'] == 0)]

        elif len(self.df[(self.df['state'] == prob)]) > 0:
            self.tmp_df = self.df[(self.df['state'] == prob)]
        else:
            self.prob = ['familiar']
            self.tmp_df = self.df[(self.df['state'] == self.prob) & (self.df['cnt'] == 0)]

        # Getting the question from the temporary dataframe
        self.word = np.random.choice(self.tmp_df['questions'])

        # Getting the choice from the question that was previously selected
        self.choice1 = self.df.loc[self.tmp_df[self.tmp_df['questions'] == self.word].index, "choice1"].values
        return str(self.word), str(self.choice1[0])


class QuestionsApp(App):

    def build(self):
        self.screen_manager = ScreenManager()
        self.question_page = QuestionWindows()
        self.screen_manager.add_widget(self.question_page)
        return self.screen_manager


if __name__ == "__main__":

    tryapp = QuestionsApp()
    tryapp.run()

問題.kv

    <SmoothButton@Button>:
    background_color: (0.0, 0.4, 0.95, 1)
    background_normal: ''
    font_size: 20

<QuestionButton@Button>:
    background_color: (0,0,0,0)
    background_normal: ''
    back_color: (0.0, 0.4, 0.95, 1)
    border_radius: [2,2,22,22]
    color: (0.0, 0.4, 0.95, 1)
    bold: True
    canvas.before:
        Color:
            rgba: self.back_color
        RoundedRectangle:
            size: self.size
            pos: self.pos
            radius: self.border_radius

<QuestionWindows>
    #id: question_page
    name: "question_page"
    FloatLayout:
        QuestionButton:
            id: question
            text: root.choosing_category()[0]
            pos_hint: {'x': 0.1, 'y': 0.77}
            size_hint: 0.8, 0.17
            back_color: 1, 1, 1, 1
            background_normal: ''
            font_size: 20
            background_down: ''
        SmoothButton:
            id: choice1
            text: root.choosing_category()[1]
            pos_hint: {'x': 0.1, 'y': 0.27}
            size_hint: 0.8, 0.1

您對choosing_category()方法被調用兩次是正確的。 解決這個問題的一個好方法是使用我建議的on_enter()方法。 您可以將QuestionWindows類修改為:

class QuestionWindows(Screen):
    word = StringProperty('')
    choice1 = StringProperty('')
.
.
.

    def choosing_category(self):
        # Loading the dataframe
        self.df = self._get_df()
        .
        .
        .
        # Getting the question from the temporary dataframe
        self.word = np.random.choice(self.tmp_df['questions'])

        # Getting the choice from the question that was previously selected
        # Note the added [0] at the end of this line
        self.choice1 = self.df.loc[self.tmp_df[self.tmp_df['questions'] == self.word].index, "choice1"].values[0]
        # return str(self.word), str(self.choice1[0])


    def on_enter(self, *args):
        self.choosing_category()

這向QuestionWindows類添加了兩個屬性,這些屬性由choosing_categroy()方法更新,並且可以在kv引用:

<QuestionWindows>:
    #id: question_page
    name: "question_page"
    FloatLayout:
        QuestionButton:
            id: question
            text: root.word
            pos_hint: {'x': 0.1, 'y': 0.77}
            size_hint: 0.8, 0.17
            back_color: 1, 1, 1, 1
            background_normal: ''
            font_size: 20
            background_down: ''
        SmoothButton:
            id: choice1
            text: root.choice1
            pos_hint: {'x': 0.1, 'y': 0.27}
            size_hint: 0.8, 0.1

這種方法的一個優點是您可以簡單地調用choosing_category()並且問題和選擇將更新。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM