在这里填写新手。我可以知道为什么在运行此代码时收到错误消息(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()
答案 0 :(得分:0)
我收到错误消息(NameError:未定义名称“ width”) 运行此代码
运行此代码时,出现错误:
_tkinter.TclError:错误的事件类型或键盘符号“正确”
这段代码很乱,特别是:
它通过以不受控制的方式组合乌龟和tkinter来放置两个窗口。当turtle独立时,我们使用Turtle
和Screen
,但是当嵌入tkinter时,我们使用RawTurtle
和TurtleScreen
。与其让第二个窗口成为忽略规则的副作用,不如让您真正控制该窗口的创建。
此代码似乎是将根窗口的标题设置为将None
作为XView
参数传递给Text()
的副作用:
T =文本(root,root.title(“控件”),高度= 8,宽度= 60)
您为箭头使用了错误的键名-对于乌龟的'Left'
函数,它们应为'Right
和onkey()
',而不是'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()