【问题标题】:Kivy: How do I add a context menu to buttonKivy:如何向按钮添加上下文菜单
【发布时间】:2018-08-16 22:22:37
【问题描述】:

我在 Kivy 中创建了一个自定义 Button 类,带有一些回调方法,当我右键单击按钮时,我希望能够从几个不同的操作中进行选择:

from kivy.config import Congfig
Config.set('input', 'mouse', 'mouse,multitouch_on_demand')

from kivy.app import App
from kivy.uix import Button


class CustomButton(Button):
   """This is just for demonstration"""

   def __init__(self, name='', **kwargs):
       super(Service, self).__init__(**kwargs)
       self.name = name
       self.on_touch_down = self.mouse_click

   def mouse_click(self, touch):
       if self.collide_point(touch.x, touch.y):
           if touch.button == 'right':
               # Open context menu
               pass

   def callback_1(self):
       # This will be called from one of the context options
       pass

   def callback_2(self):
       # Or this will be called from a different option
       pass

代码仅用于演示目的,以表达我想要实现的目标。这可能吗?

提前致谢。

【问题讨论】:

    标签: python user-interface button kivy contextmenu


    【解决方案1】:

    在您的mouse_click() 方法(您有# Open context menu)中,您可以调用自定义弹出菜单,例如:

    self.popup = PopMenu(touch)
    self.popup.open()
    

    使用创建 ModalView 的 PopMenu 类,类似于:

    class PopMenu(object):
    
        def __init__(self, touch):
            myContent = BoxLayout(orientation='vertical')
            button = Button(text='button1')
            myContent.add_widget(button)
            button = Button(text='button2')
            myContent.add_widget(button)
            button = Button(text='button3')
            myContent.add_widget(button)
            self.popup = ModalView(size_hint=(None, None), height=myContent.height, pos_hint={'x' : touch.spos[0], 'top' : touch.spos[1]})
            self.popup.add_widget(myContent)
    
        def open(self, *args):
            self.popup.open()
    

    您可以将回调添加到 PopMenu 中的按钮。

    【讨论】:

    • 这就是我最终要做的。感谢您的贡献:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2020-08-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多