# function_gui.py # # draw the graph of a user supplied function # using Zelle's graphics API # # Jim M, Sep 2013 from graphics import * from math import * def main(): # define a bunch of parameters windowWidth = 400 # in pixels windowHeight = 300 xMin = 0.0 xMax = 10.0 yMin = -1.5 yMax = 1.5 xBorder = 1.0 # in x,y coordinates yBorder = 0.2 nSteps = 200 # set up the window window = GraphWin("Function Plot", windowWidth, windowHeight) window.setCoords(xMin - xBorder, yMin - yBorder, xMax + xBorder, yMax + yBorder) plotRectangle = Rectangle(Point(xMin, yMin), Point(xMax, yMax)) plotRectangle.setOutline("grey") plotRectangle.draw(window) functionEntry = Entry(Point(xMax - 2.0, yMax - 0.2), 12) functionEntry.setText("sin(x)") functionEntry.draw(window) print "Enter a function, then click the mouse." mouse_position = window.getMouse() function = functionEntry.getText() # draw the function # # The basic idea is to draw many tiny line segments, # using a very small change in x. Calculus, basically, without the limit. # # The eval() function can be used to calcuate # the value of function, as long as the variable # names in the string are given values. # dx = (xMax - xMin)/nSteps x = xMin for i in range(nSteps): # draw a line from (x, f(x)) to ((x+dx, f(x+dx)) (x1, y1) = (x, eval(function)) x = x + dx (x2, y2) = (x, eval(function)) Line(Point(x1, y1), Point(x2, y2)).draw(window) # wait for the user to quit user_input = raw_input("Type to quit. ") window.close() main()