티스토리 뷰

 

1. 마우스 버튼 클릭 이벤트: 난이도 下

화면에 사각형을 그리고 마우스 왼쪽 버튼을 누르면 사각형의 크기를 증가시킨다. 마우스 오른쪽 버튼을 누르면 사각형이 작아지도록 하는 프로그램을 작성해보자.

 


from tkinter import *

#기본 선언
window= Tk()
w=Canvas(window, width=400, height=300)
w.pack()

#기본 사각형 그리기
x=200
y=200
square= w.create_rectangle(75,75,x,y)

#마우스 왼쪽 버튼 클릭시 사각형 크기 증가
def bigger(event):
    global x,y,w,square
    x+=25
    y+=25
    w.coords(square,75,75,x,y)
    
#마우스 오른쪽 버튼 클릭시 사각형 크기 감소
def smaller(event):
    global x,y,w,square
    x-=25
    y-=25
    w.coords(square,75,75,x,y)

#마우스 버튼에 각 이벤트 메서드 Bind 
w.bind("<Button-1>",bigger)
w.bind("<Button-3>",smaller)

window.mainloop()

 


 

2. GUI 버튼 클릭 이벤트: 난이도 中

화면의 하단에 버튼을 4개 배치하고 이 버튼을 누르면 화면의 사각형이 상하좌우로 움직이는 애플리케이션을 작성해보자

 


from tkinter import *

#기본 선언
window = Tk()
canvas= Canvas(window, width=600, height=400)

#그리드 배치 관리자를 사용하여 캔버스의 columnspan 속성을 4로 설정한다.
canvas.grid(row=0, column=0, columnspan=4)
square = canvas.create_rectangle(240,140,350,250, fill="red")

#이벤트 메서드
def up():
    canvas.move(square,0,-20)
    
def down():
    canvas.move(square,0,+20)
      
def right():
    canvas.move(square,+20,0)
    
def left():
    canvas.move(square,-20,0) 
    
#버튼 생성 후, 그리드 맨 아래에 배치한다. 
b1=Button(window, text= "<-(left)", command=left).grid(row=1, column=0)
b2=Button(window, text= "->(Right))", command=right).grid(row=1, column=1)
b3=Button(window, text= "^(Up)", command=up).grid(row=1, column=2)
b4=Button(window, text= "v(Down)", command=down).grid(row=1, column=3)

window.mainloop()

 


 

 

3. 랜덤한 크기 사각형 생성 이벤트: 난이도 中上

윈도우 하나 만들고 여기에 랜덤한 크기의 사각형을 여러 개 그려보자. 위치도 랜덤이어야 하고 크기, 색상도 랜덤으로 하여 본다.

 


from tkinter import *
import random
import time 

#기본 선언
window = Tk()
canvas = Canvas(window, width = 600, height= 400)
canvas.pack()
colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]

#랜덤 위치에 랜덤 크기 랜덤 컬러의 사각형을 생성하는 무한루프
while True:
    fill_color = random.choice(colors)
    
    #캔버스 크기에 맞추어 랜덤 좌표에 사각형 생성
    canvas.create_rectangle(random.randint(0, 600),random.randint(0,400),random.randint(x1, 600),random.randint(y1,400),fil=fill_color)
    
    #사각형 생성 속도를 늦추기 위해 sleep 호출
    time.sleep(0.05)
    window.update()
    
window.mainloop()
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
TAG
more
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함