【发布时间】:2017-12-31 03:24:53
【问题描述】:
这是我在这里的第一篇文章,但我会尽量详细。 所以我的应用程序是在 python 中的,并且在 kivy 中涉及一个网格,其中网格中的每个元素都应该包含 4 个额外的小部件,并且可能包含第五个小部件。四个额外的小部件应该在边缘呈十字形,第五个在中间。
问题是,每当我添加一个子小部件时,它都会落在主窗口位置 0,0 的左下角
到目前为止一切顺利。现在我只是想让一个小部件在另一个小部件中正确显示。
这是我的尝试:
<GridCell@Label>
BoxLayout:
orientation:'horizontal'
Button:
text:'One'
size:10,10
size_hint:None,None
为我的应用构建一个 .kv 文件,我会在其中放置一个盒子布局,然后是一个按钮。
我还尝试了以下类配置:
class GridCell(Label):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.root = FloatLayout()
self.button = Button(text="test")
self.button.x = self.root.x
self.button.center_y = self.root.center_y
self.root.add_widget(self.button)
self.add_widget(self.root)
也没有用。
我通过在网格上调用 .add 来添加网格单元,并为 for 循环的每次迭代使用一个新创建的小部件。
所有子小部件显然都已创建,但它们都位于左下角!
这是 gui 的全部代码:
import kivy
import World
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.graphics import Color, Rectangle
kivy.require('1.10.0')
class GridCell(Label):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.root = FloatLayout()
self.button = Button(text="blargh")
self.button.x = self.root.x
self.button.center_y = self.root.center_y
self.root.add_widget(self.button)
self.add_widget(self.root)
def on_size(self, *args):
self.canvas.before.clear()
if self.id is "cliff":
with self.canvas.before:
Color(249 / 255, 6 / 255, 6 / 255, 0.3)
Rectangle(pos=self.pos, size=self.size)
if self.id is "goal":
with self.canvas.before:
Color(6 / 255, 6 / 255, 249 / 255, 0.3)
Rectangle(pos=self.pos, size=self.size)
if self.id is "start":
with self.canvas.before:
Color(11 / 255, 174 / 255, 6 / 255, 0.3)
Rectangle(pos=self.pos, size=self.size)
if self.id is "normal":
with self.canvas.before:
Color(119 / 255, 115 / 255, 115 / 255, 0.3)
Rectangle(pos=self.pos, size=self.size)
class GameGridApp(App):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.grid = GridLayout(cols=8, rows=5)
self.load_into()
def load_into(self):
world = World.World(8, 5)
world.build_gamegrid()
for cell in world.gamegrid:
name = str(cell.name)
grid_cell = GridCell()
grid_cell.text = name
if cell.start:
grid_cell.id = "start"
if cell.goal:
grid_cell.id = "goal"
if cell.cliff:
grid_cell.id = "cliff"
if cell.field:
grid_cell.id = "normal"
self.grid.add_widget(grid_cell)
def build(self):
return self.grid
customLabel = GameGridApp()
customLabel.run()
【问题讨论】:
-
嗨@trashtatur。所以你想知道如何拥有一个
GridLayout对象,每个网格里面有 4/5 个小部件?例如,可能有 4/5Label对象。您可能想在帖子中澄清或突出您的问题。
标签: python user-interface widget kivy kivy-language