使用 PyGTK 的右键菜单(上下文菜单)
所以我对 Python 还很陌生,并且已经学习了几个月了,但我试图弄清楚的一件事是说你有一个基本窗口......
#!/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()
我想在这个窗口内右键单击,然后有一个弹出菜单,如警报、复制、退出,无论我想放下什么。
我将如何实现这一目标?
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.
How would I accomplish that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 http://www.pygtk.org/ 中找到了一个执行此操作的示例pygtk2tutorial/sec-ManualMenuExample.html
它向您展示了如何创建一个菜单,将其附加到菜单栏,并侦听鼠标按钮单击事件并弹出与创建的菜单完全相同的菜单。
我想这就是你所追求的。
编辑:(添加了进一步的解释以显示如何仅响应鼠标右键事件)
总结一下。
创建一个小部件来监听鼠标事件。在本例中它是一个按钮。
创建一个菜单
用菜单项填充它
让小部件侦听鼠标按下事件,并将菜单附加到它。
然后定义处理这些事件的方法。正如链接中的示例所述,传递给此方法的小部件是您想要弹出的菜单,而不是正在侦听这些事件的小部件。
您将看到 if 语句检查是否按下了按钮,如果是的话,它将检查按下了哪个按钮。 event.button 是一个整数值,表示按下了哪个鼠标按钮。所以1是左键,2是中键,3是鼠标右键。通过检查 event.button 是否为 3,您仅响应鼠标右键的鼠标按下事件。
There is a example for doing this very thing found at 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.
EDIT: (added further explanation to show how to respond to only right mouse button events)
To summarise.
Create a widget to listen for mouse events on. In this case it's a button.
Create a menu
Fill it with menu items
Make the widget listen for mouse press events, attaching the menu to it.
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.
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.