2018년 5월 23일 수요일

[python] 문법10

--------------------------------------------------------------------------------
#
# 이벤트처리
#
--------------------------------------------------------------------------------
# 화면에 마우스클릭 위치까지 선그리기

import turtle

t = turtle.Turtle()

def drawit(x, y):
#t.penup()
t.goto(x, y)
t.write("click")

s = turtle.Screen()
s.onscreenclick(drawit) #onscreenclick( ) 여기 괄호 안에 들어가는 함수는 변수 2개를 갖도록 되어 있다.

turtle.done()

# 윈도우프로그래밍 = 이벤트처리 프로그래밍
# "스크린 윈도우"에서 "클릭" 이벤트에 대해 클릭위치에 click 출력하는 "처리"를 한 예제
# 터틀에서 하는 방법일 뿐.
# 보다 범용적인 방법 필요: Tk, Qt

--------------------------------------------------------------------------------
# 사건기반(event-driven) 프로그래밍 (~ 윈도우프로그래밍)
# 대표적인 사건: 마우스클릭, 키보드입력 ...
# 사건이 발생되는 토대: 윈도우

[윈도우에서 사건기반 프로그래밍]
- with Turtle in Python
- Win32 API in C
- MFC in C++
- C#, VB
- Java
- Qt in C++

[코딩요소]
- 윈도우생성
- 이벤트처리
- 메세지처리 반복(루프)

[기타]
- 부모윈도우 - 자식윈도우 관계 설정
--------------------------------------------------------------------------------
from tkinter import *

window = Tk()
button = Button(window, text="클릭")
button.pack() # 일단 그냥 하는 걸로

window.mainloop()

----------------------------------------
이벤트 처리 1:
- command; 버튼 클릭할 때 발생; 메뉴 아이템 클릭
----------------------------------------
from tkinter import *

def process():
print("안녕하세요?")

window = Tk()

button = Button(window, text="눌러봐", command=process)
#  버튼에서, command (클릭) 이벤트가 발생하면 process 함수를 호출해라

button.pack()

window.mainloop()

----------------------------------------
윈도우 크기 및 배치
----------------------------------------
from tkinter import *

def process():
print("안녕하세요?")

window = Tk()
window.title('my first window')
window.geometry("500x500")
window.resizable(0, 0)

button = Button(window, text="클릭", command=process)
btn.place(x=0, y=0, width=100, height=100)

# btn.destroy()

window.mainloop()

# 기타 배치관리자: pack; grid;
# 웹브라우저(부모 윈도우)같이 윈도우의 크기가 (확대/축소)변경되는 경우 pcak, grid가 유용할 수 있음
----------------------------------------
에딧 윈도우
----------------------------------------
from tkinter import *

def onHello():
    msg = edt.get()
    edt2.insert(10, msg)

window = Tk()
window.title('my first window')
window.geometry("500x500")
window.resizable(0, 0)

btn = Button(window, text='hello', command=onHello)
btn.place(x=0, y=0, width=100, height=100)

edt = Entry(window, bg='white', fg='black')
edt.place(x=100, y=0, width=200, height=100)

edt2 = Entry(window, bg='white', fg='red')
edt2.place(x=100, y=100, width=200, height=100)

window.mainloop()

[참고자료]
http://effbot.org/tkinterbook/
https://www.tutorialspoint.com/python/tk_button.htm
https://www.python-course.eu/tkinter_layout_management.php

----------------------------------------
이벤트처리2

bind()
: 마우스 움직임 이벤트

printxy(event): event
----------------------------------------
from tkinter import *

def printxy(event):
    print(event.x, event.y)

window = Tk()
window.title("my")
window.geometry("500x500")
window.resizable(0, 0)

window.bind("", printxy)

window.mainloop()

[참고자료]
https://docstore.mik.ua/orelly/other/python/0596001886_pythonian-chp-16-sect-9.html

----------------------------------------
캔바스 - 그림 그리는 함수가 포함되어 있음
create_oval(x1, y1, x2, y2, fill="blue")

----------------------------------------
#
#   오른쪽 버튼 다운 이벤트
#   왼쪽버튼 누른 상태에서 마우스 이동 이벤트
  마우스 이동 이벤트
#

from tkinter import *

mycolor = "blue"

def paint(event):
    x1, y1 = ( event.x-5 ), ( event.y-5 )
    x2, y2 = ( event.x+5 ), ( event.y+5 )
    canvas.create_oval( x1, y1, x2, y2,  fill = mycolor)

def changeColor():
    global mycolor
    mycolor="red"

def toggleColor(event):
    global mycolor
    if (mycolor == "red"):
        mycolor="blue"
    else:
        mycolor="red"

window = Tk()
window.bind("", toggleColor)

canvas = Canvas(window)
canvas.pack()
canvas.bind("", paint)

button = Button(window, text="red", command=changeColor)
button.pack()

window.mainloop()

[참고자료]
http://www.python-course.eu/tkinter_layout_management.php
http://zetcode.com/gui/tkinter/layout/

--------------------------------------------------------------------------------
윈도우 생성 함수와 이벤트 처리 함수를 하나로 묶어 보자
--------------------------------------------------------------------------------
'''https://docs.python.org/3.5/library/tk.html'''

from tkinter import *

class MyButton(Button):
    def __init__(self, window):
        self.button = Button(window, text = "저를 클릭해주세요", command = self.Sum)
        self.button.pack()

    def Sum(self):
        sum = 0
        for i in range(1, 11):
            sum += i
        print("합계 : ", sum)

def main():
    window =Tk()
    a = MyButton(window)
    a.Sum()
    window.mainloop()

main()


#
# 부연설명
#

Tk() -> 뭔가를 만든다 ~ 생성
MyButton() -> 뭔가를 만든다 ~ 생성

이렇게 생성된 것들을 통칭해서 부르는 단어가 있으면 좋겠다 -> "객체; Object"

Tk() -> Tk 객체 생성
MyButton() -> MyButton 객체 생성

객체가 생성되면서 자동으로 호출되는 함수가 바로 __init__() 함수이다.

이와 같이 객체를 생성하려면, 미리 객체를 정의해 두어야 한다.

객체를 정의하는 방법은,

class 로 시작해서 위와 같이 몇 가지 규칙을 따라 작성해야 한다.

__init__() 함수가 반드시 있어야 한다.

class 내부에서 정의하는 함수들 사이에서 공동으로 사용하는 변수는 self.를 앞에 붙인다.

class 내부에서 정의하는 함수를 호출할 때도 self.를 앞에 붙인다.

class 내부에서 정의한 함수를 사용하려면 다음과 같은 형식을 취한다.

a.Sum()

미리 작성해 둔 class가 갖고 있는 함수나 변수를 유지하면서, 새롭게 함수나 변수를 추가해서 class를 정의하려면 위와 같이 객체이름 뒤 괄호안에 class이름을 넣는다.

class MyButton(Button)

그렇지 않은 경우, 다음과 같이 생략하면 된다.

class MyButton()

위 코드를 안보고 타이핑 가능해야 한다.

[참고자료]
http://zetcode.com/gui/tkinter/layout/
--------------------------------------------------------------------------------

댓글 없음:

댓글 쓰기