캔버스에서 개체를 삭제하는 방법을 이해하는 데 어려움이 있습니다. 로켓 오브젝트는 Class Rocket
단순한 타원 에서 생성되며 단순한 타원형입니다. 이벤트 후 캔버스에서이 개체를 제거하기 위해 canvas.delete()
인수가 설정된 메서드 를 사용하려고 rocket
하지만 작동하지 않는 것 같습니다.
내 목표는 목록에 여러 개의 로켓을 만들고 애니메이션 중에 일부를 삭제하는 것입니다.
main () 함수 만 포함했습니다. Class Rocket은 캔버스에 타원형을 만들고 잘 작동합니다.
파일 : constants.py
CANVAS_WIDTH = 600 # Width of drawing canvas in pixels
CANVAS_HEIGHT = 600 # Height of drawing canvas in pixels
ROCKET_SIZE = 30
파일 : test.py
import tkinter
import time
import random
from constants import *
from Rocket import Rocket
def main():
canvas = make_canvas(CANVAS_WIDTH, CANVAS_HEIGHT, 'Fireworks')
#put a rocket a bottom of canvas
rocket = Rocket(canvas)
canvas.update()
time.sleep(50/50.) #pause to see the rocket
# some event occurs (not important for this example)
canvas.delete(rocket) #this doesn't make the rocket disappear!
canvas.update()
time.sleep(50/50.)
def make_canvas(width, height, title):
top = tkinter.Tk()
top.minsize(width=width, height=height)
top.title(title)
canvas = tkinter.Canvas(top, width=width + 1, height=height + 1)
canvas.pack()
return canvas
if __name__ == '__main__':
main()
파일 : Rocket.py
import random
from constants import *
class Rocket:
'''
This is the blueprint for a new variable type called "Rocket"
Every rocket has three things: an oval, a change_x and a change_y.
Every rocket supports the "update" method which will move the rocket one step.
'''
def __init__(self, canvas):
# Starting point - screen bottom with slight angle
x_1 = random.randint(CANVAS_WIDTH/2 - 50, CANVAS_WIDTH/2 + 50)
y_1 = CANVAS_HEIGHT - ROCKET_SIZE
x_2 = x_1 + ROCKET_SIZE
y_2 = CANVAS_HEIGHT
self.fill = random.choice(['blue', 'green', 'orange', 'purple', 'red', 'lime'])
self.oval = canvas.create_oval(x_1, y_1, x_2, y_2, fill=self.fill, outline=self.fill)
self.change_x = random.randint(-3, 3)
self.change_y = random.randint(-15, -5)
# again, I pass in canvas.
def update(self, canvas):
# update a single rocket instance (the one given by self)
canvas.move(self.oval, self.change_x, self.change_y)
유용한 피드백과 더 많은 조사를 마친 후 첫 번째 해결책은 다음과 같습니다.
로켓 클래스에 다음을 추가하십시오-
# method to get canvas object id (already assigned to self.oval in constructor)
def get_id(self):
return self.oval
다음 줄을 변경하십시오.
canvas.delete(rocket)
main ()에서 :
canvas.delete(rocket.get_id())
이것은 목록에 생성 된 여러 로켓에도 적용되었습니다.
나는 Class Rocket 내에서 로켓을 삭제하는 방법을 시도하지 않았지만 이것이 가장 우아한 해결책 인 것 같습니다. 어느 쪽이든 오브젝트 ID는 canvas.delete의 필수 인수입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다