使用 PyGTK 的右键菜单(上下文菜单)

Right Click Menu (context menu) using PyGTK(使用 PyGTK 的右键菜单(上下文菜单))

本文介绍了使用 PyGTK 的右键菜单(上下文菜单)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我对 Python 还是比较陌生,并且已经学习了几个月,但我想弄清楚的一件事是说你有一个基本的窗口......

So I'm still fairly new to Python, and have been learning for a couple months, but one thing I'm trying to figure out is say you have a basic window...

#!/usr/bin/env python

import sys, os
import pygtk, gtk, gobject

class app:

   def __init__(self):
    window = gtk.Window(gtk.WINDOW_TOPLEVEL)
    window.set_title("TestApp")
    window.set_default_size(320, 240)
    window.connect("destroy", gtk.main_quit)
    window.show_all()

app()
gtk.main()

我想在这个窗口内右键单击,然后弹出一个菜单,如警报、复制、退出,无论我想放下什么.

I wanna right click inside this window, and have a menu pop up like alert, copy, exit, whatever I feel like putting down.

我将如何做到这一点?

推荐答案

在 http://www.pygtk.org/pygtk2tutorial/sec-ManualMenuExample.html

它向您展示了如何创建一个菜单,将它附加到菜单栏,并监听鼠标按钮点击事件并弹出与创建的菜单完全相同的菜单.

It shows you how to create a menu attach it to a menu bar and also listen for a mouse button click event and popup the very same menu that was created.

我认为这就是你所追求的.

I think this is what you are after.

(添加了进一步的解释以显示如何仅响应鼠标右键事件)

(added further explanation to show how to respond to only right mouse button events)

总结.

创建一个小部件来监听鼠标事件.在本例中,它是一个按钮.

Create a widget to listen for mouse events on. In this case it's a button.

button = gtk.Button("A Button")

创建菜单

menu = gtk.Menu()

用菜单项填充它

menu_item = gtk.MenuItem("A menu item")
menu.append(menu_item)
menu_item.show()

使小部件侦听鼠标按下事件,并为其附加菜单.

Make the widget listen for mouse press events, attaching the menu to it.

button.connect_object("event", self.button_press, menu)

然后定义处理这些事件的方法.如链接中的示例所述,传递给此方法的小部件是您想要弹出的菜单,而不是正在侦听这些事件的小部件.

Then define the method which handles these events. As is stated in the example in the link, the widget passed to this method is the menu that you want popping up not the widget that is listening for these events.

def button_press(self, widget, event):
    if event.type == gtk.gdk.BUTTON_PRESS and event.button == 3:
        #make widget popup
        widget.popup(None, None, None, event.button, event.time)
        pass

您将看到 if 语句检查按钮是否被按下,如果是真的,它将检查哪个按钮被按下.event.button 是一个整数值,表示按下了哪个鼠标按钮.所以1是左键,2是中键,3是鼠标右键.通过检查 event.button 是否为 3,您只会响应鼠标右键的鼠标按下事件.

You will see that the if statement checks to see if the button was pressed, if that is true it will then check to see which of the buttons was pressed. The event.button is a integer value, representing which mouse button was pressed. So 1 is the left button, 2 is the middle and 3 is the right mouse button. By checking to see if the event.button is 3, you are only responding to mouse press events for the right mouse button.

这篇关于使用 PyGTK 的右键菜单(上下文菜单)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 PyGTK 的右键菜单(上下文菜单)