简体   繁体   English

python Gtk.Clipboard.get()gtk3返回值不同

[英]python Gtk.Clipboard.get() gtk3 return value differs

I want to convert Gtk.Clipboard.get() return value to utf-8. 我想将Gtk.Clipboard.get()返回值转换为utf-8。

gtk3 gtk3

from gi.repository import Gtk, Gdk

def main():
    clip = Gtk.Clipboard.get (Gdk.SELECTION_PRIMARY)
    text=clip.wait_for_text ()
    print text
    text=text.encode("utf-8")
    print text 

main()

It works only when selected text keeps only ascii characters, but if there are are some national characters (french/german, etc) I get error from text.encode(..) function : UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128) 仅当选定的文本仅保留ascii字符时才有效,但是如果有一些国家字符(法语/德语等),我会从text.encode(..)函数中收到错误消息:UnicodeDecodeError:'ascii'编解码器无法解码字节0xc3在位置1:序数不在范围内(128)

Have You got idea where is the problem and how to make gtk3 version to work? 您知道问题出在哪里以及如何使gtk3版本正常工作吗?

This works correct when I use gtk2's gtk.clipboard_get() function: 当我使用gtk2的gtk.clipboard_get()函数时,此方法正确运行:

import gtk

def main():
    clip = gtk.clipboard_get ('PRIMARY')
    text=clip.wait_for_text ()
    print text
    text=text.encode("utf-8")
    print text 
main()

best regards 最好的祝福

Just a guess here. 这里只是一个猜测。 The clipboard's wait_for_text() method, according to the documentation, is already supposed to give you UTF-8 encoded strings. 根据文档,剪贴板的wait_for_text()方法已经可以为您提供UTF-8编码的字符串。 It might be that the GTK 3 version is mistakenly returning a str instead of a unicode object. 可能是GTK 3版本错误地返回了一个str而不是一个unicode对象。 To test this, try adding 要对此进行测试,请尝试添加

print type(text)

to see what kind of object it is. 看看它是什么样的物体。

You can try utext = text.decode('utf8') to get a unicode object. 您可以尝试utext = text.decode('utf8')获得unicode对象。

wait_for_text() does return str type, but this is not mistake: utf-8 strings are represented by str type. wait_for_text()确实返回str类型,但这不是错误:utf-8字符串由str类型表示。

It also came to my mind that this line will always produce an error: 我还想到,这一行总是会产生错误:

some_Unicode_String_With_Non_Ascii.encode("utf-8").encode("utf-8"),

Thus my gtk3 example behaves correctly. 因此,我的gtk3示例行为正确。 As a conclusion: text.encode("utf-8") operation should be removed. 结论:应该删除text.encode("utf-8")操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM