我是Python新手。我在我的樹莓派上使用IDLE(使用python 2.7)。我一直無法編譯我的教程中最新的程序,一個貓捉老鼠遊戲。我得到以下錯誤:Python屬性錯誤onkeypress
Traceback (most recent call last) :
File "/home/pi/pyth-prog/Python_Cat_and-mouse.py", line 47, in <module> window.onkeypress(up, "Up")
AttributeError: '__Screen' object has no attribute 'onkeypress'
我的代碼如下所示:
import turtle
import time
boxsize =200
caught= False
score= 0
#function that are called keypresses
def up():
mouse.forward(10)
checkbound()
def left():
mouse.left(45)
def right():
mouse.right(45)
def back():
mouse.back(10)
def quitTurtles():
window.bye()
#stop the ;ouse fro; leaving the square set by box sizes
def checkbound():
global boxsize
if mouse.xcor() > boxsize:
mouse.goto(boxsize, mouse.ycor())
if mouse.xcor() < -boxsize:
mouse.goto(-boxsize, mouse.ycor())
if mouse.ycor() > boxsize:
mouse.goto(mouse.xcor(), boxsize)
if mouse.ycor < -boxsize:
mouse.goto(mouse.xcor(), -boxsize)
#Set up screen
window=turtle.Screen()
mouse=turtle.Turtle()
cat=turtle.Turtle()
mouse.penup()
mouse.penup()
mouse.goto(100, 100)
#add key listeners
window.onkeypress(up, "Up")
window.onkeypress(left, "Left")
window.onkeypress(right, "Right")
window.onkeypress(back, "Down")
window.onkeypress(quitTurtles, "Escape")
difficulty=window.numinput("Difficulty", "Enter a difficulty from easy (1), for hard (5) ", minval=1, maxval=5)
window.listen()
#main loop
#note how it changes with difficulty
while not caught:
cat.setheading(cat.towards(mouse))
cat.forward(8+difficulty)
score=score+1
if cat.distance(mouse) < 5:
caught=True
time.sleep(0.2-(0.01*difficulty))
window.textinput("GAME OVER", "Well done. You scored:"+ str(score*difficulty))
window.bye()
如果你想幫助你的代碼排除故障的問題被執行,則需要提供更多的信息。請參閱[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。 – glibdud
它看起來像'window'不是你想象的那樣,但是看不到你的代碼是不可能的。 – zondo
雖然現在已經包含了代碼是很好的,但這需要很多代碼(請參閱我給出的鏈接的「最小」部分)。如果你幫助別人幫助你,你將有更好的機會獲得幫助。 – glibdud