본문 바로가기
프로그램

[파이썬] 문제 : tkinter canvas에 사각형 그리고, 상하좌우 이동

by 오디세이99 2023. 5. 12.
728x90
반응형

from tkinter import *            # tkinter 라이브러리에 모든 함수를 사용하겠다.

root = Tk()                       # root라는 창을 생성
root.geometry("600x400")          # 창 크기설정
root.title("yeachan_yeachan")     # 창 제목설정
# root.option_add("*Font","맑은고딕 25") # 폰트설정
# root.resizable(False, False)  # x, y 창 크기 변경 불가

rec_length = 100                  # 사각형 한 변의 길이
win_w = 600                       # 윈도우 크기
win_h = 400
x1 = win_w//2 - (rec_length//2)  # 초기 사각형의 x1 좌표
y1 = win_h//2 - (rec_length//2)  # 초기 사각형의 y1 좌표
x2 = x1 + 100                    # 초기 사각형의 x2 좌표
y2 = y1 + 100                    # 초기 사각형의 y2 좌표
pos = [x1, y1, x2, y2]           # 좌표 리스트타입 변수
def btnMove(cmd):                # 이동 함수
    global pos                   # 글로벌 변수
    # print(pos)
    canvas.delete('all')         # canvas clear
    if cmd == 'L':              # left 면
        pos[0] += -5            # x1, x2 를 -5
        pos[2] += -5
    elif cmd == 'R':            # right 면
        pos[0] += +5   
        pos[2] += +5
    elif cmd == 'U':            # up 이면
        pos[1] += -5
        pos[3] += -5
    elif cmd == 'D':            # down 이면
        pos[1] += +5
        pos[3] += +5
        
    canvas.create_rectangle(pos[0], pos[1], pos[2], pos[3], fill="blue")    # 사각형 그리기
       
    
canvas = Canvas(root, bg="white", height=350, width=600)                    # canvas
canvas.grid(row=1, column=1, columnspan=4)
canvas.create_rectangle(pos[0], pos[1], pos[2], pos[3], fill="blue")

btn1 = Button(root, text="left", width=4, command=lambda : btnMove('L'))
btn1.grid(row=2, column=1)
btn2 = Button(root, text="right", width=4, command=lambda : btnMove('R'))
btn2.grid(row=2, column=2)
btn3 = Button(root, text="up", width=4, command=lambda : btnMove('U'))
btn3.grid(row=2, column=3)
btn4 = Button(root, text="down", width=4, command=lambda : btnMove('D'))
btn4.grid(row=2, column=4)

    
root.mainloop()                  # 창 실행

728x90
반응형

댓글