以下代码的目的是显示一个按钮列表(如菜单),您现在可以使用它来更改屏幕……根本不起作用,我看不到问题是
我以前得到“ typeerror init ()接受1个位置参数,但给出了2个”,并且通过为屏幕创建一个新类使其消失,然后我得到了app.root实例设置,现在我没有任何错误
import kivy
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget
import random
import main
kivy.require('1.10.1')
class Game(BoxLayout):
layout = BoxLayout(padding=5, orientation="vertical")
colors = [(1, 0, 0, 1), (0, 1, 0, 1), (1, 0, 1, 1), (0, 0, 1, 1)]
Buttonz= ('Button1', 'Button2', 'Button3', 'Button4')
def Buttons(self):
for i in range(len(self.Buttonz)):
btn = Button(text=self.Buttonz[i],background_color=random.choice(self.colors))
self.layout.add_widget(btn)
btn.bind(on_press=main.Political)
return self.layout
class Main(App):
title='ButtonGame'
def build(self):
return Game()
if __name__ == '__main__':
Main().run()
我希望代码显示4个按钮,并从我声明的4个按钮中随机选择颜色,但是它显示的是全黑屏幕。这些按钮应该从不同的模块切换到另一个屏幕。也许我应该在两个模块中都使用ScreenManager? (对不起,我试图格式化代码的缩进方式很糟糕,但我不能)
答案 0 :(得分:0)
您需要添加一个构造函数以调用Buttons
方法。
class Game(BoxLayout):
layout = BoxLayout(padding=5, orientation="vertical")
colors = [(1, 0, 0, 1), (0, 1, 0, 1), (1, 0, 1, 1), (0, 0, 1, 1)]
Buttonz = ('Button1', 'Button2', 'Button3', 'Button4')
def __init__(self, **kwargs):
super(Game, self).__init__(**kwargs)
self.Buttons()
self.add_widget(self.layout)
def Buttons(self):
for i in range(len(self.Buttonz)):
btn = Button(text=self.Buttonz[i], background_color=random.choice(self.colors))
self.layout.add_widget(btn)
btn.bind(on_press=main.Political)
以下示例仅使用一个BoxLayout
小部件作为根。
import kivy
kivy.require('1.10.1')
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
import random
# import main
class Game(BoxLayout):
colors = [(1, 0, 0, 1), (0, 1, 0, 1), (1, 0, 1, 1), (0, 0, 1, 1)]
Buttonz = ('Button1', 'Button2', 'Button3', 'Button4')
def __init__(self, **kwargs):
super(Game, self).__init__(**kwargs)
self.padding = 5
self.orientation = "vertical"
self.Buttons()
def Buttons(self):
for i in range(len(self.Buttonz)):
btn = Button(text=self.Buttonz[i], background_color=random.choice(self.colors))
self.add_widget(btn)
# btn.bind(on_press=main.Political)
class Main(App):
title = 'ButtonGame'
def build(self):
return Game()
if __name__ == '__main__':
Main().run()