如何跟踪鼠标事件并在Kivy中为网格着色

时间:2019-06-14 14:41:01

标签: python kivy

如何绘制网格并跟踪鼠标,在其中如何使用Kivy更改鼠标悬停的框的颜色?

目前,我有下面的代码,它尚未完成,但是有一些问题。使用当前的方式,它只跟踪鼠标的位置,而没有绘制任何网格。如果我只返回布局,则将绘制网格,但未跟踪鼠标。

import kivy
kivy.require('1.10.0')
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

class TouchInput(Widget):
    def on_touch_down(self, touch):
        print(touch)
    def on_touch_move(self, touch):
        print(touch) ## WILL ADD CHANGING COLORS HERE LATER
    def on_touch_up(self, touch):
        print("RELEASED!",touch)

class MyApp(App):
    def build(self):
        T = TouchInput()

        layout = GridLayout(cols=2)
        layout.add_widget(Button(text='Hello 1'))
        layout.add_widget(Button(text='World 1'))
        layout.add_widget(Button(text='Hello 2'))
        layout.add_widget(Button(text='World 2'))

        return T

if __name__ == "__main__":
    MyApp().run()

1 个答案:

答案 0 :(得分:1)

您可以将TouchInput方法和GridLayout组合为:

import kivy
kivy.require('1.10.0')
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button

class MyGrid(GridLayout):
    def on_touch_down(self, touch):
        print(touch)
    def on_touch_move(self, touch):
        print(touch) ## WILL ADD CHANGING COLORS HERE LATER
    def on_touch_up(self, touch):
        print("RELEASED!",touch)

class MyApp(App):
    def build(self):

        layout = MyGrid(cols=2)
        layout.add_widget(Button(text='Hello 1'))
        layout.add_widget(Button(text='World 1'))
        layout.add_widget(Button(text='Hello 2'))
        layout.add_widget(Button(text='World 2'))

        return layout

if __name__ == "__main__":
    MyApp().run()