Python homework

profilesana@24
PiSimulation.pyw

# Description: This program demonstrates a simulation of the Pi calculation # Programmer: SANA # Import required modules import tkinter import math import random import turtle # Define a function to run the simulation def showMontePi(numDarts): drawingT.clear() drawingT.reset() screen.setworldcoordinates(-2, -2, 2, 2) drawingT.up() drawingT.goto(-1, 0) drawingT.down() drawingT.goto(1, 0) drawingT.up() drawingT.goto(0, 1) drawingT.down() drawingT.goto(0, -1) drawingT.goto(0, 0) circle = 0 drawingT.up() for i in range(numDarts): x = random.random() y = random.random() d = math.sqrt(x**2 + y**2) drawingT.goto(x, y) if d <= 1: circle = circle + 1 drawingT.color('blue') else: drawingT.color('red') drawingT.dot() pi = circle/numDarts * 4 lbl3.configure(text=str.format('{0:.4f}', pi)) # Define what happens when the btn button is clicked def callback(number): try: max_counter = int(number) lbl1.configure(text='') lbl3.configure(text='') except ValueError: lbl1.configure(text='You entered an invalid value. \ You must enter an integer.') else: showMontePi(max_counter) # Define what happens when the btn1 button is clicked def exit(): window.destroy() # Create a window using tkinter and set its properties window = tkinter.Tk() window.title('Pi Simulator') window.geometry('400x600') # Create a label and add it to the window lbl = tkinter.Label(window, text='Enter the number of values to be plotted:') lbl.pack(padx=5, pady=5) # Create a text entry field and add it to the window ent = tkinter.Entry(window) ent.pack(padx=5, pady=5) # Make an Enter button, enable it, and add it to the window btn = tkinter.Button(window, text='Go!', padx=10, pady=2, command=lambda: callback(ent.get())) btn.pack(padx=5, pady=5) # Create a label for displaying any error messages lbl1 = tkinter.Label(window, text=' ') lbl1.pack(padx=5, pady=5) # Create a canvas for drawing on cv = tkinter.Canvas(window, width=300, height=300) cv.pack(padx=5, pady=5) cv.config(highlightbackground='green') # Create a turtle to draw on the canvas and orient it drawingT = turtle.RawTurtle(cv) screen = drawingT.getscreen() screen.setworldcoordinates(0, 0, 250, 250) screen.bgcolor('white') # Create a label to describe the results lbl2 = tkinter.Label(window, text='The simulated value for pi is: ') lbl2.pack(padx=5, pady=5) # Create a label for displaying the results and add it to the window lbl3 = tkinter.Label(window, text=' ', padx=40, pady=3) lbl3.pack(padx=5, pady=5) # Exit btn1 = tkinter.Button(window, text='Exit', command=exit) btn1.pack() # Draw the window and start the program window.mainloop()