问题描述
我正在尝试制作一个乌龟显示器,以记住我将对象移至何处。为此,我使用了货架模块。有关海龟位置的信息以及turtle.Turtle()
本身都记录在每只海龟的词典中的列表中,如下所示:
Dots = {'A': [turtle,xcor,ycor],'B': [turtle,ycor]}
然后我写
shelfFile = shelve.open('VisualData')
shelfFile['Dots'] = Dots
并运行一次代码。
然后我像Dots = shelfFile['Dots']
那样重写第二行并再次运行它,这将导致错误显示。我还在代码末尾写了shelfFile['Dots'] = Dots
,以便它记录数据中的所有更改。
虽然我知道这很可能是一个非常优雅的解决方案,但是每次使用了货架模块后,我都会使用它,并且它会起作用。我在这里真的很茫然。
解决方法
我猜你想做类似的事情:
from turtle import Turtle
import shelve
yertle = Turtle()
yertle.goto(100,100)
myrtle = Turtle()
myrtle.goto(-200,-200)
dots = {
'A': [yertle,yertle.xcor(),yertle.ycor()],'B': [myrtle,myrtle.xcor(),myrtle.ycor()],}
with shelve.open('VisualData') as shelfFile:
shelfFile['Dots'] = dots
但是当我运行上面的命令时,我得到了错误:
TypeError: cannot pickle '_tkinter.tkapp' object
我发现在其中讨论:
- can't pickle _tkinter.tkapp objects error when trying to create multiple instances of the same class
类似的答案。如果我想给乌龟泡菜,我可能会考虑将pen()
和position()
与heading()
和from turtle import Turtle
import shelve
yertle = Turtle()
yertle.color('green')
yertle.goto(100,100)
myrtle = Turtle()
myrtle.color('red')
myrtle.goto(-200,-200)
myrtle.right(45)
dots = {
'A': [yertle.pen(),yertle.position(),yertle.heading()],'B': [myrtle.pen(),myrtle.position(),myrtle.heading()],}
with shelve.open('VisualData') as shelfFile:
shelfFile['Dots'] = dots
结合使用,它描述了大部分乌龟的精髓,很容易被腌制(如果没有, JSON):
from turtle import Screen,Turtle
import shelve
screen = Screen()
with shelve.open('VisualData') as shelfFile:
dots = shelfFile['Dots']
pen,position,heading = dots['A']
yertle = Turtle()
yertle.pen(pen)
yertle.penup()
yertle.setposition(position)
yertle.setheading(heading)
pen,heading = dots['B']
myrtle = Turtle()
myrtle.pen(pen)
myrtle.penup()
myrtle.setposition(position)
myrtle.setheading(heading)
yertle.pendown()
yertle.circle(100)
myrtle.pendown()
for _ in range(4):
myrtle.forward(100)
myrtle.right(90)
screen.exitonclick()
然后我们可以使用类似的方法恢复乌龟:
MyApplication_1
我们应该从龟被腌制之前的位置开始,以原始颜色等形式获取这些新图纸。