我无法理解为什么Kivy中的函数第二次不工作

0 投票
0 回答
18 浏览
提问于 2025-04-11 23:57

你好,我写了一个程序,创建了6个我称之为Cell的自定义小部件。我希望当其中一个小部件和另一个重叠时,它们能够交换位置。为此,我写了一个叫swap_locations的函数,最开始它工作得很好,但当我再次尝试交换我最初选择的Cell时,它确实占据了目标Cell的位置,但目标Cell却没有改变位置。我觉得这里有些可疑的代码部分如下:

class Cell (FloatLayout, DragBehavior):

    def __init__(self,**kwargs):
        super(Cell, self).__init__(**kwargs)
        self.previous_pos = [0,0]
                
    def swap_locations(self, target):
        target_pos = target.pos
        self.pos = target_pos
        target.pos = self.previous_pos
        self.previous_pos = self.pos
        target.previous_pos = target_pos

class BaseLayout (GridLayout):
clock = StringProperty()
day = StringProperty()
date = StringProperty()
temp = StringProperty()
icon = StringProperty()
selected_cell = Cell
target = Cell

    def __init__(self, **kwargs):
        super(BaseLayout, self).__init__(**kwargs),
        Clock.schedule_once(self.calculate_cell_positions)
    
    def calculate_cell_positions(self, dt):
        cell_count = len(self.children)
        if cell_count == 0:
            return 
    
        cols = self.cols
        rows = self.rows
        cell_width = self.width / cols
        cell_height = self.height / rows
    
        for i, cell in enumerate(self.children):
            if i % 2 == 0:
                factor = 1
            else:
                factor = 0
            row = i // cols
            cell.previous_pos = [factor * cell_width, row * cell_height ]           
            cell.pos = cell.previous_pos
    
    def on_touch_down(self, touch):
        x, y = touch.pos    
        for child in self.children:
            if child.collide_point(x,y):
                target = child
                self.selected_cell = target
                return True
        return True
    
    def on_touch_move(self, touch):
        if self.selected_cell:
            x, y = touch.pos
            self.selected_cell.pos = (x - self.selected_cell.width / 2, y - self.selected_cell.height / 2)
            return True
        return True
    
    def on_touch_up(self, touch): 
        if self.selected_cell:
            for child in self.children: 
                
                if child.collide_point(*touch.pos) and self.selected_cell != child:
                    self.selected_cell.swap_locations(child)
                elif child.collide_point(*touch.pos) == None:
                    self.selected_cell.pos = self.selected_cell.previous_pos                                                          
            else:
                self.selected_cell.pos = self.selected_cell.previous_pos                             
        return True 

我写了calculate_cell_positions这个方法,是为了手动计算小部件的位置,因为我的Cells没有初始位置。这可能是个笨主意,如果你有更好的解决方案,请随时告诉我。谢谢!

为了更深入地分析和建模这个问题,我附上了一些我程序的照片1 2 3

0 个回答

暂无回答

撰写回答