我很难弄清楚如何使用ModalView小部件内按钮的on_press属性来正确更改屏幕。
按下ModalView中的按钮,我希望屏幕更改为Game1HomeScreen类和其他GameHomeScreen类中定义的game_screen_name(如下面的NewGameButton和SavedGameButton所做)。这个应用程序有多个游戏,所以我宁愿不直接调用Game1HomeScreen1()。game_screen_name,而是希望保持通用,所以game_screen_name采用从中调用NewGamePopup的类的值。
这样做的好方法是什么?
main.py代码:
class Game1HomeScreen(Screen):
game_screen_name = 'game1_gameboard_screen_name'
class NewGamePopup(ModalView):
pass
class GamesApp(App):
sm = ScreenManager()
def show_new_game_popup(self):
p = NewGamePopup()
p.open()
def prev_screen(self):
self.sm.current = self.game_screen_name #this line does not work of course, because there is no game_screen_name variable in the NewGamePopup class.
.kv代码:
<NewGamePopup>:
size_hint: .5, .3
NewGameBoxLayout:
padding: [10,10,10,10]
orientation: 'vertical'
Label:
font_name: 'fonts/playce.ttf'
font_size: '14sp'
markup: True
text: '[color=#000000]Are you sure? Current game will be erased![/color]'
Button:
font_name: 'fonts/playce.ttf'
font_size: '14sp'
text: 'Confirm'
background_normal: 'img/red_button5.png'
background_down: 'img/red_button5.png'
size_hint_y: None
on_press: root.dismiss(); app.prev_screen()
<Game1HomeScreen>:
GeneralBoxLayout:
BannerGridLayout1:
BodyBoxLayout:
rows: 2
Image:
source: 'img/logo.png'
size_hint: (1.0,.9)
GridLayout:
cols: 2
spacing: '5dp'
padding: '5dp'
size_hint: (1.0,.1)
NewGameButton:
id: game1
on_press:
if saved_game1.disabled == False: app.show_new_game_popup()
else: root.manager.current = root.game_screen_name; saved_game1.disabled = False
SavedGameButton:
id: saved_game1
on_press: root.manager.current = root.game_screen_name;
FooterGridLayout:
ReturnButton:
text: 'Return to main menu'
on_press: root.manager.current = 'home'
答案 0 :(得分:1)
在选择游戏时将游戏画面名称保存在字符串属性中
from kivy.properties import StringProperty
....
class GamesApp(App):
game_screen_name = StringProperty('')
然后您可以根据需要稍后使用sm.current调用。在问题的代码片段中遗漏了太多东西来创建一个工作版本;甚至没有构建方法。