簡體   English   中英

如何在純 Python 代碼(不是 kvlang)中使用 Kivy Rotate?

[英]How to use Kivy Rotate in pure Python code (not kvlang)?

我想用純 python 代碼而不是 kvlang 旋轉按鈕。

使用 kvlang,我們可以旋轉按鈕,如示例所示。 按鈕圍繞其中心旋轉 45 度。 下面是原代碼:

from kivy.app import App
from kivy.lang import Builder
kv = '''
FloatLayout:
    Button:
        text: 'hello world'
        size_hint: None, None
        pos_hint: {'center_x': .5, 'center_y': .5}
        canvas.before:
            PushMatrix
            Rotate:
                angle: 45
                origin: self.center
        canvas.after:
            PopMatrix
'''
class RotationApp(App):
    def build(self):
        return Builder.load_string(kv)
RotationApp().run()

但是,當我嘗試重寫與純Python代碼下面這個例子中,按鈕圍繞其旋轉的其他地方,如在這里

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.graphics import PushMatrix, PopMatrix, Rotate
class MyButton(Button):
    def __init__(self):
        super().__init__()
        self.text = 'hello world'
        self.size_hint = (None, None)
        self.pos_hint = {'center_x': .5, 'center_y': .5}
        with self.canvas.before:
            PushMatrix()
            Rotate(origin=self.center, angle=45)
        with self.canvas.after:
            PopMatrix()
class RotationApp(App):
    def __init__(self):
        super().__init__()
        self.layout = FloatLayout()
        self.button = MyButton()
        self.layout.add_widget(self.button)
    def build(self):
        return self.layout
RotationApp().run()

上面的兩段代碼沒有產生相同的結果。 我們做錯了什么嗎?

更新:

按照@inclement 的建議解決了這個難題,解決方案如下:

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.button import Button
from kivy.graphics import PushMatrix, PopMatrix, Rotate
class MyButton(Button):
    def __init__(self):
        super().__init__()
        self.text = 'hello world'
        self.size_hint = (None, None)
        self.pos_hint = {'center_x': .5, 'center_y': .5}
        with self.canvas.before:
            PushMatrix()
            
            # Rotate(origin=self.center, angle=45)  # previous approach
            self.rotation = Rotate(origin=self.center, angle=45)
            self.bind(center=lambda _, value: setattr(self.rotation, "origin", value))
            
        with self.canvas.after:
            PopMatrix()
class RotationApp(App):
    def __init__(self):
        super().__init__()
        self.layout = FloatLayout()
        self.button = MyButton()
        self.layout.add_widget(self.button)
    def build(self):
        return self.layout
RotationApp().run()

在您的 Python 代碼中, self.center__init__期間只計算一次。 在 kv 代碼中,每次更改時都會自動創建一個綁定以重置Rotate指令的origin屬性。

您需要將缺少的功能放入 Python 代碼中,例如self.rotation = Rotate(...)self.bind(center=lambda instance, value: setattr(self.rotation, "origin", value)) (盡管我確定您可以想出更好的方法來設置它,但這只是內聯示例)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM