我有两个按钮小部件。 Button1旋转而Button2没有旋转。我正在尝试测试两个按钮小部件是否会发生碰撞。
这是我的代码:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.graphics import *
from kivy.logger import Logger
class RotateMe(Button):
def __init__(self, **kwargs):
Button.__init__(self, **kwargs)
with self.canvas.before:
PushMatrix()
self.rot = Rotate(angle= 45, origin= self.center)
with self.canvas.after:
PopMatrix()
class Main(Widget):
def __init__(self):
super(Main, self).__init__()
self.size = Window.size
self.rotatethis = RotateMe(text= "Button1", center= self.center)
self.add_widget(self.rotatethis)
self.somebutton = Button()
self.somebutton.text = "Button2"
self.somebutton.right = self.center_x - 60
self.somebutton.y = self.center_y
self.add_widget(self.somebutton)
if self.somebutton.collide_widget(self.rotatethis):
Logger.info("The buttons collided! Much happiness")
else:
Logger.info("The buttons didn't collide. Such sadness.")
class TestApp(App):
def build(self):
return Main()
TestApp().run()
这就是我运行代码时的样子。
我可以从输出(图像)中清楚地看到两个按钮相撞但是当我检查日志时,它表示Button Widgets没有碰撞。似乎Button1的小部件位置没有改变/旋转。
我尝试更改Button2的位置,以查看它与Button1发生碰撞的位置。我发现Button1的Widget位置没有改变。
像这样:
Button1背面的白色方块是Button1小部件的实际位置。
有没有办法旋转Button1小部件的位置?
更新:我尝试按here.
中的建议使用ScatterLayout这是我更新的代码:
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.graphics import *
from kivy.logger import Logger
from kivy.uix.scatterlayout import ScatterLayout
from kivy.uix.floatlayout import FloatLayout
class RotateMe(ScatterLayout):
def __init__(self):
ScatterLayout.__init__(self)
self.size_hint = (None, None)
self.size = (100, 100)
self.rotation = 45
self.do_rotation = False
self.add_widget(Button(text= "Button1"))
class Main(FloatLayout):
def __init__(self):
super(Main, self).__init__()
self.size = Window.size
self.rotatethis = RotateMe()
self.rotatethis.center = self.center
self.add_widget(self.rotatethis)
self.button2 = Button(text= "Button2")
self.button2.size_hint = (None, None)
self.button2.size = (100, 100)
self.button2.right = self.center_x - 60
self.button2.y = self.center_y
self.add_widget(self.button2)
if self.button2.collide_widget(self.rotatethis):
Logger.info("The buttons collided! Much happiness")
else:
Logger.info("The buttons didn't collide. Such sadness.")
class TestApp(App):
def build(self):
return Main()
TestApp().run()
现在按钮发生了碰撞但是当我尝试改变Button2的位置时,就像这样:
self.button2.y = self.center_y + 45
输出如下:
查看输出(图像),两个按钮的小部件似乎没有相互碰撞,但是当我查看日志时,它说它们相互碰撞。
事实证明,Button1的小部件大小是这个(彩色的蓝绿色背景):