如何在Python中创建一个不可编辑但接受拖放的Gtk3条目?

2024-09-29 05:28:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Drag and Drop函数创建了一个Gtk.Entry。此条目能够从拖放接收文本数据。 但是手工修改文本是不允许的,所以我将editable设置为False

现在拖放不再工作。方法“on \u drag \u data \u received”不再调用。 正在搜索解决方案

class DragDropEntry(Gtk.Entry):

    def __init__(self, placeholder_text="drop something here", editable=False):
        Gtk.Entry.__init__(self, placeholder_text=placeholder_text, editable=editable)
        self.drag_dest_set(Gtk.DestDefaults.ALL, [], DRAG_ACTION)
        self.connect("drag-data-received", self.on_drag_data_received)
        self.drag_dest_add_text_targets()

    def on_drag_data_received(self, widget, drag_context, x, y, data, info, time):
        uri = data.get_data().strip('\r\n\x00')
        uri_splitted = uri.split() # we may have more than one file dropped
        for uri in uri_splitted:
            path = self.get_file_path_from_dnd_dropped_uri(uri)
            self.set_text(path)
            return

    def get_file_path_from_dnd_dropped_uri(self, uri):
        path = ""
        if uri.startswith('file:\\\\\\'): # windows
            path = uri[8:] # 8 is len('file:///')
        elif uri.startswith('file://'): # nautilus, rox
            path = uri[7:] # 7 is len('file://')
        elif uri.startswith('file:'): # xffm
            path = uri[5:] # 5 is len('file:')
        path = urllib.url2pathname(path) # escape special chars
        path = path.strip('\r\n\x00') # remove \r\n and NULL
        return path

Tags: pathtextselfgtkdatagetondef