首页 > 解决方案 > 如何在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()

标签: pythonkivy

解决方案


您可以将您的TouchInput方法和GridLayoutas 结合起来:

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()

推荐阅读