【问题标题】:Can't get button to work in Kivy无法让按钮在 Kivy 中工作
【发布时间】:2016-09-14 21:55:27
【问题描述】:

我试图让这个按钮工作,但不知道出了什么问题。 我真的可以使用一些帮助,因为我是 kivy 的新手。当我运行代码时,按钮会弹出,但是当您单击它时,什么也没有发生。为什么它不起作用?

顺便说一句,我知道一旦你进入下一页,什么都不会发生,但现在我只想到达那里。

这是完整的代码和kv文件。

import kivy
kivy.require('1.9.1')

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput  
from kivy.uix.label import Label
from kivy.uix.button import Button

class StartScreen(Widget):
    def __init__(self, **kwargs):
      super(StartScreen,self).__init__(**kwargs)
      self.StartGame = Button(text="Start Game")
      self.StartGame.bind(on_press=self.on_press)
      self.add_widget(self.StartGame)

def on_press(self,instance):

    return LoginScreen()

class LoginScreen(GridLayout):
    def __init__(self, **kwargs):
        super(LoginScreen,self).__init__(**kwargs)
        self.cols = 2



class MyApp(App):
 def build(self):
    return StartScreen()



if __name__ == '__main__':
    MyApp().run()

KV 文件

#:kivy 1.9.1



<StartScreen>:
  Label:
    font_size: 120
    center_x: root.width / 2
    top: root.top - 100
    text: "Starfire"



<LoginScreen>
  f_username: username 
  f_password: password 
    GridLayout:
    rows: 2
    padding: 5
    spacing: 5
    Label:
        text: "User Name:"
    TextInput:
        id: username
    Label:
        text: 'Password'
    TextInput:
        id: password
        password: True

【问题讨论】:

    标签: python-3.x button kivy


    【解决方案1】:

    从 on_press 方法返回一个小部件不会使其成为根对象。

    def on_press(self,instance): 
        return LoginScreen() # will not do anything like you expected*
    

    您需要查看弹出窗口和屏幕管理器:

    https://kivy.org/docs/api-kivy.uix.screenmanager.html

    https://kivy.org/docs/api-kivy.uix.popup.html?highlight=popup#module-kivy.uix.popup

    选择适合您的。

    【讨论】:

      【解决方案2】:

      这是一个工作示例:

      from kivy.app import App
      from kivy.uix.screenmanager import ScreenManager, Screen, SlideTransition
      
      
      screen_manager = ScreenManager(transition=SlideTransition())
      
      
      class RootScreen(Screen):
      
          settings_button = Button(text='Settings')
          settings_button.bind(on_press=screen_manager.switch_to(SettingsScreen())
      
      
      class SettingsScreen(Screen):
          pass
      
      
      class WifiApp(App):
      
          def build(self):
              screen_manager.add_widget(RootScreen(name='main'))
              screen_manager.add_widget(SettingsScreen(name='settings'))
              return screen_manager
      
      
      if __name__ == '__main__':
          WifiApp().run()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2022-09-23
        • 2017-08-18
        • 1970-01-01
        • 2018-08-17
        • 2018-09-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多