我有一个功能,可以在名为block_screen的屏幕上显示保存的单词。如果我通过单击root.d_sl()之类的BlockScreen中的按钮在我的.kv文件中调用它,则效果很好。但是,我希望在打开此屏幕时显示此内容,而不是在按此屏幕上的按钮进行显示时显示。因此,我在App中将此BlockScreen称为“ b”,并在我的home_screen中将其用作app.b.d_sl(),并且它仅打印部分而不显示单词。



.py file:
from kivy.app import App
from kivy.uix.screenmanager import Screen
from kivy.lang import Builder
import slovar

class HomeScreen(Screen):
    pass

...screens....

class OpenScreen(Screen):
    def ob_slova(self):
        self.ids.text_label.text = slovar.slova_obichnie()
        f = open('nicknames.txt', 'a')
        f.write(self.ids.text_label.text + '\n')
        f.close()

class BlockScreen(Screen):
    def d_sl(self):
        self.ids.label_text.text = "ppp"
        f1 = open('nicknames.txt', 'r')
        for i in f1:
            self.ids.label_text.text += i
        f1.close()
        if self.ids.label_text.text == "":
            print('p')
        else:
            print(self.ids.label_text.text)


GUI = Builder.load_file('game.kv')
class GameApp(App):
    b = BlockScreen()
    def build(self):
        return GUI

    def change_screen(self, screen_name):
        screen_manager = self.root.ids['screen_manager']
        screen_manager.current = screen_name

GameApp().run()




homescreen.kv file:
#:kivy 1.10.1
<HomeScreen>:
    Button:
         size_hint: .7, .1
         pos_hint:{"x":.15, "y":.47}
         background_normal: 'kn1.png'
         text: "HISTORY"
         font_size: self.height - 20
         valign: 'middle'
         halign: 'center'
         padding_x: 56,56
         on_release:
             app.change_screen('block_screen')
             app.b.d_sl()





blockscreen.kv file:
#:kivy 1.10.1
<BlockScreen>:
    Button:
        text: "Z"
        font_size: self.height - 24
        valign: 'center'
        halign: 'center'
        padding: 2,2
        size_hint: .5, .08
        pos_hint: {'x':.5, 'y':.0}
        background_normal: 'kn2.png'
        on_release:
            root.d_sl()


main kv file:
#:kivy 1.10.1
#:include homescreen.kv
#:include openscreen.kv
#:include blockscreen.kv
#:include engscreen.kv

GridLayout:
    cols: 1
    ScreenManager:
        id: screen_manager
        HomeScreen:
            name: "home_screen"
            id: home_screen
        OpenScreen:
            name: "open_screen"
            id: open_screen
        BlockScreen:
            name: "block_screen"
            id: block_screen
        EngScreen:
            name: "eng_screen"
            id: eng_screen


我该如何解决这个问题?

最佳答案

b = BlockScreen()中的行App创建一个新的BlockScreen,您用app.b引用该BlockScreen,但是您的应用程序不会显示该BlockScreen。显示的kv由主BlockScreen文件创建。要访问显示的app.root.ids.block_screen.d_sl(),我认为您需要类似b = BlockScreen()的内容。并删除行。

关于python - 当我从应用程序调用函数时,如何正确调用函数?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55554211/

10-13 04:46