|  | 
 
 发表于 2023-12-30 21:23:09
|
显示全部楼层
   本楼为最佳答案 
| 复制代码import turtle
import math
def plot_function(func_expr, screen_width=800, screen_height=800):
    # 设置屏幕组态
    graph = turtle.Screen()
    graph.title(func_expr)
    graph.setup(width=screen_width, height=screen_height)
    # 创建一个函数图像的乌龟
    plot_t = turtle.Turtle(visible=False)
    plot_t.speed(0)
    plot_t.penup()
    plot_t.color("blue")
    # 创建一个坐标轴的乌龟
    axis_t = turtle.Turtle(visible=False)
    axis_t.speed(0)
    axis_t.color("black")
    # 定义xy坐标画图范围
    x = range(-int(screen_width / 2), int(screen_height / 2))
    y = [eval(func_expr.replace('x', str(i / 100))) for i in x]
    # 画x轴
    axis_t.penup()
    axis_t.goto(-screen_width / 2, 0)
    axis_t.pendown()
    axis_t.forward(screen_width)
    # 画y轴
    axis_t.penup()
    axis_t.goto(0, -screen_height / 2)
    axis_t.pendown()
    axis_t.left(90)
    axis_t.forward(screen_height)
    # 画x轴刻度线
    for i in range(-int(screen_width / 2), int(screen_width / 2), 100):
        axis_t.penup()
        axis_t.goto(i, -10)
        axis_t.pendown()
        axis_t.forward(0)
        axis_t.backward(20)
    # 画y轴刻度线
    axis_t.right(90)
    for i in range(-int(screen_height / 2), int(screen_height / 2), 100):
        axis_t.penup()
        axis_t.goto(-10, i)
        axis_t.pendown()
        axis_t.forward(20)
        axis_t.backward(20)
    # 将乌龟移动到第一个位置,开始绘图
    plot_t.penup()
    plot_t.goto(x[0], y[0] * 100)
    plot_t.pendown()
    # 遍历x轴的位置,绘制y轴上的点
    for (i, j) in zip(x, y):
        plot_t.goto(i, j * 100)
    # 使得窗口等待被关闭
    turtle.done()
if __name__ == '__main__':
    func_expr = input("请输入函数表达式(变量为x):")
    plot_function(func_expr)
 使用方法:
 
 
 
 
 
   
 求最佳答案
   | 
 |