我是Python UI编程的新手,我正在尝试Kivy.我想在屏幕上设置一些按钮,但按钮不会从窗口的右下角移动.我想知道是否有人能指出我做错了什么或错过了什么?
vgx.kv:
#:kivy 1.9.1
<VgxMainScreen>:
BoxLayout:
size_hint: 0.2,0.2
size: 200, 100
orientation: 'vertical'
Button:
text: 'Game Select'
Button:
text: 'Options'
Button:
text: 'Controllers'
<VgxUI>:
AnchorLayout:
anchor_x: 'center'
VgxMainScreen:
size_hint: 0.2,0.2
<VgxApp>:
FloatLayout:
VgxUI:
center: 0.5, 0.5
Run Code Online (Sandbox Code Playgroud)
VgxApp.py:
import kivy
from kivy.app import App
from kivy.uix.widget import Widget
kivy.require('1.9.1')
class VgxMainScreen(Widget):
pass
class VgxUI(Widget):
pass
class VgxApp(App):
def build(self):
return VgxUI()
if __name__ == '__main__':
VgxApp().run()
Run Code Online (Sandbox Code Playgroud)
编辑:调试你的小部件正在发生的事情的最佳方法是改变他们的背景颜色:).
canvas.before:
Color:
rgba: X, X, X, 1
Rectangle:
pos: self.pos
size: self.size
Run Code Online (Sandbox Code Playgroud)
问题是你的BoxLayout没有相对于它的父级定位,即使它在里面.
我在这里做的是我使用以下方法定位BoxLayout其父级的大小和位置:
size: self.parent.size
pos: self.parent.pos
Run Code Online (Sandbox Code Playgroud)
我也将size属性移到了VgxMainScreen,VgxUI因为我认为这是更常见的用例(你可以有多个VgxMainScreen不同大小的s).完整代码与背景颜色:
#:kivy 1.9.1
<VgxMainScreen>:
size_hint: None, None
canvas.before:
Color:
rgba: 1, 0, 0, 1 # red
Rectangle:
pos: self.pos
size: self.size
BoxLayout:
canvas.before:
Color:
rgba: 0, 0, 1, 1 # blue
Rectangle:
pos: self.pos
size: self.size
size: self.parent.size # important!
pos: self.parent.pos # important!
orientation: 'vertical'
Button:
text: 'Game Select'
Button:
text: 'Options'
Button:
text: 'Controllers'
<VgxUI>:
AnchorLayout:
canvas.before:
Color:
rgba: 1, 1, 1, 1 # white
Rectangle:
pos: self.pos
size: self.size
size: self.parent.size
anchor_x: 'center'
anchor_y: 'center'
VgxMainScreen:
size: 200, 100
<VgxApp>:
FloatLayout:
VgxUI:
center: 0.5, 0.5
Run Code Online (Sandbox Code Playgroud)
还有另一个解决方案.
您可以使用RelativeLayout它内部的所有小部件将相对于此布局定位.
<VgxMainScreen>:
size_hint: None, None
RelativeLayout:
pos: self.parent.pos
size: self.parent.size
BoxLayout:
orientation: 'vertical'
Button:
text: 'Game Select'
Button:
text: 'Options'
Button:
text: 'Controllers'
Run Code Online (Sandbox Code Playgroud)
在使用Kivy时,我个人多次摸不着头脑,并想知道为什么我的小部件没有定位,因为我认为他们应该:).
| 归档时间: |
|
| 查看次数: |
6892 次 |
| 最近记录: |