I am trying to run a while loop inside my program, but when the while loop is in place, the code stops, and the tkinter window does not open. How do I solve this? It should be so that the code writes out two random numbers, and then when the correct answer is input, it should re-loop.
from tkinter import *
import random
root = Tk()
#Frames
topFrame = Frame(root) # I want an invisible container in root
topFrame.pack()
bottomFrame = Frame(root) # I want an invisible container in root
bottomFrame.pack(side=BOTTOM)
#End Of Frames
#Addition Question Maker
AnswerBox = Entry(topFrame)
AnswerBox.grid(row=0,column=4)
EqualsSign = Label(topFrame, text="=").grid(row=0,column=3)
AdditionSign = Label(topFrame, text="+").grid(row=0,column=1)
NewQuestion = True
while NewQuestion == True:
AdditionQuestionLeftSide = random.randint(0, 10)
AdditionQuestionRightSide = random.randint(0, 10)
global Total
Total = AdditionQuestionLeftSide + AdditionQuestionRightSide
AdditionQuestionRightSide = Label(topFrame, text= AdditionQuestionRightSide).grid(row=0,column=0)
AdditionQuestionLeftSide= Label(topFrame, text= AdditionQuestionLeftSide).grid(row=0,column=2)
answer = None
def OutputAnswerText(event):
global answer
answer = AnswerBox.get()
if Total == int(answer):
Correct = Label(topFrame, text="Correct").grid(row=2,column=3)
NewQuestion = True
else:
Correct = Label(topFrame, text="Wrong").grid(row=2,column=3)
AnswerBox.bind('<Return>', OutputAnswerText)
root.mainloop()
Instead of making a while loop, I suggest making NewQuestion a function. The function gets called initially, then if the answer is correct the function gets called again. Here is my code for the function, along with an automatic entry delete option to remove the need to backspace your answer after inputting a correct answer.
from tkinter import *
import random
root = Tk()
#Frames
topFrame = Frame(root) # I want an invisible container in root
topFrame.pack()
bottomFrame = Frame(root) # I want an invisible container in root
bottomFrame.pack(side=BOTTOM)
#End Of Frames
#Addition Question Maker
AnswerBox = Entry(topFrame)
AnswerBox.grid(row=0,column=4)
EqualsSign = Label(topFrame, text="=").grid(row=0,column=3)
AdditionSign = Label(topFrame, text="+").grid(row=0,column=1)
def NewQuestion():
AdditionQuestionLeftSide = random.randint(0, 10)
AdditionQuestionRightSide = random.randint(0, 10)
global Total
Total = AdditionQuestionLeftSide + AdditionQuestionRightSide
AdditionQuestionRightSide = Label(topFrame, text= AdditionQuestionRightSide).grid(row=0,column=0)
AdditionQuestionLeftSide= Label(topFrame, text= AdditionQuestionLeftSide).grid(row=0,column=2)
answer = None
return
NewQuestion()
def OutputAnswerText(event):
global answer
global AnswerBox
answer = AnswerBox.get()
if Total == int(answer):
Correct = Label(topFrame, text="Correct").grid(row=2,column=3)
AnswerBox.delete(0, END)
NewQuestion()
else:
Correct = Label(topFrame, text="Wrong").grid(row=2,column=3)
AnswerBox.bind('<Return>', OutputAnswerText)
root.mainloop()
You have an infinite loop:
while NewQuestion == True:
There is no place where NewQuestion can become false (and no break in the loop). So the loop is infinite.
Also:
EqualsSign = Label(topFrame, text="=").grid(row=0,column=3)
doesn't work because grid returns None. If you want to keep a reference to the widget, you have to use the two-lines version like in:
AnswerBox = Entry(topFrame)
AnswerBox.grid(row=0,column=4)
Related
The problem is the .after() method inside the 'get_content' function. The delay freezes the whole program. I tried solving it with threading but I can't figure it out. I tried a lot of variations. I will just post the code with the last one! Any suggestions? (The code still needs some fixes here and there but the freezing issue is really annoying and I want to get rid of this first)
import random
import tkinter as tk
from sentences import sentences
import threading
from PIL import ImageTk, Image
root = tk.Tk()
root.title("Speed typing test")
root.geometry('700x700')
# Dynamic labels
entry_text = tk.StringVar()
seconds = tk.IntVar()
# Stopwatch
def seconds_counter(*args):
if not entry_text.get():
seconds.set(0)
else:
counter = 0
while counter < 100:
counter += 1
root.update()
root.after(1000)
seconds.set(counter)
global total_time
total_time = counter
if entry_text.get() == sentence:
final = (len(entry.get()) / 5) / (0.1 * total_time)
final_lbl = tk.Label(root, text=f"WPM: {final}")
final_lbl.pack()
entry.delete(0, tk.END)
seconds.set(0)
word_list = sentence.split(' ')
total_words = len(word_list)
total_words_lbl = tk.Label(root, text=f'Total words: {total_words}')
total_words_lbl.pack()
counter = 0
break
x = threading.Thread(target=seconds_counter)
x.start()
sentence = random.choice(sentences)
sentence = sentence.strip('.')
# Create widgets
logo = ImageTk.PhotoImage(Image.open('images/logo.png'))
logo_lbl = tk.Label(image=logo)
sentence_lbl = tk.Label(root, text=sentence)
entry = tk.Entry(root, width=500, textvariable=entry_text)
seconds_lbl = tk.Label(root, textvariable=seconds)
# Place widgets
logo_lbl.pack()
sentence_lbl.pack()
entry.pack()
seconds_lbl.pack()
entry_text.trace('w', seconds_counter)
def stop():
root.destroy()
# command=quit freezes for some reason
btn_quit = tk.Button(root, text='Quit', command=stop)
btn_quit.pack()
root.mainloop()
I'm trying to create a programm that reads ANT signals and displays them in a TKinter window.
To display the changing values, I'm updating labels (in an infinite loop),which works so far, but whenever I try to move the window, the program crashes (no response).
So here's what the (final program) should do:
Receive and store the ANT data, which I read with another file (which gives me
power and cadence)
Round the numbers to 2-3 decimals (max)
Read the total power output so far from a file
Write the power data in a file (append)
Sum the total power output
display the current speed, cadence, power and total power output
My Code:
# imports
import random
import time
from tkinter import *
# creating root tkinter Window
root = Tk()
root.title("ANT+ Live Data")
# defining Text Variables
running = 0
SAVE_FILE = "power_doc.txt"
HEADLINE_TEXT = StringVar()
HEADLINE_TEXT.set('')
HEADLINE_M = StringVar()
HEADLINE_M.set('')
power_display = StringVar()
power_display.set('0')
cadence_display = StringVar()
cadence_display.set('0')
speed_display = StringVar()
speed_display.set('0')
powertotal_display = StringVar()
powertotal_display.set('0')
# defining Window Size
root.geometry("800x600")
# creating Label Frame to wrap labels
frame = LabelFrame(root)
frame.pack(padx=20, pady=20)
# creating labels, Headline 1
slabel = Label(root, font = ("Helvetica",48) ,textvariable = HEADLINE_M, justify=CENTER, bg="#FFFFFF", fg = '#000000')
slabel.pack(fill=BOTH, padx=20, pady=10)
# headline 2
headLine = Label(root, font=("Helvetica", 26), textvariable= HEADLINE_TEXT, justify=CENTER, bg="#FFFFFF", fg = '#000000')
headLine.pack(fill=BOTH, pady=5)
# power
l1 = Label(root, font = ("Helvetica",20) ,textvariable = power_display, justify=CENTER, bg="#190000", fg = '#B0C4C2')
l1.pack(fill=BOTH)
# cadence
l2 = Label(root, font = ("Helvetica",20), textvariable = cadence_display, justify=CENTER, bg="#190000", fg = '#B0C4C2')
l2.pack(fill=BOTH)
# speed
l3 = Label(root, font = ("Helvetica",20), textvariable = speed_display, justify=CENTER, bg="#190000", fg = '#B0C4C2')
l3.pack(fill=BOTH)
# total Power
l4 = Label(root, font = ("Helvetica",20), textvariable = powertotal_display, justify=CENTER, bg="#190000", fg = '#B0C4C2')
l4.pack(fill=BOTH)
# function to read total power values out of a file
def get_power_total(SAVE_FILE):
power_total = 0
with open(SAVE_FILE, 'r') as inp:
for line in inp:
try:
num = float(line)
power_total += num
except ValueError:
print('{} is not a number!'.format(line))
power_total = round_number(power_total)
return power_total
# generate random Numbers for testing purposes
def randomize_number(inputNumber):
inputNumber = float(inputNumber)*random.uniform(0.99, 1.01)
inputNumber = round_number(inputNumber)
return inputNumber
# rounds numbers to 2 decimals
def round_number(inputNumber):
inputNumber = round(inputNumber, 2)
return inputNumber
# use formula for a 28" Wheel to determine Speed using cadence
def determine_speed(cadence):
speed = float(cadence)*0.356
speed = round_number(speed)
return speed
def get_power(cadence):
power = float(cadence)*0.8
power = round_number(power)
return power
# dummy function to test-print Values, redundant in current state
def print_values(x1, x2, x3):
print("Leistung: {} W Trittfrequenz: {} Geschwindigkeit: {} Km/H" .format(x1, x2, x3))
# write in document to determine total power output
def write_file(SAVE_FILE, power):
f = open(SAVE_FILE, "a+")
f.write(str(power) + '\n')
f.close()
def update_label():
power_total = get_power_total(SAVE_FILE)
cadence = int(50)
cadence = randomize_number(cadence)
root.after(100)
power = get_power(cadence)
root.after(100)
speed = determine_speed(cadence)
root.after(100)
power_total += power
write_file(SAVE_FILE, power)
power_display.set("Leistung: {} W".format(power))
cadence_display.set("Trittfrequenz: {}".format(cadence))
speed_display.set("Geschwindigkeit : {} Km/h".format(speed))
powertotal_display.set("Gesamtleistung seit 10 Uhr: {} W".format(power_total))
root.after(1000)
root.update_idletasks()
# mainloop to display the window
while True:
root.after(1000, update_label())
root.mainloop()
This is basically just a draft to import the ANT data, hence there are some numbers being randomly generated to show if the label update function works.
I'm fairly new to coding with Python (or coding at all), so I'm pretty sure there are other issues with my code as well, but perhaps someone has a suggestion on how to solve my issue.
Any help or suggestions are appreciated.
Cheers in advance!
Edit: Solved! thanks Jason!
Changes were to be made here:
def update_label():
power_display.set("Leistung: {} W".format(power))
cadence_display.set("Trittfrequenz: {}".format(cadence))
speed_display.set("Geschwindigkeit : {} Km/h".format(speed))
powertotal_display.set("Gesamtleistung seit 10 Uhr: {} W".format(power_total))
root.after(1000, update_label)
root.update_idletasks()
root.after(1000, update_label)
root.mainloop()
I am trying to make a 'guess the number' game with Pyhon tkinter but so far I have not been able to retrieve the input from the user.
How can I get the input in entry when b1 is pressed?
I also want to display a lower or higher message as a clue to the player but I am not sure if what I have is right:
import time
import random
import decimal
import tkinter as tk
root = tk.Tk()
randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)
guess = 0
def get(entry):
guess = entry.get()
return guess
def main():
b1 = tk.Button(root, text="Guess", command=get)
entry = tk.Entry()
b1.grid(column=1, row=0)
entry.grid(column=0, row=0)
root.mainloop()
print(guess)
if guess < randomnum:
l2 = tk.Label(root, text="Higher!")
l2.grid(column=0, row=2)
elif guess > randomnum:
l3 = tk.Label(root, text="Lower!")
l3.grid(column=0, row=2)
while guess != randomnum:
main()
l4 = tk.Label(root, text="Well guessed")
time.sleep(10)
You could define get inside main, so that you can access the entry widget you created beforehand, like this:
entry = tk.Entry()
def get():
guess = entry.get()
return guess # Replace this with the actual processing.
b1 = tk.Button(root, text="Guess", command=get)
You've assembled random lines of code out of order. For example, the root.mainloop() should only be called once after setting up the code but you're calling it in the middle of main() such that anything after won't execute until Tk is torn down. And the while guess != randomnum: loop has no place in event-driven code. And this, whatever it is, really should be preceded by a comment:
randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)
Let's take a simpler, cleaner approach. Rather than holding onto pointers to the the various widgets, let's use their textvariable and command properties to run the show and ignore the widgets once setup. We'll use StringVar and IntVar to handle input and output. And instead of using sleep() which throws off our events, we'll use the after() feature:
import tkinter as tk
from random import randint
def get():
number = guess.get()
if number < random_number:
hint.set("Higher!")
root.after(1000, clear_hint)
elif number > random_number:
hint.set("Lower!")
root.after(1000, clear_hint)
else:
hint.set("Well guessed!")
root.after(5000, setup)
def setup():
global random_number
random_number = randint(1, 100)
guess.set(0)
hint.set("Start Guessing!")
root.after(2000, clear_hint)
def clear_hint():
hint.set("")
root = tk.Tk()
hint = tk.StringVar()
guess = tk.IntVar()
random_number = 0
tk.Entry(textvariable=guess).grid(column=0, row=0)
tk.Button(root, text="Guess", command=get).grid(column=1, row=0)
tk.Label(root, textvariable=hint).grid(column=0, row=1)
setup()
root.mainloop()
Here is a tkinter version on the number guessing game.
while or after are not used!
Program checks for illegal input (empty str or words) and reports error message. It also keeps track of the number of tries required to guess the number and reports success with a big red banner.
I've given more meaningful names to widgets and used pack manager instead of grid.
You can use the button to enter your guess or simply press Return key.
import time
import random
import tkinter as tk
root = tk.Tk()
root.title( "The Number Guessing Game" )
count = guess = 0
label = tk.Label(root, text = "The Number Guessing Game", font = "Helvetica 20 italic")
label.pack(fill = tk.BOTH, expand = True)
def pick_number():
global randomnum
label.config( text = "I am tkinking of a Number", fg = "black" )
randomnum = random.choice( range( 10000 ) )/100
entry.focus_force()
def main_game(guess):
global count
count = count + 1
entry.delete("0", "end")
if guess < randomnum:
label[ "text" ] = "Higher!"
elif guess > randomnum:
label[ "text" ] = "Lower!"
else:
label.config( text = f"CORRECT! You got it in {count} tries", fg = "red" )
root.update()
time.sleep( 4 )
pick_number()
count = 0
def get( ev = None ):
guess = entry.get()
if len( guess ) > 0 and guess.lower() == guess.upper():
guess = float( guess )
main_game( guess )
else:
label[ "text" ] = "MUST be A NUMBER"
entry.delete("0", "end")
entry = tk.Entry(root, font = "Helvetica 15 normal")
entry.pack(fill = tk.BOTH, expand = True)
entry.bind("<Return>", get)
b1 = tk.Button(root, text = "Guess", command = get)
b1.pack(fill = tk.BOTH, expand = True)
pick_number()
root.geometry( "470x110" )
root.minsize( 470, 110 )
root.mainloop()
Correct way to write guess number.
I write a small script for number guessing game in Python in
get_number() function.
Used one widget to update Label instead of duplicating.
I added some extra for number of turns that you entered.
Code modified:
import time
import random
import decimal
import tkinter as tk
root = tk.Tk()
randomnum = float(decimal.Decimal(random.randrange(100,10000))/100)
print(randomnum)
WIN = False
GUESS = 0
TURNS = 0
Vars = tk.StringVar(root)
def get_number():
global TURNS
while WIN == False:
Your_guess = entry.get()
if randomnum == float(Your_guess):
guess_message = f"You won!"
l3.configure(text=guess_message)
number_of_turns = f"Number of turns you have used: {TURNS}"
l4.configure(text=number_of_turns)
l4.grid(column=0, row=3, columnspan=3, pady=5)
WIN == True
break
else:
if randomnum > float(Your_guess):
guess_message = f"Your Guess was low, Please enter a higher number"
else:
guess_message = f"your guess was high, please enter a lower number"
l3.configure(text=guess_message)
l3.grid(column=0, row=2, columnspan=3, pady=5)
TURNS +=1
return Your_guess
label = tk.Label(root, text="The Number Guessing Game", font="Helvetica 12 italic")
label.grid(column=0, row=0, columnspan=3, sticky='we')
l2 = tk.Label(root, text='Enter a number between 1 and 100',
fg='white', bg='blue')
l2.grid(row=1, column=0, sticky='we')
entry = tk.Entry(root, width=10, textvariable=Vars)
entry.grid(column=1, row=1, padx=5,sticky='w')
b1 = tk.Button(root, text="Guess", command=get_number)
b1.grid(column=1, row=1, sticky='e', padx=75)
l3 = tk.Label(root, width=40, fg='white', bg='red' )
l4 = tk.Label(root, width=40, fg='white', bg='black' )
root.mainloop()
while guess:
time.sleep(10)
Output for enter floating numbers:
Output after the guess was high:
Output after the guess was low:
Output You won and number of turns:
I wrote complicated program in Python 3.4 (with tkinter gui). It's temperature converter (Celsius to Fahrenheit and reverse) in real-time. It works almost good, but there is one problem. I have to add a space after input value every time. Anyone have idea what's wrong in this program?
from tkinter import *
def cel_na_fahr(event):
e = ".0"
a = float(ent1.get())
a = round((32+9/5*a),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent2.delete(0,END)
ent2.insert(0,a+event.char)
else:
ent2.delete(0,END)
ent2.insert(0,a+event.char)
def fahr_na_cel(event):
e = ".0"
a = float(ent2.get())
a = round(5/9*(a-32),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent1.delete(0,END)
ent1.insert(0,a+event.char)
else:
ent1.delete(0,END)
ent1.insert(0,a+event.char)
root = Tk()
root.geometry("300x180+400+400")
fr1 = Frame(root, padx=5, pady=40)
fr1.pack(side=TOP)
fr2 = Frame(root)
fr2.pack(side=TOP)
lbl1 = Label(fr1, text="cel to fahr ")
lbl1.pack(side=LEFT)
ent1 = Entry(fr1)
ent1.pack(side=RIGHT)
lbl2 = Label(fr2, text="fahr to cel ")
lbl2.pack(side=LEFT)
ent2 = Entry(fr2)
ent2.pack(side=RIGHT)
ent1.bind('<Key>', cel_na_fahr)
ent2.bind('<Key>', fahr_na_cel)
root.mainloop()
You have to type a space because when the <Key> callback triggers, the key that the user most recently pressed hasn't yet been added to the entry. This is probably what you're trying to compensate for by adding event.char, although you're doing it in the wrong place anyway.
Change your bindings to KeyRelease, so that the callbacks trigger after the entry is updated, and remove the +event.char stuff, as you don't need it any more.
from tkinter import *
def cel_na_fahr(event):
print(ent1.get())
e = ".0"
a = float(ent1.get())
a = round((32+9/5*a),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent2.delete(0,END)
ent2.insert(0,a)
else:
ent2.delete(0,END)
ent2.insert(0,a)
def fahr_na_cel(event):
print(ent2.get())
e = ".0"
a = float(ent2.get())
a = round(5/9*(a-32),2)
a = str(a)
if a.endswith(e):
a=a.replace(".0","")
ent1.delete(0,END)
ent1.insert(0,a)
else:
ent1.delete(0,END)
ent1.insert(0,a)
root = Tk()
root.geometry("300x180+400+400")
fr1 = Frame(root, padx=5, pady=40)
fr1.pack(side=TOP)
fr2 = Frame(root)
fr2.pack(side=TOP)
lbl1 = Label(fr1, text="cel to fahr ")
lbl1.pack(side=LEFT)
ent1 = Entry(fr1)
ent1.pack(side=RIGHT)
lbl2 = Label(fr2, text="fahr to cel ")
lbl2.pack(side=LEFT)
ent2 = Entry(fr2)
ent2.pack(side=RIGHT)
ent1.bind('<KeyRelease>', cel_na_fahr)
ent2.bind('<KeyRelease>', fahr_na_cel)
root.mainloop()
What is wrong with this program? Every time I run it the first math problem is show before I push start. Also the answer is always the first math problem, it never changes. Also there should not be a math problem above the timer. Thanks, Scott
from Tkinter import*
import time
import tkMessageBox
import random
def Questions():
number1 = random.randrange(1,25)
number2 = random.randrange(1,50)
answer = number1 + number2
prompt = ("Add " + str(number1) + " and " + str(number2))
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
return answer
def start():
global count_flag
Questions()
count_flag = True
count = 0.0
while True:
if count_flag == False:
break
# put the count value into the label
label['text'] = str(count)
# wait for 0.1 seconds
time.sleep(0.1)
# needed with time.sleep()
root.update()
# increase count
count += 0.1
def Submit(answer, entryWidget):
""" Display the Entry text value. """
global count_flag
count_flag = False
print answer
if entryWidget.get().strip() == "":
tkMessageBox.showerror("Tkinter Entry Widget", "Please enter a number.")
if answer != int(entryWidget.get().strip()):
tkMessageBox.showinfo("Answer", "INCORRECT!")
else:
tkMessageBox.showinfo("Answer", "CORRECT!")
# create a Tkinter window
root = Tk()
root.title("Math Quiz")
root["padx"] = 40
root["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(root)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Answer:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
#directions
directions = ('Click start to begin. You will be asked a series of questions.')
instructions = Label(root, text=directions, width=len(directions), bg='orange')
instructions.pack()
# this will be a global flag
count_flag = True
answer = Questions()
Sub = lambda: Submit(answer, entryWidget)
#stopwatch = lambda: start(answer)
# create needed widgets
label = Label(root, text='0.0')
btn_submit = Button(root, text="Submit", command = Sub)
btn_start = Button(root, text="Start", command = start)
btn_submit.pack()
btn_start.pack()
label.pack()
# start the event loop
root.mainloop()
Your problem is with how you're calling the Questions() method. You only ask for the answer once with
answer = Questions()
and you do this before you press start (which is why it shows up before you hit start)
To fix it you could use code like this:
from Tkinter import*
import time
import tkMessageBox
import random
def Questions():
number1 = random.randrange(1,25)
number2 = random.randrange(1,50)
answer = number1 + number2
prompt = ("Add " + str(number1) + " and " + str(number2))
label1 = Label(root, text=prompt, width=len(prompt), bg='yellow')
label1.pack()
return answer
def start():
global count_flag
global answer
answer = Questions()
count_flag = True
count = 0.0
while True:
if count_flag == False:
break
# put the count value into the label
label['text'] = str(count)
# wait for 0.1 seconds
time.sleep(0.1)
# needed with time.sleep()
root.update()
# increase count
count += 0.1
def Submit(answer, entryWidget):
""" Display the Entry text value. """
global count_flag
count_flag = False
print answer
if entryWidget.get().strip() == "":
tkMessageBox.showerror("Tkinter Entry Widget", "Please enter a number.")
if answer != int(entryWidget.get().strip()):
tkMessageBox.showinfo("Answer", "INCORRECT!")
else:
tkMessageBox.showinfo("Answer", "CORRECT!")
# create a Tkinter window
root = Tk()
root.title("Math Quiz")
root["padx"] = 40
root["pady"] = 20
# Create a text frame to hold the text Label and the Entry widget
textFrame = Frame(root)
#Create a Label in textFrame
entryLabel = Label(textFrame)
entryLabel["text"] = "Answer:"
entryLabel.pack(side=LEFT)
# Create an Entry Widget in textFrame
entryWidget = Entry(textFrame)
entryWidget["width"] = 50
entryWidget.pack(side=LEFT)
textFrame.pack()
#directions
directions = ('Click start to begin. You will be asked a series of questions.')
instructions = Label(root, text=directions, width=len(directions), bg='orange')
instructions.pack()
# this will be a global flag
count_flag = True
Sub = lambda: Submit(answer, entryWidget)
#stopwatch = lambda: start(answer)
# create needed widgets
label = Label(root, text='0.0')
btn_submit = Button(root, text="Submit", command = Sub)
btn_start = Button(root, text="Start", command = start)
btn_submit.pack()
btn_start.pack()
label.pack()
# start the event loop
root.mainloop()
In this code the answer is updated every time you hit start and only updates when you hit start.