NameError“画布”未定义?

时间:2018-11-05 20:29:21

标签: python python-3.x tkinter tkinter-canvas

所以我一直在研究使球弹跳起来的东西,但是当涉及到使用画布时,它给了我一个NameError,它说“ name'canvas”未定义。这是代码

from tkinter import *
from tkinter import PhotoImage

window = Tk()

tile_x_count = 4
tile_y_count = 4

#GetBGRND Image
background_image = PhotoImage(file = "C:/Users/david/Desktop/Bgrnd.png")
box_left = 0
box_top = 0
box_right = tile_x_count*background_image.width()
box_bottom = tile_y_count*background_image.height()

#Get sprite image
sprite_image = PhotoImage(file= "C:/Users/david/Desktop/Pelota.png")

sprite_half_width = sprite_image.width()/2
sprite_half_height = sprite_image.height()/2

#the numbers below are floating point to enable
sprite_x = 2.0*sprite_half_width
sprite_y = 2.0*sprite_half_height
vx=2.0
vy=3.0


#create canvas, background and sprite objects.
canvas = canvas(window, width = box_right, height = box_bottom, bg='black')
for i in range (tile_x_count):
    for j in range(tile_y_count):
        background = canvas.create_image(i*background_image.width(), j*background_image.height(), image = background_image, anchor = 'nw')

#the numbers below are integers and represent
sprite_image_x = int(sprite_x)
sprite_image_y = int(sprite_y)

sprite = canvas.create_image(sprite_image_x, sprite_image_y)
canvas.pack()

def on_up_arrow(event):
    global vy 
    vy -=5.0

def on_down_arrow(event):
    global vy
    vy +=5.0

def on_left_arrow(event):
    global vx
    vy -=5.0

def on_right_arrow(event):
    global vx
    vx += 5.0

window.title('Sprite Animation')
window.bind('<up>', on_up_arrow)
window.bind('<down>', on_down_arrow)
window.bind('<left>', on_left_arrow)
window.bind('<right>', on_right_arrow)
window.focus()

#animation loop
g = 9.8 #gravity
f = 0.9 #friction loss 

while true:
    sprite_x += vx
    sprite_y += vy + 0.5*g
    vy +=g

    move_x = int(sprite_x) - sprite_image_x
    move_y = int(sprite_y) - sprite_image_y
    canvas.move(sprite,move_x,move_y)

    sprite_image_x += move_x
    sprite_image_y += move_y
    canvas.after(10)
    canvas.update()


    if sprite_x+sprite_half_width >= box_right and vx > 0.0: 
        vx =-vx*f
        sprite_x = box_right - sprite_half_width
    elif sprite_x-sprite_half_width <= box_left and vx < 0.0:
        vx = -vx*f
        sprite_x = box_left +sprite_half_width
    elif sprite_y+sprite_half_height >= box_bottom and vy > 0.0:
        vy = -vy*f
        sprite_y = box_bottom - sprite_half_height
    elif sprite_y-sprite_half_height <= box_top and vy < 0.0:
        vy = -vy*f
        sprite_y = box_top + sprite_half_height


window.mainloop()

那么我能做些什么来解决它?还有其他我应该改变的事情吗?对于其他画布操作,我没有收到任何警告。

1 个答案:

答案 0 :(得分:1)

使用Canvas代替canvas,如下所示:

canvas = Canvas(...)