海龟属性未定义

Turtle attribute not defined

这里完全是新手。当我 运行 这段代码时,我能知道为什么我收到错误消息(NameError:名称 'width' 未定义)吗?谢谢:)

from tkinter import *
from turtle import *

root = Tk()
T = Text(root, root.title("Controls"), height=8, width=60)
T.pack()
T.insert(END, """Right arrow key = move forward\nLeft arrow key = move 
backward\nr = turn right\nl = turn left\n
u = pen up\nd = pen down\nh = go home\nc = clear""")


def main():
    width(2)
    speed(0)
    pencolor("blue")
    onkey(up, "u")
    onkey(down, "d")
    onkey(clear, "c")
    onkey(home, "h")
    onkey(lambda: forward(5), "right")
    onkey(lambda: back(5), "left")
    onkey(lambda: left(5), "l")
    onkey(lambda: right(5), "r")
    listen()
    return "Done!"


if __name__ == "__main__":
msg = main()
print(msg)
mainloop()

I got error message (NameError: name 'width' is not defined) when I run this code

当我运行这段代码时,我得到了错误:

_tkinter.TclError: bad event type or keysym "right"

这段代码乱七八糟,具体来说:

  • 它通过以不受控制的方式组合 turtle 和 tkinter 提出了两个 windows。当 turtle 独立时,我们使用 TurtleScreen,但是当嵌入到 tkinter 中时,我们使用 RawTurtleTurtleScreen。与其让第二个 window 作为忽略规则的副作用出现,你真的应该控制 window.

  • 的创建
  • 此代码似乎将根 window 的标题设置为将 None 作为 XView 参数传递给 Text() 的副作用:

    T = Text(root, root.title("Controls"), height=8, width=60)

  • 您为箭头使用了错误的键名——对于 turtle 的 onkey() 函数,它们应该是 'Left''Right',而不是 'left''right'.

以下是我对如何构建此类程序的理解:

import tkinter as tk
from turtle import RawTurtle, ScrolledCanvas, TurtleScreen

root = tk.Tk()

instructions = tk.Toplevel()
instructions.title("Controls")

text = tk.Text(instructions, height=8, width=60)
text.pack()
text.insert(tk.END, """Right arrow key = move forward\nLeft arrow key = move
backward\nr = turn right\nl = turn left\n
u = pen up\nd = pen down\nh = go home\nc = clear""")

canvas = ScrolledCanvas(root, width=500, height=500)
canvas.pack()

screen = TurtleScreen(canvas)

turtle = RawTurtle(screen, 'turtle')
turtle.pencolor('blue')
turtle.width(2)

screen.onkey(turtle.penup, "u")
screen.onkey(turtle.pendown, "d")
screen.onkey(turtle.clear, "c")
screen.onkey(turtle.home, "h")

screen.onkey(lambda: turtle.forward(5), "Right")
screen.onkey(lambda: turtle.backward(5), "Left")
screen.onkey(lambda: turtle.left(5), "l")
screen.onkey(lambda: turtle.right(5), "r")

screen.listen()

screen.mainloop()