我有一个由按钮组成的 GridLayout。当您单击其中任何一个时,按下的会改变颜色。
在这个网格下,我有一个开始按钮,当点击时,所有按钮都应该变成一样的,但这不会发生。单击开始后我尝试显示每个按钮的当前颜色,但输出显示到处都是相同的值
这是python代码:
import kivy
kivy.require('1.9.1') # Ваша версия может отличаться
from kivy.app import App
from kivy.uix.button import Button
from kivy.properties import ListProperty
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
import numpy as np
class Field(GridLayout):
def __init__(self, *args, **kwargs):
self.rows = 5
self.cols = 5
self.status = ListProperty([[0 for _ in range(5)] for _ in range(5)])
super(Field, self).__init__(*args, **kwargs)
self.buttons = [[None for _ in range(self.cols)] for _ in range(self.rows)]
for row in range(self.rows):
for col in range(self.cols):
grid_entry = GridEntry(coords=(row, col))
grid_entry.bind(on_press=self.button_pressed)
self.add_widget(grid_entry)
self.buttons[row][col] = grid_entry
def button_pressed(self, button):
x, y = button.coords
colors = {0: (0, 1, 0, 1), 1: (1, 1, 1, 1)}
button.background_color = colors[self.status.defaultvalue[x][y]]
self.status.defaultvalue[x][y] ^= 1
print(list(map(lambda x: x.background_color, self.children)))
def get_buttons(self):
return self.buttons
def make_new_population(self):
pop = np.array(self.status.defaultvalue)
neighbors = sum([
np.roll(np.roll(pop, -1, 1), 1, 0),
np.roll(np.roll(pop, 1, 1), -1, 0),
np.roll(np.roll(pop, 1, 1), 1, 0),
np.roll(np.roll(pop, -1, 1), -1, 0),
np.roll(pop, 1, 1),
np.roll(pop, -1, 1),
np.roll(pop, 1, 0),
np.roll(pop, -1, 0)
])
neighbors = (neighbors == 3) | (pop & (neighbors == 2))
for i in range(self.rows):
for j in range(self.cols):
self.status.defaultvalue[i][j] = neighbors[i, j]
def paint(self):
print(list(map(lambda x: x.background_color, self.children)))
self.make_new_population()
for i in self.children:
x, y = i.coords
was = i.background_color
i.background_color = (1, 1, 1, 1)
if was != i.background_color:
print(x, y)
class LifeGrid(BoxLayout):
def __init__(self, *args, **kwargs):
super(LifeGrid, self).__init__(*args, **kwargs)
self.field = Field()
self.in_game = False
def start(self, button):
self.in_game = True
self.paint()
def paint(self):
if self.in_game:
self.field.paint()
class GridEntry(Button):
coords = ListProperty([0, 0])
class LifeApp(App):
def build(self):
return LifeGrid()
if __name__ == '__main__':
LifeApp().run()
这是基维代码:
<LifeGrid>:
id: lifegrid
orientation: 'vertical'
Field:
cols: 5
rows: 5
GridLayout:
height: '50dp'
width: self.parent.width
size_hint: None, None
cols: 2
rows: 1
row_default_width: self.parent.width // 2
Button:
id: start_button
on_press: lifegrid.start(start_button)
text: 'Start'
font_size: '20dp'
Button:
id: restart_button
on_press: lifegrid.restart(restart_button)
text: 'Restart'
font_size: '20dp'
<GridEntry>:
font_size: self.height
原来值得先
__init__
写buttons = ListProperty([[None for _ in range(5)] for _ in range(5)])
,之后写我不明白为什么会这样。我将非常感谢有人会解释为什么我不能只是经历
children
并改变background_color
周期