問(wèn)題描述
我想知道如何使用綁定到按鈕的 on_press 事件來(lái)更改屏幕,而不使用 KV 文件/KV 語(yǔ)言.
I would like to know how to change screens using an on_press event binded to a button, without using a KV file/KV language.
我已通讀 Kivy 文檔,但只能使用 KV 文件找到解決方案.
I have read through the Kivy documentation, but have only been able to find solutions using a KV file.
例子:
on_press: root.manager.current = 'screen2'
我還可以使用以下方法更改主 python 文件中的屏幕:
I can also change the screen in the main python file using:
screenmanager.current = 'screen2'
但我不知道如何使用按鈕來(lái)達(dá)到同樣的效果.
But I cant figure out how to achieve the same using a button.
推薦答案
實(shí)現(xiàn)此目的的一種簡(jiǎn)單方法是定義自己的按鈕子類(lèi):
One simple way to accomplish this is to define your own button subclass:
class ScreenButton(Button):
screenmanager = ObjectProperty()
def on_press(self, *args):
super(ScreenButton, self).on_press(*args)
self.screenmanager.current = 'whatever'
按下按鈕時(shí)會(huì)自動(dòng)調(diào)用on_press方法,所以會(huì)改變screenmanager的current
屬性.
The on_press method is automatically called when the button is pressed, so the screenmanager's current
property will be changed.
然后你可以有類(lèi)似的代碼:
Then you can have code something like:
sm = ScreenManager()
sc1 = Screen(name='firstscreen')
sc1.add_widget(ScreenButton(screenmanager=sm))
sc2 = Screen(name='whatever')
sc2.add_widget(Label(text='another screen'))
sm.add_widget(sc1)
sm.add_widget(sc2)
單擊按鈕應(yīng)根據(jù)需要切換屏幕.
Clicking the button should switch the screens as required.
另一種方式(這可能是 kv 語(yǔ)言實(shí)際的做法)是手動(dòng)使用 bind
方法.
Another way (which is probably how kv language actually does it) would be to manually use the bind
method.
def switching_function(*args):
some_screen_manager.current = 'whatever'
some_button.bind(on_press=switching_function)
這意味著只要按下 some_button
就會(huì)調(diào)用 switching_function
.當(dāng)然,關(guān)于如何以及何時(shí)定義函數(shù),這里有很大的靈活性,因此(例如)您可以做一些更一般的事情,比如將屏幕管理器作為第一個(gè)參數(shù)傳遞給函數(shù).
This would mean that switching_function
is called whenever some_button
is pressed. Of course there is a lot of flexibility here regarding how and when you define the function, so (for instance) you could do something more general like pass the screenmanager as the first argument to the function.
我沒(méi)有測(cè)試這段代碼,它不是一個(gè)完整的應(yīng)用程序,但希望含義清楚.任何一種方法都應(yīng)該可以正常工作,您可以選擇看起來(lái)最明智的方法.稍后我可能會(huì)構(gòu)建一個(gè)更完整的示例.
I didn't test this code and it isn't a complete app, but hopefully the meaning is clear. Either method should work fine, you can choose the way that seems most sensible. I might construct a more complete example later.
這篇關(guān)于Kivy:使用 on_press 事件在屏幕管理器中更改屏幕的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!