首页 > 解决方案 > pos_hint、DragBehavior 和 FloatLayout - 可能的冲突 - 如何解决?

问题描述

我有一个带有 04 个按钮的 FloatLayout,使用 pos_hint(左、右、上、下)定位。其中 pos_hint 为零,则 Btn 有一个 DoF,否则无法移动。我试着用 pos 来定位我的按钮,但这是不可能的。如何设置初始位置并使 btns 可拖动?感谢您的帮助!:)

import kivy
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.behaviors import DragBehavior
from kivy.lang import Builder

kv = '''
<DragBtn>:
    # Define the properties for the DragLabel
    drag_rectangle: self.x, self.y, self.width, self.height
    drag_timeout: 10000000
    drag_distance: 0
    
    size_hint: None, None
    size: 150,150        
    on_touch_down: print(self.pos)

FloatLayout:
                  ##########################
                  # Btn2                   #
                  #                   Btn4 #
                  # Btn1     Btn3          #
                  ##########################    
    DragBtn:
        text: 'Btn1'
        pos_hint: {'left':0, 'bottom':0} # free
    DragBtn:
        text: 'Btn2'
        pos_hint: {'left':0, 'top':1} # just move on x
    DragBtn:
        text: 'Btn3'
        pos_hint: {'center_x':.5, 'bottom':0} # just move on y
    DragBtn:
        text: 'Btn4'
        pos_hint: {'right':1, 'top':.5} # locked
'''

class DragBtn(DragBehavior, Button): pass
class TestApp(App): 
    def build(self): return Builder.load_string(kv)
TestApp().run()

标签: pythonpython-3.xkivy

解决方案


您可以只计算起始位置:

DragBtn:
    text: 'Btn1'
    pos: 0,0
    # pos_hint: {'left':0, 'bottom':0} # free
DragBtn:
    text: 'Btn2'
    pos: 0, root.height - self.height
    # pos_hint: {'left':0, 'top':1} # just move on x
DragBtn:
    text: 'Btn3'
    pos: root.center_x - self.width/2, 0
    # pos_hint: {'center_x':.5, 'bottom':0} # just move on y
DragBtn:
    text: 'Btn4'
    pos: root.width - self.width, root.center_y - self.height/2
    # pos_hint: {'right':1, 'top':.5} # locked

推荐阅读