[Tutor] Fwd: Re: Dynamic variables changed via Tkinter button

Alan Gauld alan.gauld at yahoo.co.uk
Sun Apr 19 12:01:21 EDT 2020


On 19/04/2020 16:00, Jon Davies wrote:
> Hi Alan,
> 
> Have tried amending to the below:
> def update(self):
>         self.fuelcount += 0.1
>         total_price = self.fuelcount * self.controller.currency * PETROL_PRICE
>         self.litre_lbl['text'] = _("Litres = %f") % self.fuelcount
>         self.price_lbl['text'] = f"{symbol}" + _("Price = %f") + f"{total_price}"
>         self.update_idletasks()
>         if self.state == 'working':
>             self.lever_btn.after(100, self.update)
> But providing me this error:
> NameError: name 'symbol' is not defined

Sorry, the symbol needs to be whatever the currency symbol is.
(Presu,ably fetched from the controller.
Maybe create a controller method that returns both symbol
and exchange rate as a tuple? getCurrencyDetails() perhaps?
Also you don't want the %f inside the _(). - see below...
In fact you don't need %f at all, the new format string
uses the simpler substitution mechanism so the

f"{total_price}"

is equivalent to

"%f" % total_price

using the older printf(%) formatting

Regarding the use of _() in gettext.
This is not magic - although it can seem like it!
When you call the GNU translation init mechanism
it builds a translation dictionary that has your
literal strings as keys and the translation strings
from your translation file as values. It then defines
the _() function as just a function like any other.
Python calls it with a string argument.
Inside _() it looks like this, in pseudo code:

def _(theString):
   return translationTable[thestring]

Now that requires that the string you pass in
to _() matches exactly the string in the table,
which in turn has been previously extracted from
your code by gettext. So, if you have a string like:

_("%s Price = ")

getext will extract that string - including
the %s part - and expect a literal translation.
So in your translation file you would need
to put in something like

"£ Price ="  for uk English and
"$ Price ="  for US English etc...

Which limits you to having one currency per
language file which is not good. It all gets very messy.
That's why it's better not to have the currency
symbol inside the translated string.
Something like

symbol + _(" Price = ") + f"{value}"

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list