我是kivy的新手,想开始一个小应用程序项目。我想要达到的目标:
到目前为止,我已经找到了一个有效的解决方案,但它的工作方式并不能让我满意。我想要的是在.kv文件中创建ScreenManager和Screens,并让.py文件执行逻辑(通过检查存储中是否存在userdata来加载哪个屏幕)
我试过:
<WindowManager>:
root.check_for_user()
MainWindow:
UserDataWindow:
<MainWindow>:
...
以下是我目前的工作代码:
main.py:
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivy.storage.jsonstore import JsonStore
class LoginWindow(Screen):
nick = ObjectProperty(None)
isle = ObjectProperty(None)
hemisphere_n = ObjectProperty(None)
hemisphere_s = ObjectProperty(None)
def submit(self):
store = JsonStore('store.json')
if self.hemisphere_n.state == 'down' and self.hemisphere_s.state == 'normal':
store.put('user', nickname=self.nick.text, island=self.isle.text, hemisphere="north")
elif self.hemisphere_n.state == "normal" and self.hemisphere_s.state == "down":
store.put('user', nickname=self.nick.text, island=self.isle.text, hemisphere="south")
class MainWindow(Screen):
pass
class WindowManager(ScreenManager):
pass
kv = Builder.load_file("my.kv")
sm = WindowManager()
store = JsonStore('store.json')
screens = [MainWindow(name="main"), LoginWindow(name="login")]
for screen in screens:
sm.add_widget(screen)
if store.exists('user'):
print("exists")
sm.current = "main"
else:
print("not found")
sm.current = "login"
class MainApp(App):
def build(self):
return sm
if __name__ == '__main__':
MainApp().run()
my.kv:
#:kivy 1.11.1
<MainWindow>:
FloatLayout:
Label:
text:
Button:
text: "Go Back"
pos_hint: {"x": 0.45, "top": 0.5}
size_hint: (0.1, 0.05)
on_release:
app.root.current = "login"
<LoginWindow>:
nick: nickname
isle: island
hemisphere_n: hemisphere_n
hemisphere_s: hemisphere_s
FloatLayout:
Label:
text: "Nickname:"
pos_hint: {"x": 0.45, "top": 0.7}
size_hint: (0.1, 0.05)
TextInput:
id: nickname
multiline: False
pos_hint: {"x": 0.4, "top": 0.65}
size_hint: (0.2, 0.05)
Label:
text: "Island Name:"
pos_hint: {"x": 0.45, "top": 0.6}
size_hint: (0.1, 0.05)
TextInput:
id: island
multiline: False
pos_hint: {"x": 0.4, "top": 0.55}
size_hint: (0.2, 0.05)
Label:
text: "Hemisphere:"
pos_hint: {"x": 0.45, "top": 0.5}
size_hint: (0.1, 0.05)
ToggleButton:
id: hemisphere_n
text: "North"
group: "hemisphere"
state: "down"
pos_hint: {"x": 0.41, "top": 0.45}
size_hint: (0.08, 0.05)
ToggleButton:
id: hemisphere_s
text: "South"
group: "hemisphere"
pos_hint: {"x": 0.51, "top": 0.45}
size_hint: (0.08, 0.05)
Button:
text: "Submit"
pos_hint: {"x": 0.45, "top": 0.38}
size_hint: (0.1, 0.05)
on_press:
root.submit()
on_release:
app.root.current = "main"
在某些方面,请忽略未解决的问题。我想在做进一步的工作之前让它工作起来。 它现在转到主屏幕(当我将屏幕添加到screenmanager时),然后检查用户数据并最终切换到登录。你有什么建议吗? 提前谢谢
您看到的是
transition
动画。您可以这样使用NoTransition()
来消除这种情况:你可以把你的
Screen
选择逻辑放在任何你想要的地方。下面是一个将其放入WindowManager
类的示例:然后可以在
build()
方法中调用select_start_screen()
:在@John的答案中添加一个空白屏幕怎么样
相关问题 更多 >
编程相关推荐