使用PyGTK右键单击菜单(上下文菜单) [英] Right Click Menu (context menu) using PyGTK

查看:266
本文介绍了使用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.

我该怎么做?

推荐答案

它向您展示如何创建菜单,并将其附加到菜单栏,还监听鼠标单击事件并弹出与创建的菜单相同的菜单.

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.

我想这就是你的追求.

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

(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语句检查是否已按下按钮,如果为true,则将检查是否已按下了哪个按钮. 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右键单击菜单(上下文菜单)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆