Python KeyError,但没有dict

时间:2017-02-09 18:39:19

标签: python python-3.x turtle-graphics

我一直在尝试运行我的程序,但每次我都这样做,我得到了这个:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\GURNHH\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1550, in __call__
    return self.func(*args)
  File "C:\Users\GURNHH\AppData\Local\Programs\Python\Python35-32\lib\turtle.py", line 686, in eventfun
    fun()
  File "C:/Users/GURNHH/OneDrive - Rugby School/ICT/Python/bored.py", line 22, in k1
    badpos.remove((int(turtle.xcor()), int(turtle.ycor())))
KeyError: (0, 0)

在这种情况下,我不知道关键错误意味着什么,因为与许多其他人不同,我没有使用过dict。 我的程序应该让乌龟在50次移动后返回中心,但不会在设置的badpos中计数0,0。我的节目是:

from turtle import Turtle, Screen
    from math import *
    from random import *

    random = 0

    """def add():
        random = random + 1
    def check():
        if random > 4:
            random = 0"""

    def k1():
        global random
        turtle.forward(10)
        random = random + 1

        if random > 5:
            turtle.goto(0,0)
            badpos.remove((int(turtle.xcor()), int(turtle.ycor())))


        position = (int(turtle.xcor()), int(turtle.ycor()))

        if position in badpos:
            turtle.color("red")
            screen.bye()


    def k2():
        turtle.left(90)

    def k3():
        turtle.right(90)

    turtle = Turtle(shape="turtle")

    badpos = set()

    screen = Screen()
    screen.setup(1200, 700)
    screen.title("Turtle-Snaky Thing")

    screen.onkey(k1, "Up")
    screen.onkey(k2, "Left")
    screen.onkey(k3, "Right")

    screen.listen()

    screen.mainloop()

1 个答案:

答案 0 :(得分:0)

我对如何使用一段代码并完全搞砸了我印象深刻。这是我原始示例的返工,添加了50个移动约束:

def add_fav(request,pk):
    post = get_object_or_404(Post, pk=pk)
    form = PostForm(instance=post)
    post = form.save(commit=False)
    if not request.user.profile:
        request.user.profile = Profile.objects.create()
    userprofile=request.user.profile
    with userprofile.favorites.all as favorite_posts:
        for post in post_list:
            if post not in favorite_posts:
                userprofile.favorites.add(post)
    userprofile.save() 
    return redirect('post_list')

我对你的例子批发并没有接受我之前的答案给你留下了深刻的印象。这种新的变化使用起来比较棘手,因为只有很多次你可以从家里重新开始90度角,而不是踩到前一行,即使排除了原点:

enter image description here

也许转60或30度可能会让你有更多的机动性离家出走。

PS。你没有在这个程序中使用from turtle import Turtle, Screen def k1(): global move_count turtle.forward(10) move_count += 1 if move_count % 50 == 0: turtle.home() position = (int(turtle.xcor()), int(turtle.ycor())) if position != (0, 0) and position in badpos: turtle.color("red") screen.bye() badpos.add(position) def k2(): turtle.left(90) def k3(): turtle.right(90) turtle = Turtle(shape="turtle") move_count = 0 badpos = set() screen = Screen() screen.setup(1200, 700) screen.title("Turtle-Snakey Thing") screen.onkey(k1, "Up") screen.onkey(k2, "Left") screen.onkey(k3, "Right") screen.listen() screen.mainloop() 。这是一个dict()

相关问题