[英]Kivy: Getting a fixed-size widget to display in the centre of the window
關於這個,我一直在扯頭發。 我有一個自定義窗口小部件,該子類將RelativeLayout
子類化,該大小必須為固定大小。 我希望此小部件顯示在窗口的中央。 我還希望其他普通的小部件(即按鈕)顯示在其周圍。 經過一整天的努力之后,我現在發現在添加按鈕后,它阻止了我使它表現出來的所有嘗試。 請有人可以看看我的.kv文件,並告訴我我要去哪里了嗎?
#:kivy 1.8.0
# This is my fixed-size widget
<DrawableGrid>:
# Note: this is just an example size to keep things simple
size: 500, 500
canvas:
Color:
rgba: 1, 0, 0, 1
Rectangle:
pos: self.pos
size: self.size
# This subclasses BoxLayout
CustomLayout:
orientation: "vertical"
# I put my DrawableGrid inside an AnchorLayout in the hope that it might
# behave in some way like the documentation says it does. No such luck.
# This should be taking up the entire top half of the window.
AnchorLayout:
size_hint: 1, 1
# This anchor_x/anchor_y stuff seemingly does nothing.
anchor_x: "center"
anchor_y: "center"
# This should be appearing as a red rectangle of size 500x500
DrawableGrid:
# This next line was needed to set a custom size in the first place
size_hint: 0, 0
# This appears exactly as expected, filling the bottom half of the window.
Button:
id: next_button
text: "Next"
因此,重申一下,我目前想要的是:
我實際上得到的是: (如您所見,明顯沒有紅色方塊)
我嘗試了多種不同的方法(有些比其他方法更笨拙)來完成這項工作,但無濟於事。 請有人建議我該如何解決?
我認為您想要一個垂直的BoxLayout作為您的根小部件。 根目錄中的第一個小部件將是RelativeLayout,第二個將是您的按鈕。 這將為您提供50/50的分屏顯示。 RelativeLayout將包含您的500x500小部件,其位置為(self.parent.width-self.width)/ 2,(self.parent.height-self.height)/ 2
注意:在以下代碼示例中,我將100x100用作窗口小部件,因為500x500無法在我的屏幕上顯示。
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
kv = """
<Test>:
orientation: "vertical"
RelativeLayout:
GridLayout:
pos: (self.parent.width-self.width)/2, (self.parent.height-self.height)/2
size_hint: None, None
size: 100, 100
canvas:
Color:
rgba: 1, 0, 0, 1
Rectangle:
pos: self.pos
size: self.size
Button:
text: "Next"
"""
Builder.load_string(kv)
class Test(BoxLayout):
def __init__(self, **kwargs):
super(Test, self).__init__(**kwargs)
class TestApp(App):
def build(self):
return Test()
if __name__ == '__main__':
TestApp().run()
RelativeLayout
相對於布局位置定位所有子項。 這包括所有繪圖說明-因為那才是所有孩子的真實情況。 布局的所有子項都繪制在canvas
,因此canvas
內使用的位置必須相對於布局本身! 因此,當您在canvas
說要在self.pos
處繪制矩形時,該位置將像其他任何子項一樣平移(換句話說,該矩形在self.pos + self.pos
處繪制)。 如果將矩形pos更改為0, 0
則它將按預期繪制。
為了幫助說明,這是RelativeLayout
的默認樣式(來自kivy/data/style.kv
):
<RelativeLayout>:
canvas.before:
PushMatrix
Translate:
xy: self.pos
canvas.after:
PopMatrix
您在canvas
放置的所有內容都在canvas.before
和canvas.after
之間。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.