2017-09-22 1 views
0

다음과 같은 코드를 사용하여 Ball 클래스의 인스턴스를 2 개 더 만들고 다른 색상과 다른 위치를 만들려고합니다. 현재 타원형을 만들고 그 위치를 지정하는 메서드는 init 메서드에 있습니다.클래스의 메서드를 호출하여 tkinter 파이썬 클래스를 변경하는 가장 좋은 방법

문제점 : ball2 및 ball3 (Ball 클래스의 인스턴스 생성)을 만들려고했지만 작동하지 않았습니다. 분명한 이유로 볼 1을 덮어 씁니다.

I 답변 (코드)와 함께 최고의 솔루션

에 대한 몇 가지 제안이 가장 지금 어디에서 직접 메소드를 호출하는 방법 그렇다면 수 있나요 후 무엇입니까? (나는 여러 가지 일을 시도하지 않았다).

그렇지 않으면 볼을 그리기위한 새로운 방법을 만드는 것이 더 파이썬 적이거나 효율적입니까? 그렇다면 대답으로 제공 할 수 있습니까?

대답은 위의 설명과 설명 또는 다른 대안이있는 것이 이상적입니다.

class Ball: #create a ball class 
    def __init__(self,canvas,color): #initiliased with the variables/attributes self, canvas, and color 
     self.canvas=canvas #set the intiial values for the starting attributes 
     self.id=canvas.create_oval(30,30,50,50,fill=color) #starting default values for the ball 
     """ Note: x and y coordinates for top left corner and x and y coordinates for the bottom right corner, and finally the fill colour for the oval 
     """ 
     self.canvas.move(self.id,0,0) #thia moves the oval to the specified location 

    def draw(self): #we have created the draw method but it doesn't do anything yet. 
     pass 


ball1=Ball(canvas,'green') #here we are creating an object (green ball) of the class Ball 

ball2=Ball(canvas,'blue') 
ball3=Ball(canvas,'purple') 

아래

코드 예를 들어, 시도하고 나는이 시도하는 방법으로 이동,하지만 운 :

def moveball(x_position,y_position): 
     self.canvas.move(self.id,0,0) 


ball3=Ball(canvas,'purple') 
ball3.moveball(100,100) 

오류 :

ball3.moveball(100,100) 
TypeError: moveball() takes 2 positional arguments but 3 were given 
+0

? http://xyproblem.info/을 참조하십시오 –

+0

좀 더 명확하게 문제를 포함하도록 질문을 편집했습니다. balls2와 ball3 (인스턴스)는 ball1을 덮어 씁니다.가장 효율적인 방법으로 그 문제에 대한 해결책을 모색 중입니다 - __init__ 클래스에서 속성을 호출하거나 작동하지 않는 다른 방법을 만드는 시도를 수정하십시오 (편집 참조) – MissComputing

답변

관련 문제