【问题标题】:PyGObject: Single button, one action for left click, another action for right click?PyGObject:单个按钮,左键单击的一个动作,右键单击的另一个动作?
【发布时间】:2021-05-28 18:06:07
【问题描述】:

我有一个 PyGObject 应用程序(Python、GTK+),它在左键单击时执行一个操作。

现在,该按钮在右键单击时什么也不做。

我想让按钮在右键单击时执行不同的操作。

有没有办法在 PyGObject 中做到这一点?

现在,我拥有的是:


    def setup_gui_objects(self):                                                                                                     
        """Set up GUI objects."""                                                                                                    
        # pylint: disable=cell-var-from-loop                                                                                         
        self.buttons = {}                                                                                                            
        for button_type in ['Run']:                                                                                                  
            # prints byte strings of hostnames and command names:                                                                    
            # print(self.dict_[b'name'])                                                                                             
            toggle_button = Gtk.ToggleButton(label=to_ascii(self.dict_[b'name']))                                                    
            self.buttons[button_type] = MyButton(toggle_button, self.selected)                                                       
            self.buttons[button_type].set_name(self.color)                                                                           
            self.buttons[button_type].connect('toggled', lambda widget: self.toggle_selected(button_type, widget))                   

谢谢。

【问题讨论】:

    标签: python gtk pygobject


    【解决方案1】:

    您可以使用button_press_event 信号和event.button 来检查是否按下了左 (1) 或右 (3) 按钮。

    import gi
    
    gi.require_version("Gtk", "3.0")
    from gi.repository import Gtk
    
    
    class MyWindow(Gtk.Window):
        def __init__(self):
            Gtk.Window.__init__(self)
    
            button = Gtk.Button()
            button.connect("button_press_event", self.on_button_clicked)
            self.add(button)
    
        def on_button_clicked(self, widget, event):
            if event.button == 1:
                print("Left click")
            elif event.button == 3:
                print("Right click")
    
    
    win = MyWindow()
    win.connect("destroy", Gtk.main_quit)
    win.show_all()
    Gtk.main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 1970-01-01
      相关资源
      最近更新 更多