[英]Kivy: screen defined in kvlang, how to add to screenmanager in python?
[英]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.