【问题标题】:How to make an image "float" over the buttons?如何使图像“浮动”在按钮上?
【发布时间】:2019-02-22 01:24:53
【问题描述】:

我开始学习 Kivy。 下面的代码生成一个 10x10 的按钮网格:

from kivy.uix.gridlayout import GridLayout
from kivy.app import App
from kivy.uix.button import Button


class MyApp(App):
    def build(self):
        layout = GridLayout(cols=10)
        for i in range (1, 101):
            layout.add_widget(Button(text=str(i)))
        return layout

MyApp().run()

现在,我想将 png 图像添加到一个独立的图层,该图层独立地随机“徘徊”在这些按钮上。

然后用户应该点击图片所在的按钮,就像在游戏中一样。

也就是说,图像不应该是可点击的,并且只会在按钮上直观地显示,同时,按钮应该完美地响应,就好像它们上面没有图像一样。 如何做到这一点?

【问题讨论】:

    标签: python-3.x image animation kivy layer


    【解决方案1】:

    您可以使用RectangleGridLayoutCanvas 中绘制图像。并且可以使用Clock_schedule_interval() 更新位置。像这样:

    from kivy.clock import Clock
    from kivy.graphics.context_instructions import Color
    from kivy.graphics.vertex_instructions import Rectangle
    from kivy.uix.gridlayout import GridLayout
    from kivy.app import App
    from kivy.uix.button import Button
    
    
    class MyApp(App):
        def build(self):
            layout = GridLayout(cols=10)
            with layout.canvas.after:
                Color(1,1,1,0.5)  # if you want to see through the image
                self.bg = Rectangle(source='KQxab.png') # source is the image
            for i in range (1, 101):
                layout.add_widget(Button(text=str(i)))
            Clock.schedule_interval(self.update_bg, 1.0/24.0)  # schedule the image movement
            return layout
    
        def update_bg(self, dt):
            self.bg.pos = (self.bg.pos[0] + 1, self.bg.pos[1] + 1)
    
    
    MyApp().run()
    

    此代码只是沿直线移动图像,但您可以改进它。

    【讨论】:

    • 完美!非常感谢。
    猜你喜欢
    • 2016-08-05
    • 2016-01-17
    • 2019-11-18
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-07
    相关资源
    最近更新 更多