我很难弄清楚如何使用 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'
最佳答案
选择游戏时将游戏屏幕名称保存在字符串属性中
from kivy.properties import StringProperty
....
class GamesApp(App):
game_screen_name = StringProperty('')
然后您可以稍后根据需要使用 sm.current 调用。问题中的代码片段中遗漏了太多内容,无法创建工作版本;甚至连构建方法都丢失了。
关于python - Kivy - 在 ModalView 中按下按钮后更改屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26127117/