我正在Kivy中构建一个GUI,该窗口需要水平调整大小。我有三个按钮,两个小按钮在一个更大的按钮的两侧,当窗口变得太窄时,我想更改位置。
范例图片
这些按钮需要居中对齐。我可以通过在任一侧使用填充来做到这一点,但是当窗口变得太小时,填充也会移动到新行,这将使按钮在中心对齐。我也尝试过尝试使用堆栈布局,但是没有设法使任何东西都能正确对齐。
是否有一个简单的解决方案?
最小的工作示例:
from kivy.uix.stacklayout import StackLayout
from kivy.uix.button import Button
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.core.window import Window
class Home(Widget):
def __init__(self, **kwargs):
super(Home, self).__init__(**kwargs)
BUTTON_WIDTH = 0.1
BUTTON_HEIGHT = 0.1
layout = StackLayout(orientation='lr-tb',
size=(Window.width, Window.height),
pos=self.pos
)
self.add_widget(layout)
button1 = Button(text='1',
size_hint=(BUTTON_WIDTH, BUTTON_HEIGHT)
)
big_button = Button(text='big button',
size_hint=(3*BUTTON_WIDTH, BUTTON_HEIGHT)
)
button2 = Button(text='2',
size_hint=(BUTTON_WIDTH, BUTTON_HEIGHT)
)
layout.add_widget(button1)
layout.add_widget(big_button)
layout.add_widget(button2)
class TestApp(App):
def build(self):
return Home()
if __name__ == '__main__':
TestApp().run()
对于在您的应用中进行重大更改,我深表歉意,但是我认为,将类扩展Layout
而不是向类中添加Layout
,Widget
可以简化代码。我还用于kv
设置Home
类的成员。我将大按钮的宽度设置为其纹理(文本)的宽度,以将文本保留在按钮内。
无论如何,这是我认为您想要的代码版本。我使用on_size
方法(在更改大小时调用)对按钮进行重新排列:
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
Builder.load_string('''
#:set BUTTON_WIDTH 0.1
#:set BUTTON_HEIGHT 0.1
<Home>:
Button:
id: b1
text: '1'
size_hint: (BUTTON_WIDTH, BUTTON_HEIGHT)
pos_hint: {'x':0, 'center_y': 0.5}
Button:
id: big
text: 'big button'
size_hint: (None, BUTTON_HEIGHT)
size_x: self.texture_size[0]
pos_hint: {'center_x':0.5, 'center_y': 0.5}
Button:
id: b2
text: '2'
size_hint: (BUTTON_WIDTH, BUTTON_HEIGHT)
pos_hint: {'right':1.0, 'center_y': 0.5}
''')
class Home(FloatLayout):
def __init__(self, **kwargs):
super(Home, self).__init__(**kwargs)
self.pos_switched = False # keeps track of whether things have been re-arranged
def on_size(self, instance, new_size):
if not self.pos_switched and instance.width <= self.ids.b1.width + self.ids.big.width + self.ids.b2.width:
# not enough room for the buttons side-by-side, re-arrange
self.ids.b1.pos_hint = {'center_x': 0.5}
self.ids.b1.y = self.ids.big.y + self.ids.big.height
self.ids.b2.pos_hint = {'center_x': 0.5}
self.ids.b2.y = self.ids.big.y - self.ids.b2.height
self.pos_switched = True
elif self.pos_switched and instance.width > self.ids.b1.width + self.ids.big.width + self.ids.b2.width:
# ok to move the buttons back to original positions
self.ids.b1.pos_hint = {'x':0, 'center_y': 0.5}
self.ids.b2.pos_hint = {'right':1.0, 'center_y': 0.5}
self.pos_switched = False
class TestApp(App):
def build(self):
return Home()
if __name__ == '__main__':
TestApp().run()
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句