Question

Write a program that asks the user for a rating from 1-10.
Follow these guidelines:

If the user rates between a 1 and 4, draw a red X in the middle of the canvas.
If they rate between 5 and 7, draw a yellow horizontal line in the middle of the canvas.
If they rate an 8 or above, draw a green checkmark in the middle of the canvas.
Use the variable rating to save the user input value.
Hint: Write functions to draw each mark type and then use these functions in an if-elif-else statement.

Answers

GPT-4o mini
Sure! Below is a Python program using the `tkinter` library, which provides a simple way to create a graphical user interface (GUI). The program will ask the user for a rating, and based on the rating, it will draw an appropriate mark on a canvas.

Make sure you have Python installed on your system, and run the following code:

```python
import tkinter as tk

def draw_red_x(canvas):
canvas.create_line(50, 50, 150, 150, fill='red', width=5)
canvas.create_line(150, 50, 50, 150, fill='red', width=5)

def draw_yellow_line(canvas):
canvas.create_line(50, 100, 150, 100, fill='yellow', width=5)

def draw_green_checkmark(canvas):
canvas.create_line(50, 100, 100, 150, fill='green', width=5)
canvas.create_line(100, 150, 150, 50, fill='green', width=5)

def submit_rating():
rating = entry.get()
try:
rating = int(rating)
if 1 <= rating <= 4:
draw_red_x(canvas)
elif 5 <= rating <= 7:
draw_yellow_line(canvas)
elif 8 <= rating <= 10:
draw_green_checkmark(canvas)
else:
print("Please enter a rating between 1 and 10.")
except ValueError:
print("Please enter a valid integer rating.")

# Create the main window
window = tk.Tk()
window.title("Rating System")

# Create a canvas to draw on
canvas = tk.Canvas(window, width=200, height=200)
canvas.pack()

# Entry for rating input
entry = tk.Entry(window)
entry.pack()

# Submit button
submit_button = tk.Button(window, text="Submit Rating", command=submit_rating)
submit_button.pack()

# Run the application
window.mainloop()
```

### Explanation of the Code:

- **Import the Tkinter library**: This is needed to create the window, canvas, and other GUI elements.
- **Define drawing functions**: Three functions are created to draw a red X, a yellow line, and a green checkmark respectively on the canvas based on the user's rating.
- **Submit Rating Function**: Reads user input, checks if it's a valid integer, and calls the appropriate drawing function based on the rating range.
- **Main GUI setup**: A window, canvas, entry box, and button are created to take user input and submit it for evaluation.

### Running the Program:

1. Copy the code into a `.py` file (for example, `rating_program.py`).
2. Run the program with a Python interpreter.
3. Enter a rating from 1 to 10 in the entry box and click the "Submit Rating" button.
4. Observe the drawing on the canvas which corresponds to your rating.

Related Questions