How can I change the font size in GTK? - python

Is there an easy way to change the font size of text elements in GTK? Right now the best I can do is do set_markup on a label, with something silly like:
lbl.set_markup("<span font_desc='Tahoma 5.4'>%s</span>" % text)
This 1) requires me to set the font , 2) seems like a lot of overhead (having to parse the markup), and 3) would make it annoying to change the font size of buttons and such. Is there a better way?

If you want to change font overall in your app(s), I'd leave this job to gtkrc (then becomes a google question, and "gtkrc font" query brings us to this ubuntu forums link which has the following snippet of the the gtkrc file):
style "font"
{
font_name = "Corbel 8"
}
widget_class "*" style "font"
gtk-font-name = "Corbel 8"
(replace the font with the one you/user need)
Then the user will get consistent experience and will be able to change the settings easily without need for them to poke in the code and without you needing to handle the overhead of maintaining your personal configuration-related code. I understand you can make this setting more specific if you have a more precise definition for the widget_class.
YMMV for different platforms, but AFAIK this file is always present at some location if GTK is being used, and allows to the user to be in charge of presentation details.

In C, you can do:
gtk_widget_modify_font(lbl, pango_font_description_from_string("Tahoma 5.4"));
In PyGTK, I believe it's something like:
pangoFont = pango.FontDescription("Tahoma 5.4")
lbl.modify_font(pangoFont)

Related

auto formatting python code to put parameters on same line

I really hate having spread out code, I am looking at a bunch of long code with parameters and arguments that are taking up way to much space.
def __init__(self,
network,
value_coef,
entropy_coef,
lr=None,
eps=None,
max_grad_norm=None,
conv=False):
Seems the guy who wrote it forced a 50 character line limit, I whole heartedly disagree. I would much rather it looked like this.
def __init__(self, network, value_coef, entropy_coef, lr=None, eps=None, max_grad_norm=None, conv=False):
There is also more nonsense like this which I would like to get rid of.
if self.conv:
grid_obs = rollouts.grid_obs[:-1]\
.view(-1, *rollouts.grid_obs.size()[2:])
dest_obs = rollouts.dest_obs[:-1]\
.view(-1, *rollouts.dest_obs.size()[2:])
obs = (grid_obs, dest_obs)
I am using VS code for the python and am an ex Intellij user and am missing all the built in code formatting code tools. Any one got any tips? I have been looking at autopep8 but it seems they are missing that functionality.
First, that's not 50 chars limit but 79 (as per pep8 conventions) and the way you would like to have it wouldn't be pep8 compliant as it's over 100 columns.
So, for the first snippet you can have it the way you don't like it (which is the correct way) or let your formatter know that you want the line-length to be over 79 columns.
For the second snippet you can remove the escape character \ and let the formatter do its job. I don't think it's 'nonsense' as you call it, but feel free to format it differently.
Autopep8 or Black both work very well and they are not missing any functionality.
Provided you installed one or the other, you have to add the proper key/value pair to your settings.json:
"python.formatting.provider": "autopep8" // (or "black")
If you use autopep8, for example, you can specify the line length you want (150 in your case) by adding this to your settings.json file:
"python.formatting.autopep8Args": [
"--line-length=150"
]
The same goes for black. In that case the value would be:
"python.formatting.blackArgs": [
"--line-length=150"
]
Formatting with that parameter will wrap your code to that amount.
You can format code with alt+shift+f (on a Mac) or right click on the editor and "Format Document".

Python Wand: how to get the text bolded?

How to generate bolded text using python wand library? I cant get it to work.
http://docs.wand-py.org/en/0.4.1/wand/drawing.html - regarding documentation styles that are supported:
'undefined;
'normal'
'italic'
'oblique'
'any'
there is no bold style?
sample usage i wanted to do a footer with a date that I get from contents file:
with Image(width=150, height=25,) as img:
draw.font_family = 'MS Reference Sans Serif'
draw.font_size = 14.0
draw.push()
draw.font_style = 'italics'
metrics = draw.get_font_metrics(img, contents['date'], multiline=False)
draw.text(int((img.width - metrics.text_width)/2), int((metrics.text_height)), contents['date'])
draw.pop()
draw(img)
img.save(filename='./temp/footer.png')
Maybe there is some way to make it bold in some quick way? Would really appreciate any help.
"bold" is not a font_style, it's a font_weight: http://docs.wand-py.org/en/0.4.1/wand/drawing.html#wand.drawing.Drawing.font_weight
And the integer values it takes are the values fonts typically use, where 400 is "normal" and 700 is "bold". (These are also used in CSS. See e.g. https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#Common_weight_name_mapping.)
Although mercator offered a correct answer to the title question, this answer focusing on the nested question:
Maybe there is some way to make it bold in some quick way?
Try using the bold variant typeface directly.
Either specific the bold-font file provided by Microsoft ...
draw.font = 'refsanb.ttf`
... or use the font style with a "Bold" suffix.
draw.font_family = 'MS Reference Sans Serif Bold'

Python Reportlab combine paragraph

I hope you can help me trying to combine a paragraph, my style is called "cursiva" and works perfectly also I have other's but it's the same if I change cursiva to other one. the issue is that If I use this coude o get this.
As you can see guys it shows with a line break and I need it shows togetter.
The problem is that i need to make it like this (one, one) togetter because I need to use two styles, the issue here is that I'm using arial narrrow so if I use italic or bold I need to use each one by separate because the typography does not alow me to use "< i >italic text< /i > ", so I need to use two different styles that actually works fine by separate.
how can I achive this?
cursiva = ParagraphStyle('cursiva')
cursiva.fontSize = 8
cursiva.fontName= "Arialni"
incertidumbre=[]
incertidumbre.extend([Paragraph("one", cursiva), Paragraph("one", cursiva)])
Thank you guys
The question you are asking is actually caused by a workaround for a different problem, namely that you don't know how to register font families in Reportlab. Because that is what is needed to make <i> and <b> work.
So you probably already managed to add a custom font, so the first part should look familiar, the final line is probably the missing link. It is registering the combination of these fonts a family.
from reportlab.pdfbase.pdfmetrics import registerFontFamily
pdfmetrics.registerFont(TTFont('Arialn', 'Arialn.ttf'))
pdfmetrics.registerFont(TTFont('Arialnb', 'Arialnb.ttf'))
pdfmetrics.registerFont(TTFont('Arialni', 'Arialni.ttf'))
pdfmetrics.registerFont(TTFont('Arialnbi', 'Arialnbi.ttf'))
registerFontFamily('Arialn',normal='Arialn',bold='Arialnb',italic='Arialni',boldItalic='Arialnbi')

use the system monospace font in gtk textview

I would like to have a GtkTextView in my (Python) program which shows text with the system monospace font. I found many ways which use an expicit font family name and size. However, I would like to use the system specified monospace font (e.g. from the ubuntu font preferences panel).
My program should be able to run on Windows as well as Linux without modifications, chosing automatically the right font.
to clarify, this is not what I want:
fontdesc = pango.FontDescription("Courier 18")
textview.modify_font(fontdesc)
You can just use "monospace 18" as your font and it will use the system monospaced font.
[available since 3.16]
set_monospace()
GTK3+ Doc
https://developer.gnome.org/gtk3/stable/GtkTextView.html#gtk-text-view-set-monospace
gtk_text_view_set_monospace ()
void
gtk_text_view_set_monospace (GtkTextView *text_view, gboolean monospace);
Sets the “monospace” property, which indicates that the text view should use monospace fonts.
Parameters
text_view a GtkTextView
monospace TRUE to request monospace styling

Entry with suggestions

I'm building a small PyGTK application and I have an text input field (currently a ComboBoxEntry) which is populated with a few values that the user should be able to choose from.
I think what I want to do is to filter out the matching fields and only show those ones so the user using the keyboard arrows can choose one of the matching ones.
To give some background the predefined values are a bunch of urls and the user should be able to choose from theese or fill in a new one.
Example:
the predefined urls:
http://www.google.com
http://www.google.com/android
http://www.greatstuff.com
http://www.facebook.com
When a user types 'http://www.g'
The three URLs starting with that string is to be shown (in some way) and when typeing 'http://www.goog' the two starting with that is to be shown
Any Ideas?
An Entry with an EntryCompletion seems more appropriate than a ComboBoxEntry. As always, the tutorial is a good start.
It's very easy to set up when the predefined URLs list is small and fixed.
You just need to populate a ListStore:
# simplified example from the tutorial
import gtk
urls = [
'http://www.google.com',
'http://www.google.com/android',
'http://www.greatstuff.com',
'http://www.facebook.com',
]
liststore = gtk.ListStore(str)
for s in urls:
liststore.append([s])
completion = gtk.EntryCompletion()
completion.set_model(liststore)
completion.set_text_column(0)
entry = gtk.Entry()
entry.set_completion(completion)
# boilerplate
window = gtk.Window()
window.add(entry)
window.connect('destroy', lambda w: gtk.main_quit())
window.show_all()
gtk.main()
Users are not likely to bother typing "http://" or even "www.", so you probably want to match any part of the URL (e.g. just "og" works!):
def match_anywhere(completion, entrystr, iter, data):
modelstr = completion.get_model()[iter][0]
return entrystr in modelstr
completion.set_match_func(match_anywhere, None)
This will test every value in the ListStore for a match, so it's not scalable to huge lists (I mean huge; a 1000 works fine).
Be sure to play with the various options of EntryCompletion, to configure the most pleasant behavior.
You may want to look at how Deskbar Applet's Cuemiac does it.
Well, you obviously want to deal with prefixes so you'll probably want to use some sort of trie. Of course, there are issues to deal with. For instance, after a person has typed in a few letters ( or maybe even just one) you will want to either traverse the rest of the branches of the trie to find suggestions, or have suggestions stored in each node. A lot of these sorts of decisions depend on how many possible suggestions you plan on having.

Categories