2012-11-04 3 views
3

왜 애니메이션이 작동하지 않습니까? 프로그램을 실행할 때 모양이 움직이지 않습니다.Python Tkinter 애니메이션

from Tkinter import * 
import time 



class alien(object): 
    def __init__(self): 
     self.root = Tk() 
     self.canvas = Canvas(self.root, width=400, height = 400) 
     self.canvas.pack() 
     alien1 = self.canvas.create_oval(20, 260, 120, 360, outline='white',   fill='blue') 
     alien2 = self.canvas.create_oval(2, 2, 40, 40, outline='white', fill='red') 
     self.canvas.pack() 
     self.root.mainloop() 

    def animation(self): 
     track = 0 
     while True: 
     x = 5 
     y = 0 
     if track == 0: 
      for i in range(0,51): 
       self.time.sleep(0.025) 
       self.canvas.move(alien1, x, y) 
       self.canvas.move(alien2, x, y) 
       self.canvas.update() 
      track = 1 
      print "check" 

     else: 
      for i in range(0,51): 
       self.time.sleep(0.025) 
       self.canvas.move(alien1, -x, y) 
       self.canvas.move(alien2, -x, y) 
       self.canvas.update() 
      track = 0 
     print track 

alien() 
+1

* '??????????????????????????????????? ?????????????????????/'* 정말 도움이되지 않습니다. 기대하지 않거나 효과가없는 것은 어떻게됩니까? 예외가 발생하면 우리에게 전적으로주십시오. –

+4

더 많은 물음표를주십시오 –

+0

x - xis – mvitagames

답변

4

animation 메서드는 절대로 호출하지 않았습니다. 몇 가지 다른 이름 지정 문제가있었습니다.

# Assuming Python 2.x 
# For Python 3.x support change print -> print(..) and Tkinter to tkinter 
from Tkinter import * 
import time 

class alien(object): 
    def __init__(self): 
     self.root = Tk() 
     self.canvas = Canvas(self.root, width=400, height = 400) 
     self.canvas.pack() 
     self.alien1 = self.canvas.create_oval(20, 260, 120, 360, outline='white',   fill='blue') 
     self.alien2 = self.canvas.create_oval(2, 2, 40, 40, outline='white', fill='red') 
     self.canvas.pack() 
     self.root.after(0, self.animation) 
     self.root.mainloop() 

    def animation(self): 
     track = 0 
     while True: 
      x = 5 
      y = 0 
      if track == 0: 
       for i in range(0,51): 
        time.sleep(0.025) 
        self.canvas.move(self.alien1, x, y) 
        self.canvas.move(self.alien2, x, y) 
        self.canvas.update() 
       track = 1 
       print "check" 

      else: 
       for i in range(0,51): 
        time.sleep(0.025) 
        self.canvas.move(self.alien1, -x, y) 
        self.canvas.move(self.alien2, -x, y) 
        self.canvas.update() 
       track = 0 
      print track 

alien() 
+0

와우는 그 실수를 포착하지 않았으므로 좋은 프로그래머가되는 방법에 대한 팁을 줄 수 있습니까? 어떤 취미 나 웹 사이트를 개선하는데 도움이 될만한 웹 사이트 나 책은 매우 흥미 롭습니다 .... 그리고 대단히 감사합니다 !!! – mvitagames

+0

가능한 한 연습하고 작은 세부 사항에주의하십시오. 이 경우 프로그램을 실행할 때 오류 메시지를 읽으면 모든 이름 지정 문제가 확인됩니다. – Tim

+2

퍼팅을 코드에 사용하는 것은 좋지 않습니다. 짧지 만 잠자기 할 때마다 전체 GUI가 응답하지 않습니다. –

12

귀하의 animation 방법은 휴식 결코 그것의 while True 루프를 가지고있다. 이것은 GUI 프로그램에서 no-no입니다. 반환하지 않기 때문에 GUI의 이벤트 루프가 이벤트를 처리하지 못하기 때문입니다. 예를 들어, 메뉴가있는 경우 사용자는 메뉴 항목을 선택할 수 없습니다. GUI는 animation 메소드에서 구현 한 모든 조치를 제외하고 고정 된 것처럼 보입니다.

@ Tim의 코드를 약간 수정하여 while 루프를 제거하고 돌아 가기 전에 외계인을 한 단계 만 이동하면이 문제가 해결됩니다. self.master.afteranimation 메서드의 끝에 호출되어 잠시 멈춘 후 이벤트 루프에서 애니메이션을 다시 호출합니다.


import tkinter as tk 
import time 

class Alien(object): 
    def __init__(self, canvas, *args, **kwargs): 
     self.canvas = canvas 
     self.id = canvas.create_oval(*args, **kwargs) 
     self.vx = 5 
     self.vy = 0 

    def move(self): 
     x1, y1, x2, y2 = self.canvas.bbox(self.id) 
     if x2 > 400: 
      self.vx = -5 
     if x1 < 0: 
      self.vx = 5 
     self.canvas.move(self.id, self.vx, self.vy) 

class App(object): 
    def __init__(self, master, **kwargs): 
     self.master = master 
     self.canvas = tk.Canvas(self.master, width=400, height=400) 
     self.canvas.pack() 
     self.aliens = [ 
      Alien(self.canvas, 20, 260, 120, 360, 
        outline='white', fill='blue'), 
      Alien(self.canvas, 2, 2, 40, 40, outline='white', fill='red'), 
     ] 
     self.canvas.pack() 
     self.master.after(0, self.animation) 

    def animation(self): 
     for alien in self.aliens: 
      alien.move() 
     self.master.after(12, self.animation) 

root = tk.Tk() 
app = App(root) 
root.mainloop() 
+0

oic이지만 Tkinter 가져 오기 * 과 Tkinter를 tk로 가져 오는 것의 차이점은 무엇입니까 ?? – mvitagames

+0

'from Tkinter import *'는'Tkinter' 모듈을 가져오고'public '전역을'Tkinter' 모듈에서 현재 모듈의 네임 스페이스로 추가합니다. 'import Tkinter as tk'는'Tkinter' 모듈을 가져오고'tk'에 의해 참조되는 모듈 객체 자체를 현재 모듈의 네임 스페이스에 추가합니다. 'modulename import * '를 결코 사용하지 않습니다. 왜냐하면 변수가 어디서 왔는지 추적하기가 어렵 기 때문입니다. "이 FAQ"(http://docs.python.org/3/faq/programming.html#what-are-the-best-practices-for-using-import-in-a-module)에서 " 모범 사례 "를 사용하여 모듈에서 가져 오기를 사용합니다. – unutbu

+0

@unutbu 우리가 애니메이션과 함께 좀 더 복잡한 GUI를 사용하려면 애니메이션을 "애니메이션"메소드에 넣고 이벤트 관리와 같은 기능을 가진 GUI 자체를 _____init_____ 함수에 넣거나 호출해야합니다. self.master.after. 난 괜찮아 ? 또는 그것은 전에 있어야합니까? – Yann

1

여기에 루프를 사용하여 수행하는 방법 :

from tkinter import * # version 3.x 

tk = Tk() 

frame = Frame(tk) 
canvas = Canvas(frame) # use canvas 

frame.pack(fill = BOTH, expand = 1) 
canvas.pack(fill = BOTH, expand = 1) 

ball = canvas.create_oval(10, 10, 30, 30, tags = 'ball') # create object to animate 

def animation(x_move, y_move): 
    canvas.move(ball, x_move, y_move) # movement 
    canvas.update() 
    canvas.after(20) # milliseconds in wait time, this is 50 fps 

    tk.after_idle(animation, x_move, y_move) # loop variables and animation, these are updatable variables 

animation(2, 2) # run animation 

갱신 가능한 변수를 업데이트하고 다시 업데이트 할 수 있습니다 때 동일하게 유지 변수입니다.

+0

'canvas.update()'와'canvas.after_idle (...)'을 제거하고 대신에'canvas.after (20, animation, x_move, y_move) '. 또한 마지막 줄 다음에'tk.mainloop()'를 추가하십시오. – user136036