Inserting text inside a circle in Python

时间:2016-12-02 04:54:39

标签: python graphics turtle-graphics finite-automata state-machine

I am trying to write Python code for drawing a DFA. I am planning to use the turtle library. Are there any alternates? I can draw the nodes but am unsure about how to insert the state names inside the circles. Can anyone please guide me? Below is my code so far. Thanks!

import turtle

def draw_node(some_turtle):
    myTurtle.circle(50)
    turtle.getscreen().__root.mainloop()


def draw_design():

    window = turtle.Screen()
    window.bgcolor("teal")

    myTurtle = turtle.Turtle()
    myTurtle.color("white")
    myTurtle.shape("turtle")
    myTurtle.speed(5)
    myTurtle.pensize(4)

    draw_node(myTurtle)

    window.exitonclick()

draw_design()

2 个答案:

答案 0 :(得分:0)

我无法在我的环境中安装 turtle 模块,但我认为该问题在可变范围内。

myTurtle 变量未在全局范围内定义,因此 draw_node 中的 myTurtle myTurtle 不同<强> draw_design

另一方面,使用 myTurtle 作为输入参数正确调用函数 draw_node ,但实际上 draw_node <内部没有使用该输入/ strong>即可。

尝试改变:

def draw_node(some_turtle):
    myTurtle.circle(50)
    turtle.getscreen().__root.mainloop()

到那个:

def draw_node(some_turtle):
    some_turtle.circle(50)
    turtle.getscreen().__root.mainloop()

答案 1 :(得分:0)

您的代码的问题似乎是缺乏对特定的乌龟库以及一般的Python编程的熟悉程度。我不一定会说乌龟图书馆是你想要做的最好的选择,但它可以做你的计划所希望实现的目标:

from turtle import Turtle, Screen

RADIUS = 50

FONT_SIZE = 18

FONT = ("Arial", FONT_SIZE, "normal")

def draw_node(turtle, text, x, y):
    turtle.up()
    turtle.goto(x, y - RADIUS)
    turtle.down()
    turtle.circle(RADIUS)
    turtle.up()
    turtle.goto(x, y - FONT_SIZE // 2)
    turtle.write(text, align="center", font=FONT)

def draw_design(turtle):

    turtle.color("white")
    turtle.pensize(4)

    draw_node(turtle, "S0", -100, 100)

    draw_node(turtle, "S1", 100, 100)

screen = Screen()
screen.bgcolor("blue")

yertle = Turtle(shape="turtle")

draw_design(yertle)

yertle.home()

screen.exitonclick()

<强>输出

enter image description here