Python GTK 拖放 - 获取 URL

6 投票
4 回答
5156 浏览
提问于 2025-04-15 13:20

我正在创建一个小应用程序,它需要能够接收网址。如果应用程序的窗口是打开的,我应该能够从浏览器中拖动一个链接,然后放到应用程序里——这样应用程序就会把这个网址保存到数据库中。

我是在用Python和GTk来做这个。但是我对它的拖放功能有点困惑。那么,我该怎么做呢?

这里有一些示例代码,可以用来实现拖放功能(我的应用程序用到了一部分这样的代码)...

import pygtk
pygtk.require('2.0')
import gtk

# function to print out the mime type of the drop item
def drop_cb(wid, context, x, y, time):
    l.set_text('\n'.join([str(t) for t in context.targets]))
    # What should I put here to get the URL of the link?

    context.finish(True, False, time)
    return True

# Create a GTK window and Label, and hook up
# drag n drop signal handlers to the window
w = gtk.Window()
w.set_size_request(200, 150)
w.drag_dest_set(0, [], 0)
w.connect('drag_drop', drop_cb)
w.connect('destroy', lambda w: gtk.main_quit())
l = gtk.Label()
w.add(l)
w.show_all()

# Start the program
gtk.main()

4 个回答

2

下面的代码是从一个旧的PyGTK教程示例移植过来的,我猜这个示例启发了被接受的答案,不过是用pygi写的:

#!/usr/local/env python
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk

def motion_cb(wid, context, x, y, time):
    Gdk.drag_status(context, Gdk.DragAction.COPY, time)
    return True

def drop_cb(wid, context, x, y, time):
    l.set_text('\n'.join([str(t) for t in context.list_targets()]))
    context.finish(True, False, time)
    return True

w = Gtk.Window()
w.set_size_request(200, 150)
w.drag_dest_set(0, [], 0)
w.connect('drag-motion', motion_cb)
w.connect('drag-drop', drop_cb)
w.connect('destroy', lambda w: Gtk.main_quit())
l = Gtk.Label()
w.add(l)
w.show_all()

Gtk.main()
3

为了确保在从文件浏览器拖放一系列文件时,只获取一个文件或目录的数据,你可以使用类似下面的代码:

data.get_text().split(None,1)[0]

然后“got_data_cb”这个方法的代码看起来会是这样的:

def got_data_cb(wid, context, x, y, data, info, time):
    # Got data.
    l.set_text(data.get_text().split(None,1)[0])
    context.finish(True, False, time)

这段代码会把数据按照空格分开,并返回第一个项目。

8

你需要自己去获取数据。下面是一个简单的示例,它会把你拖放的链接显示在标签上:

#!/usr/local/env python

import pygtk
pygtk.require('2.0')
import gtk

def motion_cb(wid, context, x, y, time):
    l.set_text('\n'.join([str(t) for t in context.targets]))
    context.drag_status(gtk.gdk.ACTION_COPY, time)
    # Returning True which means "I accept this data".
    return True

def drop_cb(wid, context, x, y, time):
    # Some data was dropped, get the data
    wid.drag_get_data(context, context.targets[-1], time)
    return True

def got_data_cb(wid, context, x, y, data, info, time):
    # Got data.
    l.set_text(data.get_text())
    context.finish(True, False, time)

w = gtk.Window()
w.set_size_request(200, 150)
w.drag_dest_set(0, [], 0)
w.connect('drag_motion', motion_cb)
w.connect('drag_drop', drop_cb)
w.connect('drag_data_received', got_data_cb)
w.connect('destroy', lambda w: gtk.main_quit())
l = gtk.Label()
w.add(l)
w.show_all()

gtk.main()

撰写回答