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

编程入门 行业动态 更新时间:2024-10-27 02:23:46
本文介绍了使用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.

我该怎么做?

推荐答案

在 www.pygtk/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.

我想这就是你的追求.

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

(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右键单击菜单(上下文菜单)

本文发布于:2023-08-06 05:10:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1310265.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:菜单   右键   上下文   单击   PyGTK

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!