在kivy按钮点击时不会发生屏幕切换

时间:2015-05-06 12:40:53

标签: python user-interface kivy

我是kivy的新手。我想在注册'时切换到另一个屏幕(注册屏幕)。在主屏幕(登录屏幕)上单击按钮。这是python代码:

import kivy
kivy.require('1.9.0') 
import ConfigParser
from kivy.app import App
from kivy.core.window import Window
from kivy.uix.screenmanager import Screen, ScreenManager

Window.size = (700, 550)

class LoginPage(Screen):
    def switch_screen(*args):
       global sm
       print "i am in login and will switch to signup"
       sm.current = 'signup'

class SignUp(Screen):
    print "signup screen"
    pass

sm = ScreenManager()
sm.add_widget(LoginPage(name="login"))
sm.add_widget(SignUp(name="signup"))

class Test(App):
    icon = "C:\Users\shru\Desktop\download.jpg"
    title = "Member Login"
    def build(self):
        return sm

if __name__ == "__main__":
   Test().run()

这是.kv代码

<LoginPage>:
      canvas:
         Rectangle:
            source: "C:\Users\shru\Desktop\m.jpg"
            size: self.size

      Widget:
         Button:
            size: 90,35
            pos: 380,200
            font_size:15
            background_color: (1,1,1,0.3)
            text: "SignUp"
            on_press: root.switch_screen()

<SignUp>:
     canvas:
         Rectangle:
           source: "C:\Users\shru\Desktop\m.jpg"
           size: self.size
     Widget:
         Button:
           size: 90,35
           pos: 380,200
           font_size:15
           background_color: (1,1,1,0.3)
           text: "hello"

执行后返回空白屏幕。难道我做错了什么?

谢谢

2 个答案:

答案 0 :(得分:2)

您可以在运行应用程序之前创建窗口小部件的实例,这也是在加载kv文件之前,因此您的kv规则未应用,您什么也看不到。

sm =等移动到构建方法中以解决此问题,在运行此方法之前加载kv文件。

答案 1 :(得分:1)

代码中的这些更改使其有效:

sm = ScreenManager()

class Test(App):
    def build(self):
       sm.add_widget(LoginPage(name="login"))
       sm.add_widget(SignUp(name="signup"))
       return sm

if __name__ == "__main__":
      Test().run()