Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
Thanks Alan and Peter for all your help with this. I got it all to work..thank you.. like learning a musical instrument...probably just need some time consolidating the current skill set...has been a lot to take in... but getting there steadily...and bit by bit it is starting to make sense.. I'll probably stick with the traditional %. method too for a while because that is now what I understand. thanks...will keep trying things..and then also reading through the various docs provided...+ your emails. Thank you. Matthew Polack | Teacher [image: Emailbanner3.png] Trinity Drive | PO Box 822 Horsham Victoria 3402 p. 03 5382 2529 m. 0402456854 e. matthew.pol...@htlc.vic.edu.au w. www.htlc.vic.edu.au On Thu, Aug 23, 2018 at 10:34 PM, Alan Gauld via Tutor wrote: > 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 > -- **Disclaimer: *Whilst every attempt has been made to ensure that material contained in this email is free from computer viruses or other defects, the attached files are provided, and may only be used, on the basis that the user assumes all responsibility for use of the material transmitted. This email is intended only for the use of the individual or entity named above and may contain information that is confidential and privileged. If you are not the intended recipient, please note that any dissemination, distribution or copying of this email is strictly prohibited. If you have received this email in error, please notify us immediately by return email or telephone +61 3 5382 2529** and destroy the original message.* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
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
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
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... > > _tkinter.TclError: unknown option "-text %.2f" > > .I'm sure it is a simple syntax issue...but I don't know what it is. > > def viewPercent(): > percentCalc = score/total*100 > percentViewLab["text %.2f"] % percentCalc I'm sure you can resolve that one yourself. You have obj[key] = float_value Now you want to format the float value as a string showing a decimal number. So all you need to change is the righthand side. If it helps write it in two lines: some_string = ... expression involving float_value ... obj[key] = some_string ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
Matthew Polack wrote: > I'm working my way through some of the tips you provided and tried to use > the code givenbut am getting an error at Line 75 in my code re: not > enough arguments for format string > > _ > return self.func(*args) > File "Timespicture.py", line 75, in checkanswer > Your current score is: %f""" % answer,score > TypeError: not enough arguments for format string > fail_str = """ > Sorry, you got it wrong, > the correct answer was %d > Your current score is: %f""" % answer,score Python reads some_str % arg1, arg2 as (some_str % arg1), arg2 To make the above work you have to use parens: fail_str = """ Sorry, you got it wrong, the correct answer was %d Your current score is: %f""" % (answer, score) Another option is to use f-strings to sidestep the issue: fail_str = f""" Sorry, you got it wrong, the correct answer was {answer} Your current score is: {score}""" ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
On 23/08/18 05:47, Matthew Polack wrote: > Hi Alan, > > I'm working my way through some of the tips you provided and tried to use > the code givenbut am getting an error at Line 75 in my code re: not > enough arguments for format string > > _ > return self.func(*args) > File "Timespicture.py", line 75, in checkanswer > Your current score is: %f""" % answer,score > TypeError: not enough arguments for format string Lets go back to basics with Python assignment. In your example you have a format string as: fail_str = """ Sorry, you got it wrong, the correct answer was %d Your current score is: %f""" And you try to insert 2 values, answer and score. Unfortunately Python sees it like this: fail_string = someData, moreData Where someData looks like fmtString % answer and moreData looks like score. The solution is to use parentheses to create an explicit tuple to group both of your data values together: fail_str = """ Sorry, you got it wrong, the correct answer was %d Your current score is: %f""" % (answer,score) -- 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
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
Hi Alan, 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... _tkinter.TclError: unknown option "-text %.2f" .I'm sure it is a simple syntax issue...but I don't know what it is. def viewPercent(): percentCalc = score/total*100 percentViewLab["text %.2f"] % percentCalc ''' # This was my working version pre the version suggest above. percentCalc = score/total*100 rounded = round(percentCalc, 2) percentViewLab["text"] = rounded ''' ''' Instructions given: >>> s = "Here is a string with a rounded float: %.2f" % 42.3456789 >>> s 'Here is a string with a rounded float: 42.35' ''' Thanks for any clues. - Matt Matthew Polack | Teacher [image: Emailbanner3.png] Trinity Drive | PO Box 822 Horsham Victoria 3402 p. 03 5382 2529 m. 0402456854 e. matthew.pol...@htlc.vic.edu.au w. www.htlc.vic.edu.au On Fri, Aug 17, 2018 at 8:18 PM, Alan Gauld via Tutor wrote: > On 17/08/18 03:19, Matthew Polack wrote: > > > def viewPercent(): > > percentCalc = score/total*100 > > rounded = round(percentCalc, 2) > > percentViewLab["text"] = rounded > > Since you only want the rounded value for display > this is usually achieved using string formatting: > > >>> s = "Here is a string with a rounded float: %.2f" % 42.3456789 > >>> s > 'Here is a string with a rounded float: 42.35' > > That doesn't change the value of the variable but changes how > it is displayed. There are lots of other options in format > strings to control justification, padding etc. You should > definitely explore their capabilities. Just because you > are using a GUI rather than a console doesn't mean the > string methods are any less useful. > > > from tkinter import * > > import random > > > > # GLOBAL VARIABLES > > # Created with a starting value. > > answer = 0 > > score = 0 > > wrong = 0 > > mistakes = 0 > > total = 0 > > > > def makeproblem(): > > global answer > > > > txt.delete(0.0, 'end') > > sentence = "Here is your problem " > > number1 = random.randint(2,12) > > number2 = random.randint(2,12) > > answer = number1 * number2 > > > > center = txt.tag_config("center", justify="center") > > > > txt.insert(0.0, sentence, "center") > > txt.insert(2.2, number1, "center") > > txt.insert(3.3, " x ", "center") > > txt.insert(4.4, number2, "center") > > All of the above could be replaced with a single format string > and a single insert. > > display = """ > Here is your problem: > > %d x %d > """ % (number1, number2) > > txt.insert(1.0,display, "center") > > > def checkanswer(): > > txt.delete(0.0, 'end') > > > > global score > > global mistakes > > global total > > Its conventional (although not necessary) to put all > globals at the very top of the function. > > > response = int(answerbox.get()) > > wordScore = "Your score is now " > > if response == answer: > > score += 1 > > total += 1 > > result = "Great Job! " > > root.update() > > viewSC() > > viewPercent() > > viewTotal() > > else : > > total += 1 > > result = "Sorry...you made a mistake. \n " > > # the \n above adds a line break. > > mistakes += 1 > > viewMistakes() > > viewTotal() > > viewPercent() > > Notice you display Total and Percent in both block > but do it in an inconsistent order. > If you took both of this display calls outside > the if/else you only need to call them once and > they will be in the same sequence for all cases. > > > center = txt.tag_config("center", justify="center") > > txt.insert(0.0, result, "center") > > txt.insert(3.0, wordScore, "center") > > txt.insert(8.1, score, "center") > ># txt.insert(1,1, "Score is") > > #txt.insert(3,3, score) > > Again this could all be replaced with string > formatting and a single insert() > > > def about(): > > txt.delete(0.0, 'end') > > > > instructions = "Here is how you play the game. Press generate > > problem..and then enter your answer. Your score will be displayed below." > > If you use triple quoted strings you can have > more text and lay it out using line breaks etc. > > > txt.insert(0.0,instructions) > > > > root = Tk() > > root.geometry("640x700+0+0") > > root.title("Times Tables Game") > > > > # MENU SECTION > > # These are included as an example menu structure...in many cases they > > don't do much...but do feature instructions and a quit feature. > > > > # create a toplevel menu > > menubar = Menu(root) > > > > # Just an example of printing hello to console for use in a menu item. > > def hello(): > > print ("hello!") > > > > # display the menu > > root.config(menu=menubar) > > > > # create a pulldown menu, and adds it to the menu bar > > filemenu = Menu(menubar, tearoff=0) > > filemenu.add_command(label="Open", command=makeproblem) > > filemenu
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
Hi Alan, I'm working my way through some of the tips you provided and tried to use the code givenbut am getting an error at Line 75 in my code re: not enough arguments for format string _ return self.func(*args) File "Timespicture.py", line 75, in checkanswer Your current score is: %f""" % answer,score TypeError: not enough arguments for format string The instructions you game me were: > > Is there a way to simply combine all these commands with one txt.insert and > using commas? Not with commas but you can use line breaks inside a triple quoted string and just do a single insert. In fact one of the improvements I'd suggest for your code is to use string formatting to insert the values into your strings before inserting them. eg: fail_str = """ Sorry, you got it wrong, the correct answer was %d Your current score is: %f""" % answer,score txt.insert(1.0, fail_str, "center") Can you see what is going wrong? My code in that section has this: def checkanswer(): txt.delete(0.0, 'end') # as each variable changes outside of function...we need to make these global. global score global mistakes global total # checks for what is written in answerbox using the 'get' feature...makes it an integer. response = int(answerbox.get()) wordScore = "Your score is now " if response == answer: score += 1 total += 1 result = "Great Job! " root.update() viewSC() viewPercent() viewTotal() else : total += 1 result = "Sorry...you made a mistake. \n " # the \n above adds a line break. mistakes += 1 viewMistakes() viewTotal() viewPercent() fail_str = """ Sorry, you got it wrong, the correct answer was %d Your current score is: %f""" % answer,score txt.insert(1.0, fail_str, "center") Full code of whole program below Thanks! - Matt from tkinter import * import random # GLOBAL VARIABLES # Created with a starting value. answer = 0 score = 0 wrong = 0 mistakes = 0 total = 0 def makeproblem(): # access global answer...this is only required IF you need to update the variable within the function. # this happens below when answer is changed to number1 * number2 global answer # erases all text in current text box. txt.delete(0.0, 'end') sentence = "Here is your problem " # example of generating a random number. number1 = random.randint(2,12) number2 = random.randint(2,12) answer = number1 * number2 # creates a justification command called centre. (Not too sure why this is needed here...but not on the answer box elsewhere!) center = txt.tag_config("center", justify="center") txt.insert(0.0, sentence, "center") txt.insert(2.2, number1, "center") txt.insert(3.3, " x ", "center") txt.insert(4.4, number2, "center") def checkanswer(): txt.delete(0.0, 'end') # as each variable changes outside of function...we need to make these global. global score global mistakes global total # checks for what is written in answerbox using the 'get' feature...makes it an integer. response = int(answerbox.get()) wordScore = "Your score is now " if response == answer: score += 1 total += 1 result = "Great Job! " root.update() viewSC() viewPercent() viewTotal() else : total += 1 result = "Sorry...you made a mistake. \n " # the \n above adds a line break. mistakes += 1 viewMistakes() viewTotal() viewPercent() fail_str = """ Sorry, you got it wrong, the correct answer was %d Your current score is: %f""" % answer,score txt.insert(1.0, fail_str, "center") ''' center = txt.tag_config("center", justify="center") txt.insert(0.0, result, "center") txt.insert(3.0, wordScore, "center") txt.insert(8.1, score, "center") # txt.insert(1,1, "Score is") #txt.insert(3,3, score) ''' ''' All of the above could be replaced with a single format string and a single insert. display = """ Here is your problem: %d x %d """ % (number1, number2) txt.insert(1.0,display, "center") ''' def about(): txt.delete(0.0, 'end') instructions = "Here is how you play the game. Press generate problem..and then enter your answer. Your score will be displayed below." txt.insert(0.0,instructions) root = Tk() root.geometry("640x600+0+0") root.title("Times Tables Game") photo = PhotoImage(file="pool.gif") label = Label(image=photo) label.image = photo # keep a reference! label.grid(row=0, columnspan=20) # MENU SECTION # These are included as an example menu structure...in many cases they don't do much...but do feature instructions and a quit feature. # create a toplevel menu menubar = Menu(root) # Just an example of printing hello to console for use in a menu item. def hello(): prin
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
On 17/08/18 03:19, Matthew Polack wrote: > def viewPercent(): > percentCalc = score/total*100 > rounded = round(percentCalc, 2) > percentViewLab["text"] = rounded Since you only want the rounded value for display this is usually achieved using string formatting: >>> s = "Here is a string with a rounded float: %.2f" % 42.3456789 >>> s 'Here is a string with a rounded float: 42.35' That doesn't change the value of the variable but changes how it is displayed. There are lots of other options in format strings to control justification, padding etc. You should definitely explore their capabilities. Just because you are using a GUI rather than a console doesn't mean the string methods are any less useful. > from tkinter import * > import random > > # GLOBAL VARIABLES > # Created with a starting value. > answer = 0 > score = 0 > wrong = 0 > mistakes = 0 > total = 0 > > def makeproblem(): > global answer > > txt.delete(0.0, 'end') > sentence = "Here is your problem " > number1 = random.randint(2,12) > number2 = random.randint(2,12) > answer = number1 * number2 > > center = txt.tag_config("center", justify="center") > > txt.insert(0.0, sentence, "center") > txt.insert(2.2, number1, "center") > txt.insert(3.3, " x ", "center") > txt.insert(4.4, number2, "center") All of the above could be replaced with a single format string and a single insert. display = """ Here is your problem: %d x %d """ % (number1, number2) txt.insert(1.0,display, "center") > def checkanswer(): > txt.delete(0.0, 'end') > > global score > global mistakes > global total Its conventional (although not necessary) to put all globals at the very top of the function. > response = int(answerbox.get()) > wordScore = "Your score is now " > if response == answer: > score += 1 > total += 1 > result = "Great Job! " > root.update() > viewSC() > viewPercent() > viewTotal() > else : > total += 1 > result = "Sorry...you made a mistake. \n " > # the \n above adds a line break. > mistakes += 1 > viewMistakes() > viewTotal() > viewPercent() Notice you display Total and Percent in both block but do it in an inconsistent order. If you took both of this display calls outside the if/else you only need to call them once and they will be in the same sequence for all cases. > center = txt.tag_config("center", justify="center") > txt.insert(0.0, result, "center") > txt.insert(3.0, wordScore, "center") > txt.insert(8.1, score, "center") ># txt.insert(1,1, "Score is") > #txt.insert(3,3, score) Again this could all be replaced with string formatting and a single insert() > def about(): > txt.delete(0.0, 'end') > > instructions = "Here is how you play the game. Press generate > problem..and then enter your answer. Your score will be displayed below." If you use triple quoted strings you can have more text and lay it out using line breaks etc. > txt.insert(0.0,instructions) > root = Tk() > root.geometry("640x700+0+0") > root.title("Times Tables Game") > > # MENU SECTION > # These are included as an example menu structure...in many cases they > don't do much...but do feature instructions and a quit feature. > > # create a toplevel menu > menubar = Menu(root) > > # Just an example of printing hello to console for use in a menu item. > def hello(): > print ("hello!") > > # display the menu > root.config(menu=menubar) > > # create a pulldown menu, and adds it to the menu bar > filemenu = Menu(menubar, tearoff=0) > filemenu.add_command(label="Open", command=makeproblem) > filemenu.add_command(label="Save", command=makeproblem) > filemenu.add_separator() > filemenu.add_command(label="Exit", command=root.quit) > > menubar.add_cascade(label="File", menu=filemenu) > > # create more pulldown menus > editmenu = Menu(menubar, tearoff=0) > editmenu.add_command(label="Cut", command=checkanswer) > editmenu.add_command(label="Copy", command=checkanswer) > editmenu.add_command(label="Paste", command=checkanswer) > menubar.add_cascade(label="Edit", menu=editmenu) > > helpmenu = Menu(menubar, tearoff=0) > helpmenu.add_command(label="About", command=about) > menubar.add_command(label="Hello", command=hello) > menubar.add_cascade(label="Help", menu=helpmenu) > menubar.add_command(label="Quit", command=root.quit) A bit odd adding a command after you add the cascade. Normally we do the cascade as the last item. > # Plain text labels at top of window. > timeslabel = Label(root, text="Times Tables Practice", fg="white", > bg="blue", font=("arial", 36, "bold")) > timeslabel.grid(columnspan=12, sticky='ew') > instruction = Label(root, text="Please click on the button to generate a > problem", fg="blue", bg="white", font=("arial", 16, "bold")) > instruction.grid(row=2, columnspan=20) > > # Makes an entry box with the variable of
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
On 17/08/18 03:19, Matthew Polack wrote: > 1.) Centre feature > > When I use txt.insert I need to use the feature Peter found... > > center = txt.tag_config("center", justify="center") > txt.insert(0.0, result, "center") > > but in the Enter label section...I could just use it straight away..without > defining it with the tag... > > answerbox = Entry(root, bg="grey", font=("arial", 24, "bold"), justify > ="center") > answerbox.grid(row=15, columnspan=2, padx=0, pady=0, sticky=EW) > > Can you explain why? That's how the Tcl/Tlk designers decided to do things. tags are a concept that only apply to the Text widget so don't make much sense in a single line Entry. But essentially its an arbitrary design decision taken 30 years ago and we are stuck with it :-) > 2.) When inserting the wording re: 'You have made mistake' or 'Great job' > etc...I found I had to break it up into separate lines...as I was getting > syntax errors. > > txt.insert(0.0, result, "center") > txt.insert(3.0, wordScore, "center") > txt.insert(8.1, score, "center") > > > Is there a way to simply combine all these commands with one txt.insert and > using commas? Not with commas but you can use line breaks inside a triple quoted string and just do a single insert. In fact one of the improvements I'd suggest for your code is to use string formatting to insert the values into your strings before inserting them. eg: fail_str = """ Sorry, you got it wrong, the correct answer was %d Your current score is: %f""" % answer,score txt.insert(1.0, fail_str, "center") > 3.) Is there anything else in this code that looks like a bit of a > glaring...'Coding Rookie' mistake? Or is simply inefficient? I'll send a second reply with inline comments. -- 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
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
Thanks Alan and Peter, I've gone through and made a bunch of changes based on all your advice. Thank you...everything seems to be fully working and I think I have made the code more efficient using your advice...hope I got everything. (full code below) I've just added an example menu to highlight the concept for teachers or students to refer to. 2 questions: 1.) Centre feature When I use txt.insert I need to use the feature Peter found... center = txt.tag_config("center", justify="center") txt.insert(0.0, result, "center") but in the Enter label section...I could just use it straight away..without defining it with the tag... answerbox = Entry(root, bg="grey", font=("arial", 24, "bold"), justify ="center") answerbox.grid(row=15, columnspan=2, padx=0, pady=0, sticky=EW) Can you explain why? 2.) When inserting the wording re: 'You have made mistake' or 'Great job' etc...I found I had to break it up into separate lines...as I was getting syntax errors. txt.insert(0.0, result, "center") txt.insert(3.0, wordScore, "center") txt.insert(8.1, score, "center") Is there a way to simply combine all these commands with one txt.insert and using commas? 3.) Is there anything else in this code that looks like a bit of a glaring...'Coding Rookie' mistake? Or is simply inefficient? Thanks again for all your help. I've found things are starting to make a lot more sense...and googling things now let me add other features. eg. The rounding function here: def viewPercent(): percentCalc = score/total*100 rounded = round(percentCalc, 2) percentViewLab["text"] = rounded Thank you Peter and Allan..and others here who have helped on the journey. from tkinter import * import random # GLOBAL VARIABLES # Created with a starting value. answer = 0 score = 0 wrong = 0 mistakes = 0 total = 0 def makeproblem(): # access global answer...this is only required IF you need to update the variable within the function. # this happens below when answer is changed to number1 * number2 global answer # erases all text in current text box. txt.delete(0.0, 'end') sentence = "Here is your problem " # example of generating a random number. number1 = random.randint(2,12) number2 = random.randint(2,12) answer = number1 * number2 # creates a justification command called centre. (Not too sure why this is needed here...but not on the answer box elsewhere!) center = txt.tag_config("center", justify="center") txt.insert(0.0, sentence, "center") txt.insert(2.2, number1, "center") txt.insert(3.3, " x ", "center") txt.insert(4.4, number2, "center") def checkanswer(): txt.delete(0.0, 'end') # as each variable changes outside of function...we need to make these global. global score global mistakes global total # checks for what is written in answerbox using the 'get' feature...makes it an integer. response = int(answerbox.get()) wordScore = "Your score is now " if response == answer: score += 1 total += 1 result = "Great Job! " root.update() viewSC() viewPercent() viewTotal() else : total += 1 result = "Sorry...you made a mistake. \n " # the \n above adds a line break. mistakes += 1 viewMistakes() viewTotal() viewPercent() center = txt.tag_config("center", justify="center") txt.insert(0.0, result, "center") txt.insert(3.0, wordScore, "center") txt.insert(8.1, score, "center") # txt.insert(1,1, "Score is") #txt.insert(3,3, score) def about(): txt.delete(0.0, 'end') instructions = "Here is how you play the game. Press generate problem..and then enter your answer. Your score will be displayed below." txt.insert(0.0,instructions) root = Tk() root.geometry("640x700+0+0") root.title("Times Tables Game") # MENU SECTION # These are included as an example menu structure...in many cases they don't do much...but do feature instructions and a quit feature. # create a toplevel menu menubar = Menu(root) # Just an example of printing hello to console for use in a menu item. def hello(): print ("hello!") # display the menu root.config(menu=menubar) # create a pulldown menu, and adds it to the menu bar filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="Open", command=makeproblem) filemenu.add_command(label="Save", command=makeproblem) filemenu.add_separator() filemenu.add_command(label="Exit", command=root.quit) menubar.add_cascade(label="File", menu=filemenu) # create more pulldown menus editmenu = Menu(menubar, tearoff=0) editmenu.add_command(label="Cut", command=checkanswer) editmenu.add_command(label="Copy", command=checkanswer) editmenu.add_command(label="Paste", command=checkanswer) menubar.add_cascade(label="Edit", menu=editmenu) helpmenu = Menu(menubar, tearoff=0) helpmenu.add_command(label="About", command=about) menubar.add_command(label="Hel
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
On 16/08/18 08:18, Matthew Polack wrote: > The last remaining issue is the program does not calculate the percentage > right when you make mistakes...it just keeps giving a result of 100%. > def percentCheck(): > global percentScore > global score > global mistakes > global total While you do need some globals in your program you only need to declare the ones you are changing. In this case you only need to declare percentScore as global. > percentScore = float(score/total) * 100 To debug this I would add a print line such as print(score, total) Since if you always get 100 it suggests that score and total are the same. One problem here is that you are converting to float after doing the division. That's usually the wrong thing to do. In fact I notice you do that a lot of conversions on expressions. Its much safer to do the conversions on the individual values then perform the computation after the conversion. In fact in this case (and most of the other similar cases) you should not need the float conversion since you already converted the values when you read them from the GUI. You should aim to convert the data into the correct type as soon as possible then you will not need to use conversions anywhere else. Some more observations below... > viewPercent() > > > def makeproblem(): > # deletes anything in text box from location 00 to the end > global answer # access global answer > > txt.delete(0.0, 'end') > > sentence = "Here is your problem " > > number1 = random.randint(2,12) > number2 = random.randint(2,12) > > answer = number1 * number2 > > txt.insert(0.0, sentence) > txt.insert(2.2, number1) > txt.insert(3.3, " x ") > txt.insert(4.4, number2) > > def checkanswer(): > # deletes anything in text box from location 00 to the end > txt.delete(0.0, 'end') > > global answer > global score > global wrong > global mistakes > global percentScore > global total > > # checks for what is written in answerbox > response = int(answerbox.get()) > wordScore = "Your score is now " > > if response == answer: > score = int(score + 1) > total = int(total + 1) > else : > score= int(score + 1) > total = int(total + 1) Notice that regardless of what the answer is you update both score and total. And again you don't need the int() conversions, the variables are already integers. > root = Tk() > root.geometry("640x700+0+0") > root.title("Times Tables") > > > #HOW CAN I CENTRE THE TEXT??? > txt = Text(root, width=35, height=8, wrap=WORD, font=("arial", 24, "bold")) > txt.grid(row=12, columnspan=2, sticky=EW ) AS per Peter's link you need to create a tag and configure it with the font and justification you want. Then when you insert the text you add the tag name. eg: center = txt.tag_config("center", justify="center") txt.insert(1.0, "Hello world", "center") > blankline3 = Label(root, text = "", bg = "white") > blankline3.grid(row=17, sticky='ew') I'm not sure what this is for. If you want some space just add some padding to the label below. > scorelab = Label(root, text="Score", bg="green", fg="white", font=("arial", > 20, "bold")) > scorelab.grid(row=18, column=0, sticky=E) Note that you create a Label here, but in ViewSC below you create another label which causes this one to be deleted. This is not necessary, instead just change the text of this label in viewSC. scorelab['text'] = "New text here" > totalLab = Label(root, text="Out of", bg="purple", fg="white", > font=("arial", 20, "bold")) > totalLab.grid(row=19, column=0, sticky=E) Same applies to the other viewXXX functions, just update these labels, don't build and destroy new label widgets each time. That's a lot of wasted work and time for your PC. > def viewSC(): > global score You don't change score so no need for global here. You only need global when changing the data. > scoreViewLab = Label(root, text=score, fg="black", bg="grey", > font=("arial", 20, "bold")) > scoreViewLab.grid(row=18, column=1, sticky=W) I just noticed this is in a different grid location, but the principle still applies create it once at the start of the GUI then update it in the view functions. > def viewTotal(): > global total > #scoreViewLab=Label(root, scoreView, textvariable=scoreView) > totalViewLab = Label(root, text=total, fg="black", bg="grey", > font=("arial", 20, "bold")) > totalViewLab.grid(row=19, column=1, sticky=W) > > def viewWrong(): > global wrong > global mistakes > > #scoreViewLab=Label(root, scoreView, textvariable=scoreView) > wrongViewLab = Label(root, text=mistakes, fg="black", bg="grey", > font=("arial", 20, "bold")) > wrongViewLab.grid(row=20, column=1, sticky=W) You declare wrong as global but never use it. Should this function not be called viewMistakes? > def viewPercent(): > global percentScore > global total >
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
Matthew Polack wrote: > Hi All, > > Thanks to your help I've nearly got my demo 'Times Tables' program fully > working. > > The last remaining issue is the program does not calculate the percentage > right when you make mistakes...it just keeps giving a result of 100%. > > I've looked and head scratched...and am not sure. > > Can anyone figure out what is wrong with this code? You increment the score no matter whether the answer is correct or not. > if response == answer: > score = int(score + 1) > else : > score= int(score + 1) Random remarks - Your code suffers from "over-globalisation". You only need to declare a variable global when you want to change it from within a function. Example: x = 0 def show_x(): # no global necessary print("x =", x) def inc_x(): global x x += 1 - You create a new Label in every call of viewXXX(). For long-running applications that will consume a lot of memory. You should instead create the label once and then update it percentViewLab = Label(...) percentViewLab.grid(...) def viewPercent(): percentViewLab["text"] = percentScore - You convert integers to integers. >score = int(score + 1) should better be written score = score + 1 or score += 1 - I rarely say that, but you have too many functions -- or rather you have written them in such a way that you need to call them in a special order. Personally I would omit the percentCheck function and the percentScore variable and rewrite viewPercent as def viewPercent(): percentViewLab["text"] = score/total*100 or if you want to keep the function def get_percent_score(): return score/total*100 def viewPercent(): percentViewLab["text"] = get_percent_score() With both approaches viewPercent() can never show an out-of-date value. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
Hi All, Thanks to your help I've nearly got my demo 'Times Tables' program fully working. The last remaining issue is the program does not calculate the percentage right when you make mistakes...it just keeps giving a result of 100%. I've looked and head scratched...and am not sure. Can anyone figure out what is wrong with this code? Thanks! - Matt from tkinter import * import random answer = 0 score = 0 wrong = 0 mistakes = 0 percentScore = 0 total = 0 def percentCheck(): global percentScore global score global mistakes global total percentScore = float(score/total) * 100 viewPercent() def makeproblem(): # deletes anything in text box from location 00 to the end global answer # access global answer txt.delete(0.0, 'end') sentence = "Here is your problem " number1 = random.randint(2,12) number2 = random.randint(2,12) answer = number1 * number2 txt.insert(0.0, sentence) txt.insert(2.2, number1) txt.insert(3.3, " x ") txt.insert(4.4, number2) def checkanswer(): # deletes anything in text box from location 00 to the end txt.delete(0.0, 'end') global answer global score global wrong global mistakes global percentScore global total # checks for what is written in answerbox response = int(answerbox.get()) wordScore = "Your score is now " if response == answer: score = int(score + 1) total = int(total + 1) result = "Great Job! " root.update() viewSC() percentCheck() viewPercent() viewTotal() else : score= int(score + 1) total = int(total + 1) result = "Sorry...you were wrong" mistakes = int(mistakes + 1) viewWrong() viewTotal() percentCheck() viewPercent() txt.insert(0.0, result) txt.insert(3.0, wordScore) txt.insert(8.1, score) # txt.insert(1,1, "Score is") #txt.insert(3,3, score) root = Tk() root.geometry("640x700+0+0") root.title("Times Tables") timeslabel = Label(root, text="Times Tables Practice", fg="white", bg="blue", font=("arial", 36, "bold")) timeslabel.grid(columnspan=12, sticky='ew') instruction = Label(root, text="Please click on the button to generate a problem", fg="blue", bg="white", font=("arial", 16, "bold")) instruction.grid(row=2, columnspan=20) blankline = Label(root, text = "", bg = "white") blankline.grid(row=12, sticky='ew') # Makes an entry box with the variable of 'answerbox' answerbox = Entry(root, bg="aqua", font=("arial", 24, "bold")) answerbox.grid(row=15, columnspan=2, sticky=EW) # Makes a button that generate the Times Tables problem btn = Button(root, text="GENERATE PROBLEM", bg="blue", fg="white", command=makeproblem) btn.grid(row=11, columnspan=2, sticky=EW) # Makes a button that checks the answer btn = Button(root, text="CHECK ANSWER", bg="darkblue", fg="white", command=checkanswer) btn.grid(row=13, columnspan=2, sticky=EW) #HOW CAN I CENTRE THE TEXT??? txt = Text(root, width=35, height=8, wrap=WORD, font=("arial", 24, "bold")) txt.grid(row=12, columnspan=2, sticky=EW ) blankline3 = Label(root, text = "", bg = "white") blankline3.grid(row=17, sticky='ew') scorelab = Label(root, text="Score", bg="green", fg="white", font=("arial", 20, "bold")) scorelab.grid(row=18, column=0, sticky=E) totalLab = Label(root, text="Out of", bg="purple", fg="white", font=("arial", 20, "bold")) totalLab.grid(row=19, column=0, sticky=E) wronglab = Label(root, text="Mistakes", bg="red", fg="white", font=("arial", 20, "bold")) wronglab.grid(row=20, column=0, sticky=E) percentlab = Label(root, text="Percentage", bg="aqua", fg="white", font=("arial", 20, "bold")) percentlab.grid(row=21, column=0, sticky=E) def viewSC(): global score #scoreViewLab=Label(root, scoreView, textvariable=scoreView) scoreViewLab = Label(root, text=score, fg="black", bg="grey", font=("arial", 20, "bold")) scoreViewLab.grid(row=18, column=1, sticky=W) def viewTotal(): global total #scoreViewLab=Label(root, scoreView, textvariable=scoreView) totalViewLab = Label(root, text=total, fg="black", bg="grey", font=("arial", 20, "bold")) totalViewLab.grid(row=19, column=1, sticky=W) def viewWrong(): global wrong global mistakes #scoreViewLab=Label(root, scoreView, textvariable=scoreView) wrongViewLab = Label(root, text=mistakes, fg="black", bg="grey", font=("arial", 20, "bold")) wrongViewLab.grid(row=20, column=1, sticky=W) def viewPercent(): global percentScore global total global score #scoreViewLab=Label(root, scoreView, textvariable=scoreView) percentViewLab = Label(root, text=percentScore, fg="black", bg="grey", font=("arial", 20, "bold")) percentViewLab.grid(row=21, column=1, sticky=W) viewSC() viewWrong() viewPercent() viewTotal() root.mainloop() Matthew Polack | Teacher [image: Emailbanner3.png] Trinity Drive | PO Box 822 Horsham Victoria 3
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
Thanks Alan and Peter, Really appreciate your replies. Will try this out tomorrow and see if I can get it to work. I keep googling things myself...but with my 'beginner' status sometimes struggle to understand the solutions out therebut in tiny steps am making progress! Certainly know a lot more than when I started 4 weeks ago! Thank you so much for your support and time replyingit is very encouraging. - Matthew Polack Matthew Polack | Teacher [image: Emailbanner3.png] Trinity Drive | PO Box 822 Horsham Victoria 3402 p. 03 5382 2529 m. 0402456854 e. matthew.pol...@htlc.vic.edu.au w. www.htlc.vic.edu.au On Wed, Aug 15, 2018 at 8:10 PM, Alan Gauld via Tutor wrote: > On 15/08/18 10:18, Peter Otten wrote: > > Matthew Polack wrote: > > > >> *Question 2:* > >> Is there a way to centre text within the text frame? I can change the > font > >> and size...but don't know how to centre it? > > > > Ok, I wanted to know it myself, and found > > > > https://stackoverflow.com/questions/42560585/how-do-i- > center-text-in-the-tkinter-text-widget > > Well done Peter. I've looked for ways to do this > (and other format tricks) several times and > failed. I never thought of looking at tags though... > > Using the string methods as I suggested relies on > using monospace fonts, and splitting the text > manually into lines of appropriate length - a major > pain. > > This works with proportional fonts and long text too. > So much better. > > Thanks again for your superior google skills :-) > > -- > 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 > -- **Disclaimer: *Whilst every attempt has been made to ensure that material contained in this email is free from computer viruses or other defects, the attached files are provided, and may only be used, on the basis that the user assumes all responsibility for use of the material transmitted. This email is intended only for the use of the individual or entity named above and may contain information that is confidential and privileged. If you are not the intended recipient, please note that any dissemination, distribution or copying of this email is strictly prohibited. If you have received this email in error, please notify us immediately by return email or telephone +61 3 5382 2529** and destroy the original message.* ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
On 15/08/18 10:18, Peter Otten wrote: > Matthew Polack wrote: > >> *Question 2:* >> Is there a way to centre text within the text frame? I can change the font >> and size...but don't know how to centre it? > > Ok, I wanted to know it myself, and found > > https://stackoverflow.com/questions/42560585/how-do-i-center-text-in-the-tkinter-text-widget Well done Peter. I've looked for ways to do this (and other format tricks) several times and failed. I never thought of looking at tags though... Using the string methods as I suggested relies on using monospace fonts, and splitting the text manually into lines of appropriate length - a major pain. This works with proportional fonts and long text too. So much better. Thanks again for your superior google skills :-) -- 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
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
Matthew Polack wrote: > *Question 2:* > Is there a way to centre text within the text frame? I can change the font > and size...but don't know how to centre it? Ok, I wanted to know it myself, and found https://stackoverflow.com/questions/42560585/how-do-i-center-text-in-the-tkinter-text-widget ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
Matthew Polack wrote: > *Question 1:* > > *Why cant the program check if 'answer' variable is correct?* Change the line result = "Sorry...you were wrong. in your script to result = "Sorry...you were wrong. Expected {!r}, but got {!r}".format(answer, response) and find out yourself. Hint: answer in the makeproblem() function is not a global variable. > lib\tkinter\__init__.py", line 3269, in insert > self.tk.call((self._w, 'insert', index, chars) + args) > _tkinter.TclError: bad text index "1" The first argument of the Text.insert() is a string in a special format. Read http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text-index.html http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/text-methods.html for the details. You have a mix of one float (which may work by accident) or two integers (which raises an exception). > *Question 2:* > Is there a way to centre text within the text frame? I can change the font > and size...but don't know how to centre it? I don't know, and I'm too lazy to google ;) > txt = Text(root, width=35, height=10, wrap=WORD, font=("arial", 24, > "bold")) txt.grid(row=12, columnspan=2, sticky=EW ) > > > *Question 3:* > > My 'Score' check idea..may not actually work...haven't been able to get > that far yet though! The score variable is not declared global and not initialised. You cannot increment something that doesn't exist. > Thanks so much for any clues. > > - Matthew Polack > > > > > > > > Matthew Polack | Teacher > > > [image: Emailbanner3.png] > > Trinity Drive | PO Box 822 > > Horsham Victoria 3402 > > p. 03 5382 2529 m. 0402456854 > > e. matthew.pol...@htlc.vic.edu.au > > w. www.htlc.vic.edu.au > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Times Tables Program that constantly tells you that you are wrong!
On 15/08/18 01:56, Matthew Polack wrote: > from tkinter import * > > import random > > answer = "global" You have the right concept but the wrong implementation. To declare a variable as global you declare it as normal in the outer scope then inside each function that uses it add a global line which, in this case, looks like global answer So your code should look like: answer = 0 # placeholder value def makeProblem(): global answer # access global answer def checkAnswer(): global answer BTW, Please post messages in plain text not HTML/RTF because otherwise we lose all the formatting which is critical in understanding the code. > def makeproblem(): > # deletes anything in text box from location 00 to the end > txt.delete(0.0, 'end') > sentence = "Your first problem is " > > number1 = random.randint(2,12) > number2 = random.randint(2,12) > answer = number1 * number2 without the global line at the top this create a local variable inside the function which is then lost when the function exits > txt.insert(0.0, sentence) > txt.insert(2.2, number1) > txt.insert(3.3, " x ") > txt.insert(4.4, number2) > > def checkanswer(): > # deletes anything in text box from location 00 to the end > txt.delete(0.0, 'end') > > # checks for what is written in answerbox > response = int(answerbox.get()) > if response == answer: This compares response to the global answer which has the value "global", so it is never equal. > result = "Great Job!" > score = int(score + 1) > else : > result = "Sorry...you were wrong" > txt.insert(0.0, result) > txt.insert(1,1, "Score is") > txt.insert(2,2, score) > > root = Tk() > root.geometry("640x640+0+0") > root.title("Times Tables") > > > timeslabel = Label(root, text="Times Tables Practice", fg="white", bg="blue", > font=("arial", 36, "bold")) > timeslabel.grid(columnspan=12, sticky='ew') > instruction = Label(root, text="Please click on the button to generate a > problem", fg="blue", bg="white", font=("arial", 16, "bold")) > instruction.grid(row=2, columnspan=20) > > blankline = Label(root, text = "", bg = "white") > blankline.grid(row=12, sticky='ew') > > # Makes an entry box with the variable of 'answerbox' > answerbox = Entry(root, bg="aqua", font=("arial", 24, "bold")) > answerbox.grid(row=15, columnspan=2, sticky=EW) > > # Makes a button that generate the Times Tables problem > btn = Button(root, text="GENERATE PROBLEM", bg="blue", fg="white", command= > makeproblem) > btn.grid(row=11, columnspan=2, sticky=EW) > > # Makes a button that checks the answer > btn = Button(root, text="CHECK ANSWER", bg="darkblue", fg="white", command= > checkanswer) > btn.grid(row=13, columnspan=2, sticky=EW) > > #HOW CAN I CENTRE THE TEXT??? If you mean the widget look at the fill and padding attributes of the layout manager. If you mean the text inside the widget look at the string formatting methods. Especiially center(), ljust() and rjust(). Its messy but with patience and suitable font selection it works. I don't know any other way in Tkinter, so usually stick with left aligned! > txt = Text(root, width=35, height=10, wrap=WORD, font=("arial", 24, "bold")) > txt.grid(row=12, columnspan=2, sticky=EW ) > > root.mainloop() > > > *Question 1:* > *Why cant the program check if 'answer' variable is correct?* See use of global above > *Question 2:* > Is there a way to centre text within the text frame? I can change the font > and size...but don't know how to centre it? Only with difficulty. See above. > *Question 3:* > My 'Score' check idea..may not actually work...haven't been able to get > that far yet though! It should work but you need to make score a global variable too or else the score will be thrown away when the function ends. -- 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