Write a program that asks a user for a radius value and then draws a blue circle inside a red square in the center of the canvas.

Make sure to use parameters so that the circle-square combo can be altered to any size.

Hint: You can only collect one value named radius from the user, so you may first need to determine a mathematical relationship between these two shapes.

1 answer

To create a program that draws a blue circle inside a red square based on a radius provided by the user, we first need to establish a relationship between the radius of the circle and the size of the square.

A good relationship for this scenario is that the diameter of the circle should be equal to the side length of the square. Since the diameter of a circle is twice its radius (diameter = 2 * radius), the side length of the square will also be 2 * radius.

With this understanding, we can use a graphics library such as tkinter in Python to draw the shapes. Below is a complete program that does this:

import tkinter as tk

def draw_circle_in_square(radius):
    # Calculate the side length of the square
    side_length = 2 * radius

    # Creating the main window
    window = tk.Tk()
    window.title("Circle in Square")
    
    # Creating a canvas
    canvas_size = side_length + 20  # Adding padding
    canvas = tk.Canvas(window, width=canvas_size, height=canvas_size, bg='white')
    canvas.pack()

    # Calculate square's top-left and bottom-right coordinates
    square_top_left = (10, 10)
    square_bottom_right = (square_top_left[0] + side_length, square_top_left[1] + side_length)

    # Draw red square
    canvas.create_rectangle(square_top_left[0], square_top_left[1], 
                            square_bottom_right[0], square_bottom_right[1], 
                            fill='red')

    # Calculate circle's bounding box
    circle_bounds = (10, 10, 10 + side_length, 10 + side_length)

    # Draw blue circle
    canvas.create_oval(circle_bounds, fill='blue')

    # Start the Tkinter main loop
    window.mainloop()

# Main program
if __name__ == "__main__":
    # Ask the user for the radius
    radius_input = input("Please enter the radius of the circle: ")
    try:
        radius = float(radius_input)
        draw_circle_in_square(radius)
    except ValueError:
        print("Invalid input! Please enter a numeric value.")

Explanation:

  • The program uses the tkinter library to create a simple GUI application.
  • The user is prompted to enter a radius value.
  • The program calculates the side length of the square, which is double the radius.
  • It then creates a window and a canvas to draw both the square and the circle.
  • A red square and a blue circle are drawn on the canvas.

To run this program, make sure you have Python installed, and then you can execute the script in your Python environment. When you enter a radius, it opens a window displaying the shapes.