好的,所以一旦满足要求,我就尝试删除画布,但出现此错误: 我希望当herox达到700时背景会发生变化,我认为只有删除了旧背景后我才能这样做。
line 56, in <module>
backgroundcanvas.delete(ALL)
AttributeError: 'int' object has no attribute 'delete'
from tkinter import *
from PIL import Image
root = Tk()
root.title("Game")
heroc = None
backgroundcanvas = None
speed = 10
def ChangeMap():
heropos = canvas.coords(heroc)
herox = heropos[0]
heroy = heropos[1]
if herox == 700:
print("requirement met")
backgroundcanvas.delete("all")
backgroundcanvas.create_image(350, 200, image="background2.png")
def Move_hero(event):
global heroc
if event.keysym == "Up":
canvas.move(heroc, 0, -speed)
if event.keysym == 'Down':
canvas.move(heroc, 0, speed)
if event.keysym == 'Right':
ChangeMap()
canvas.move(heroc, speed, 0)
if event.keysym == 'Left':
canvas.move(heroc, -speed, 0)
print(canvas.coords(heroc))
canvas = Canvas(root, bg="black", width=700, height=400)
canvas.pack()
heroc = None
backgroundcanvas = None
background = PhotoImage(file="background.png")
background2 = PhotoImage(file="background2.png")
backgroundcanvas = canvas.create_image(350,200,image=background)
character = PhotoImage(file="hero.png")
heroc = canvas.create_image(30, 260 ,image=character)
canvas.bind_all('<KeyPress-Up>', Move_hero)
canvas.bind_all('<KeyPress-Down>', Move_hero)
canvas.bind_all('<KeyPress-Left>', Move_hero)
canvas.bind_all('<KeyPress-Right>', Move_hero)
root.mainloop()
如果需要图像和代码中的其他内容,我将其添加:)
答案 0 :(得分:0)
该错误告诉您确切的问题是:您试图在整数上调用delete("all")
,就像您进行42.delete("all")
一样,这是相同的错误。
原因是backgroundcanvas
是一个整数(画布ID),而整数没有delete
方法。相反,您需要调用画布的delete
方法。如果要删除所有内容,则将执行canvas.delete("all")
,如果仅要删除背景,则将执行canvas.delete(backgroundcanvas
。
您尝试在create_image
上调用backgroundcanvas
的以下行也是如此。您需要在实际的画布小部件上调用它。