Search code examples
pythonuser-inputpython-turtle

How do I display questions to the user on a screen (turtle), instead of in the terminal?


I'm making a program which solves f.e. the quadratic formula. However I would like to ask the variables (A,B,C) in a screen with "import turtle" instead of in the terminal. I know how to make a screen: background color; amount of pixels; etc. But I don't know how to ask the variables and display the answer on that screen.

This is the code:

import math
import turtle

wn = turtle.Screen()
wn.title("VKV by @Boldarcticwolf")
wn.bgcolor("green")
wn.setup(width=600, height=600)


A = int(input("What is A? "))
B = int(input("What is B? "))
C = int(input("What is C? "))

D = (B * B) - (4 * A * C)
    
if D < 0: 
    print('D is', D)
       
elif D == 0:
    X1 = (-1 * B) / (2 * A)
    print('D is 0 and x is', X )
    
elif D > 0:
    X1 = ((-1 * B) + math.sqrt(D)) / (2 * A)
    X2 = ((-1 * B) - math.sqrt(D)) / (2 * A)
    print('D is', D, ', X1 is', X1, 'and X2 is', X2)

This brings up a screen and asks the variables but doesn't ask them on the screen.


Solution

  • You can use turtle.textinput to pop a dialog for user input.

    import math
    import turtle
    
    wn = turtle.Screen()
    wn.title("VKV by @Boldarcticwolf")
    wn.bgcolor("green")
    wn.setup(width=600, height=600)
    
    
    A = int(turtle.textinput('A value',"What is A? "))
    B = int(turtle.textinput('B value',"What is B? "))
    C = int(turtle.textinput('C value',"What is C? "))
    
    D = (B * B) - (4 * A * C)
        
    if D < 0: 
        turtle.write(f'D is{D}', font=('Courier', 30, 'italic'), align='center' )
           
    elif D == 0:
        X1 = (-1 * B) / (2 * A)
        turtle.write(f'D is 0 and {X1} is {X1}', font=('Courier', 30, 'italic'), align='center' )
        
    elif D > 0:
        X1 = ((-1 * B) + math.sqrt(D)) / (2 * A)
        X2 = ((-1 * B) - math.sqrt(D)) / (2 * A)
        turtle.write(f'D is {D}, X1 is{X1} and and X2 is {X2}', font=('Courier', 30, 'italic'), align='center' )
        
    wn.exitonclick()
    

    Note, you should probably add some sort of validation, or use try/except, to check the use has actually entered a numeric value.