python - 在 RelativeLayout 中嵌入 GridLayout
问题描述
我正在与 Kivy 斗争,以使其正确显示按钮。我想创建一个在 for 循环中创建的按钮网格,并将它们显示在 RelativeLayout 内的网格中。这导致按钮堆叠在另一个之上。请看下面:
主要.py:
import kivy
from kivy.app import App
from kivy.uix.anchorlayout import AnchorLayout
from kivy.lang.builder import Builder
from kivy.uix.button import Button
Builder.load_file('TopMenu.kv')
Builder.load_file('BottomMenu.kv')
Builder.load_file('Center.kv')
Builder.load_file('Left.kv')
class mainHolder(AnchorLayout):
pass
class MainApp(App):
def build(self):
self.title = "NAZWA APLIKACJI"
#return Label(text = "Hello, world")
return mainHolder()
if __name__ == '__main__':
MainApp().run()
主文件.kv
<MainHolder>:
anchor_x: 'left'
anchor_y: 'top'
BoxLayout:
orientation: 'vertical'
#anchor_x: 'left'
#anchor_y: 'top'
TopMenu:
id: _top_menu
#size_hint: 1, 0.1
#height: 0, 1
canvas.before:
Color:
rgba:0.5, 0.5, 0.5, 0.5
Rectangle:
pos: self.pos
size: self.size
Center:
BottomMenu:
中心.kv:
<Center@GridLayout>:
cols: 2
size_hint: 1, 1
Left:
Label:
text: 'prawa'
左.py:
from kivy.uix.relativelayout import RelativeLayout
from kivy.uix.button import Button
class Left(RelativeLayout):
def __init__(self, **kwargs):
super(RelativeLayout, self).__init__(**kwargs)
print("Left is alive!")
for i in range(0, 11):
print("Adding button: " + str(i))
but = Button(text="X" + str(i))
self.add_widget(but)
最后,left.kv:
#:import Left Left
<Left>:
size_hint: 1.3, 1
pos_hint: 1, 1
这种方法创建了以下内容: 我尝试将 RelativeLayout 更改为 GridLayout,但按钮看起来大致相同,不同之处在于它们位于最左下角,所以我猜 RelativeLayout 是开始将它们定位的好方法一个正确的地方。
所以我在 Left.kv 中手动添加了一些 GridLayout,如下所示:
<Left>:
size_hint: 1.3, 1
pos_hint: 1, 1
GridLayout:
cols: 4
Button:
text: "t2"
Button:
text: "t2"
Button:
text: "t2"
Button:
text: "test"
这很好用。因此,在此之后,我创建了另一个类,这次是 GridLayout,但这根本不起作用 - 抱歉,我没有代码了,删除它,因为它没有结果。此外,如上所示添加 GridLayout 不会导致 add_widget() 将其添加到正确的位置。你们能帮帮我吗?我对此感到非常沮丧,谷歌没有提供任何合理的答案。我想从这个应用程序设计的一开始这可能是错误的方法,但老实说,我不知道“好”点可能是什么。
约翰安德森谢谢你!这就像一个魅力。我是如此接近,但到目前为止,我永远不会找到这个。干杯! :-)
解决方案
我认为使用 aGridLayout
是一种合理的方法。我稍微修改了你的Left
课程来做到这一点:
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
class Left(GridLayout):
def __init__(self, **kwargs):
# corrected the call to super
super(Left, self).__init__(**kwargs)
print("Left is alive!")
# set the number of columns in this grid
self.cols = 5
for i in range(0, 11):
print("Adding button: " + str(i))
but = Button(text="X" + str(i))
self.add_widget(but)
推荐阅读
- python - 无论用户名如何,在桌面上打开文件
- visual-studio-code - VSCode - 在子进程断点处暂停程序
- python - 如何找到数据框的顶部任何百分比?
- spring-boot - 轴突事件处理程序读取所有事件每次重启
- javascript - 有没有办法在提交时更改表单值
- python - 查找python支持的最大正数
- pyspark - pyspark saveAsTable 不保存到虚拟驱动器(谷歌驱动器)
- angular-cli - 未捕获(承诺),打开新的 Angular 项目时无法读取配置器
- python - TypeError:尝试绘制函数时,只能将大小为 1 的数组转换为 Python 标量
- go - 在golang中有多个返回值的函数返回1个值