Tkinter는 GUI 기반 응용 프로그램을 만드는 데 사용되는 표준 Python 라이브러리입니다. 간단한 움직이는 공 응용 프로그램을 만들기 위해 사용자가 이미지를 추가하고, 모양을 그리며, 개체에 애니메이션을 적용할 수 있는 Canvas 위젯을 사용할 수 있습니다. 응용 프로그램에는 다음 구성 요소가 있습니다.
-
창에 타원이나 공을 그리는 캔버스 위젯.
-
공을 움직이려면 move_ball() 함수를 정의해야 합니다. . 함수에서 공이 캔버스 벽에 부딪힐 때 지속적으로 업데이트될 공의 위치를 정의해야 합니다(왼쪽, 오른쪽, 위, 아래).
-
공 위치를 업데이트하려면 canvas.after(duration, function())를 사용해야 합니다. 일정 시간이 지나면 공의 위치가 변경되는 것을 반사합니다.
-
마지막으로 코드를 실행하여 애플리케이션을 실행합니다.
예시
# Import the required libraries
from tkinter import *
# Create an instance of tkinter frame or window
win=Tk()
# Set the size of the window
win.geometry("700x350")
# Make the window size fixed
win.resizable(False,False)
# Create a canvas widget
canvas=Canvas(win, width=700, height=350)
canvas.pack()
# Create an oval or ball in the canvas widget
ball=canvas.create_oval(10,10,50,50, fill="green3")
# Move the ball
xspeed=yspeed=3
def move_ball():
global xspeed, yspeed
canvas.move(ball, xspeed, yspeed)
(leftpos, toppos, rightpos, bottompos)=canvas.coords(ball)
if leftpos <=0 or rightpos>=700:
xspeed=-xspeed
if toppos <=0 or bottompos >=350:
yspeed=-yspeed
canvas.after(30,move_ball)
canvas.after(30, move_ball)
win.mainloop() 출력
위의 코드를 실행하면 캔버스에 움직일 수 있는 공이 있는 응용 프로그램 창이 표시됩니다.
