On 23/08/18 06:10, Matthew Polack wrote:

> I'm also trying to solve the rounding issue...but can't work out the syntax
> using the example provided...have tried this but I get an error...
> 

> def viewPercent():
>      percentCalc = score/total*100
>      percentViewLab["text %.2f"] % percentCalc

OK, the problem here is mixing up your data with TKinter's
(inherited from Tcl/Tk) mechanism for accessing widget
attributes.

percentViewLab["text %.2f"]

This tells Tkinter to fetch an attribute of your widget
called "text %.2f". Of course there is no such attribute,
it is called just "text".

percentViewLab["text %.2f"] % percentCalc

This tries to insert the percentCalc value into the
string returned by the widget.

Again that's not what you want. You want to insert
the data into a string which will then be assigned
to the widget's text attribute.

val = "%.2f" % percentCalc  # eg. -> val = "0.76"

Now insert val into your widget

percentViewLab["text"] = val

or equivalently:

percentViewLab.config("text", val)

You can of course combine all of that with

percentViewLab["text"] = ".2f" % percentCalc

Personally I tend to separate the creation of the
string from the widget assignment because it makes
it easier to debug by printing the string to the
console.

One final note. When using % to inject data into
a format string you MUST put the percent immediately
after the format string. No commas or parentheses
allowed.

The % formatting style is preferred by old school
programmers (like me) who came from the world of C and
its relatives because C uses a very similar style in
its printf() family of functions. However, new programmers
may find the format() method of a string more obvious.
(I'm thinking about your students here)

Using format your case would look like:

val = "{:.2f}".format(percentCalc)

And the previous example would be:

fail_str = """
Sorry, you got it wrong,
the correct answer was {:d}
Your current score is: {:f}""".format(answer,score)

It is quite similar except the placemarkers are {}
and you call the format() method. The formatting
characters inside the {} are different too - you
need to read the docs... There are zillions of examples.
You might find it more logical.

-- 
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


_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to