我有一个简单的测试程序:
main.py
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.screenmanager import Screen
from kivy.clock import mainthread
class TestScreen(Screen):
@mainthread
def on_pre_enter(self): #Is loaded before kv buttons etc? how make it work
pass
@mainthread
def on_enter(self): #Load after kv buttons etc?
button = Button(text="Work?")
#how now add it to display?
#how control where display it? on end or begin is just about on_pre and on?
class TestApp(App):
pass
if __name__ == '__main__':
TestApp().run()
和test.kv文件
#:import NoTransition kivy.uix.screenmanager.NoTransition
<TestScreen>:
name:'try'
GridLayout:
id:'test'
cols:2
Button:
text:'Test'
on_press:app.root.current='Main'
ScreenManager:
transition: NoTransition()
Screen:
name: 'Main'
GridLayout:
cols:1
Button:
text:'1'
Button:
text:'2'
Button:
text:'Test'
on_press:root.current='try'
TestScreen:
控制kv和python小部件很简单(但是我不知道如何在kv文件中更容易编写小部件等,但仍然需要在python中创建一些用于自动内容)或者更好的只是在python中创建所有的kv文件?我想做这样的事情:总是显示左侧菜单的应用程序,右侧另一个基于屏幕的动态内容屏幕(从菜单中点击)可能是另一个简单的解决方案。有人可以一步一步解释我吗? :)
答案 0 :(得分:0)
AttributeError的解决方案,请在test.kv文件中将“id:'test'”替换为“id:test”。
可以根据菜单中的点击显示具有动态内容的屏幕。但请记住删除退出屏幕时添加的小部件(TestScreen / SettingsScreen)。如果不删除小部件,每次进入屏幕时都会添加每个小部件的重复/倍数(TestScreen / SettingsScreen)。我建议使用on_pre_enter和on_leave方法。有关详细信息,请参阅以下示例。
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
class MyScreenManager(ScreenManager):
pass
class MenuScreen(Screen):
pass
class SettingsScreen(Screen):
def on_pre_enter(self, *args):
self.ids.test.add_widget(Button(text="Work?"))
def on_leave(self, *args):
self.ids.test.remove_widget(self.ids.test.children[0])
class TestApp(App):
title = "Add & Remove Widgets Dynamically"
def build(self):
return MyScreenManager()
if __name__ == "__main__":
TestApp().run()
#:kivy 1.10.0
#:import NoTransition kivy.uix.screenmanager.NoTransition
<MyScreenManager>:
transition: NoTransition()
MenuScreen:
SettingsScreen:
<MenuScreen>:
name: 'menu'
GridLayout:
cols: 1
Button:
text: '1'
Button:
text: '2'
Button:
text: 'Test'
on_press: root.manager.current = 'settings'
<SettingsScreen>:
name:'settings'
GridLayout:
id: test
cols: 2
Button:
text: 'Test'
on_press: root.manager.current = 'menu'