我是第一次嘗試使用 Kivy。我已經使用從外部文件導入了一個函數#:import centerAlign helperFunctions.centerAlign我的函數(centerAlign)如下所示:def centerAlign(elem, parent): pos = [parent.width/2-elem.width/2, parent.height/2-elem.height/2] return pos它的實現看起來像這樣: GridLayout: cols: 2 spacing: 10 size_hint: 0.5, 0.25 pos: centerAlign(self, root)此操作失敗,因為它計算兩個元素(根元素和 GridLayout)的高度和寬度均為 100。但是,我知道這應該有效,因為當我說: GridLayout: cols: 2 spacing: 10 size_hint: 0.5, 0.25 pos: [root.width/2-self.width/2, root.height/2-self.height/2]效果很好!所以我真的不明白這里發生了什么。我對 Python 有點陌生,所以希望這是一個簡單的事情,經驗豐富的老手可以提供一些啟發。提前致謝!
1 回答

四季花海
TA貢獻1811條經驗 獲得超5個贊
pos: [root.width/2-self.width/2, root.height/2-self.height/2]
當 kv 解析這一行時,可以看到pos
當 root.width、root.height、self.width 或 self.height 改變時它需要更新,因為它們都在這里被引用。為了實現這一點,會自動創建綁定。
pos: centerAlign(self, root)
在此行中沒有任何要綁定的屬性,因此當發生任何更改時不會更新。因此,您只能得到基于寬度/高度初始值(100)的結果。
要解決此問題,請在 kv 行中引用您想要綁定的屬性,或者編寫一些其他代碼來創建您想要的綁定。
添加回答
舉報
0/150
提交
取消