【问题标题】:Inserting text inside a circle in Python在 Python 中的圆圈内插入文本
【发布时间】:2017-04-16 22:35:53
【问题描述】:

我正在尝试编写用于绘制 DFA 的 Python 代码。我打算使用海龟库。有替代品吗?我可以绘制节点,但不确定如何在圆圈内插入状态名称。 谁能指导我?以下是我到目前为止的代码。 谢谢!

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()

【问题讨论】:

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


    【解决方案1】:

    您的代码的问题似乎是缺乏对海龟库的熟悉和一般的 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()
    

    输出

    【讨论】:

    • 是的,你说的对,我是 python 新手。非常感谢您的代码;请问乌龟不是最好的选择,有什么替代品?
    • @Chica_Programmador,一种替代方法是使用构建turtle 模块的tkinter 模块。它比 turtle 更复杂,但就像 turtle 一样,您可以构建一组与您的问题域相关的函数,然后在您的代码中使用这些函数。
    【解决方案2】:

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

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

    另一方面,函数 draw_nodemyTurtle 作为输入参数被正确调用,但实际上 draw_node。

    尝试改变它:

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 2015-07-04
      • 1970-01-01
      相关资源
      最近更新 更多