How do I change a Gtk3 Entry text color in Python3?

筅森魡賤 提交于 2019-12-22 08:35:49

问题


I have a list of Gtk.Entry() in my application, and I would like to change the color of the text of some of them.

I tried the following :

#!/usr/bin/python3
# Filename: mywindow.py

from gi.repository import Gtk
from gi.repository import Gdk

class MyWindow(Gtk.Window):
    def __init__(self):
        Gtk.Window.__init__(self, title="My window")

        self.mainGrid = Gtk.Grid()
        self.add(self.mainGrid)

        self.myOkEntry = Gtk.Entry()
        self.myOkEntry.set_text("This is OK (green)")
        self.myOkEntry.override_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0.0, 1.0, 0.0, 0.0))

        self.mainGrid.add(self.myOkEntry)

mainWin = MyWindow()
mainWin.connect("delete-event", Gtk.main_quit)
mainWin.show_all()

Gtk.main()

But then the text was invisible. I tried different values for Gdk.RGBA from 0.0 to 1.0, and from 0 to 65000, it was the same. Another test :

print(Gdk.color_parse("green"))

prints :

<Gdk.Color(red=0, green=65535, blue=0)>

So I tried :

print(Gdk.RGBA(Gdk.color_parse("green")))

But :

File "/usr/lib/python3/dist-packages/gi/overrides/Gdk.py", line 55, in __init__
    self.red = red
TypeError: argument 2: Must be number, not Color

I'm a bit confused. The documentations I use are mainly:
https://python-gtk-3-tutorial.readthedocs.org/en/latest/
https://developer.gnome.org/gtk3/stable/

I found some documentation about CSS styling, can I use it like :

GtkEntry {
    color: #000000
}
GtkEntry#ok {
    color: #00cc00
}
GtkEntry#error {
    color: #cc0000
}

Like in HTML for instance ? This documentation was linked in a previous question about Python3/Gtk3 Entry color

Well, my question is : how can I change the text color of one Gtk.Entry() without modifying the color of the others ?


回答1:


Set the alpha channel to 1.0:

self.myOkEntry.override_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0.0, 1.0, 0.0, 1.0))



回答2:


You can use gtk.Widget.modify_fg (Widget being one of the base classes for gtk.Entry) with your color_parse logic like so:

self.myOkEntry.modify_fg(Gtk.StateFlags.NORMAL, Gdk.color_parse("green"))


来源:https://stackoverflow.com/questions/15245886/how-do-i-change-a-gtk3-entry-text-color-in-python3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!