narnie
narnie

Reputation: 1772

Python with Gtk3 not setting unicode properly

I have some simple code that isn't working as expected. First, the docs say that Gtk.Clipboard.get(Gdk.SELECTION_PRIMARY).set_text() should be able to accept only one argument with the length argument option, but it doesn't work (see below). Finally, pasting a unicode ° symbol breaks setting the text when trying to retrieve it from the clipboard (and won't paste into other programs). It gives this warning:

Gdk-WARNING **: Error converting selection from UTF8_STRING

>>> from gi.repository.Gtk import Clipboard
>>> from gi.repository.Gdk import SELECTION_PRIMARY
>>> d='\u00B0'
>>> print(d)
°
>>> cb=Clipboard
Clipboard
>>> cb=Clipboard.get(SELECTION_PRIMARY)
>>> cb.set_text(d) #this should work
Traceback (most recent call last):
  File "<ipython-input-6-b563adc3e800>", line 1, in <module>
    cb.set_text(d)
  File "/usr/lib/python3/dist-packages/gi/types.py", line 43, in function
    return info.invoke(*args, **kwargs)
TypeError: set_text() takes exactly 3 arguments (2 given)

>>> cb.set_text(d, len(d))
>>> cb.wait_for_text()

(.:13153): Gdk-WARNING **: Error converting selection from UTF8_STRING
'\\Uffffffff\\Uffffffff'

Upvotes: 0

Views: 490

Answers (3)

D. Mueka
D. Mueka

Reputation: 26

Since GTK version 3.16 there is a easier way of getting the clipboard. You can get it with the get_default() method:

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GLib, Gio

display = Gdk.Display.get_default()
clipboard = Gtk.Clipboard.get_default(display)
clipboard.set_text(string, -1)

also for me it worked without

clipboard.store()

Reference: https://lazka.github.io/pgi-docs/Gtk-3.0/classes/Clipboard.html#Gtk.Clipboard.get_default

Upvotes: 1

Jan Baarda
Jan Baarda

Reputation: 1

In Python 3.4. this is only needed for GtkEntryBuffers. In case of GtkTextBuffer set_text works without the second parameter.

example1 works as usual:

settinginfo = 'serveradres = ' + server + '\n poortnummer = ' + poort
GtkTextBuffer2.set_text(settinginfo)

example2 needs extra parameter len:

ErrorTextDate = 'choose earlier date'
GtkEntryBuffer1.set_text(ErrorTextDate, -1)

Upvotes: 0

jonalmeida
jonalmeida

Reputation: 1236

From the documentation for Gtk.Clipboard

It looks like the method set_text needs a second argument. The first is the text, the second is the length of the text. Or if you don't want to provide the length, you can use -1 to let it calculate the length itself.

gtk.Clipboard.set_text

def set_text(text, len=-1) 

text : a string.

len : the length of text, in bytes, or -1, to calculate the length.

I've tested it on Python 3 and it works with cb.set_text(d, -1).

Upvotes: 1

Related Questions