C-log

👩‍🏫class : 12week 본문

📘Python/👩‍🏫class

👩‍🏫class : 12week

4:Bee 2023. 12. 8. 16:28
728x90

12주차에선 if문을 주로 다루었지만 아주 기본적이기 때문에 바로 응용부터 글을 작성할 것이다.

img와 entry를 이용한 if문 

from tkinter import *
root = Tk()
root.title("윈도우 창 만들기")
#geometry는 윈도우 창 크기를 결정 짓는 명령어이다.
root.geometry("230x120")

def pass_check():
    score = int(ent.get())

    if score >= 70:
        #lbl_status.configure(text = "합격")
        lbl_status.configure(text = "합격")
        lbl_img = Label(root, text = "합격")#image = photo1
        lbl_img.place(x=100, y=30)
    else :
        lbl_status.configure(text="불합격")
        lbl_img = Label(root, image = photo2)
        lbl_img.place(x=100, y=30)

photo1 = PhotoImage(file="smile.png")
photo2 = PhotoImage(file="try.png")

lbl = Label(root, text = "정수")
ent = Entry(root, width= 20)
btn = Button(root, text = "확인", command = pass_check)
lbl_status = Label(root, text = "합격여부")

lbl.place(x = 10, y = 10)
ent.place(x = 50, y = 10)
btn.place(x = 50, y = 40)
lbl_status.place(x = 50, y = 80)

#위치를 배치하려면 pack으로 지정하면 안된다.
#lbl.pack()
#ent.pack()
#btn.pack()
#lbl_status.pack()
root.mainloop()

#https://076923.github.io/posts/Python-tkinter-12/

주석으로도 설명을 했지만 place를 사용하기 위해서는 pack()을 이용하면 안된다. 물론 pack내부에서도 위치값을 조정할 수는 있지만 place만큼 정밀하게 조정할 수 없다.

이미지를 불러오는 방식에서 이미지의 주소는 컴파일이 되는 py파일 과 동등하게 위치해야 한다. 뿐만 아니라 configue를 통해서 변경된 값을 줄 수 있는데 여기서 img를 줄수도 있고 text로 변경 할 수 있다.

직접 입력한 값의 짝수 홀수 구분

number = input("정수를 입력하세요.->")
#끝의 한자리만 가지고 와서 구문하는 방법
last_char = number[-1]

last_num = int(last_char)

if last_num == 0 \
   or last_num == 2 \
   or last_num == 4 \
   or last_num == 6 \
   or last_num == 8 :
    print("짝수 입니다.")
else :
    print("홀수 입니다.")

무한히 직접 입려된 값이 짝수인지 홀수 인지 확인하는 방법은 마지막 뒷 자리의 홀짝여부에 따라 결정되게 만든 코드이다.


버튼을 구현해서 사진 위치를 바꿀 수 있는 페이지를 제작

from tkinter import *
root = Tk()
root.title("image 조작하기")
root.geometry("720x450")


#-------------------- image area --------------
#이미지 불러오기
brain = PhotoImage(file="smile.png")
#이미지 위젯 생성
lbl_img = Label(root, image = brain)

#img위치 변수
current_x = 100
current_y = 100

#img 위젯 위치 설정 
lbl_img.place(x = current_x, y = current_y)

def new_pos() : #x,y
    #매개변수로 가져올 수 없으니 직접적으로 get을 해서 가지고 와야한다.
    current_x = x_ent.get()
    current_y = y_ent.get()
    #이미지의 위치가 event 위젯 영역에 침범하지 않기 위한 if문
    if int(current_y) > 100 :
        lbl_img.place(x = current_x, y = current_y)
        print("check", current_x, current_y)
    else :
        #초과 될 경우 경고문을 활성
        print("Whatch OUT!!")
    

#--------------- 위젯 생성 ---------------
x_lbl = Label(root, text = "input pos(x)")
x_ent = Entry(root, width = 20)


y_lbl = Label(root, text = "input pos(y)")
y_ent = Entry(root, width = 20)

#btn_create
btn = Button(root, text = "변경", command = new_pos)#lambda : new_pos(x_ent.get(), y_ent.get())



# ---------------위젯 위치 지정---------------
x_lbl.place(x = 10, y = 20)
x_ent.place(x = 90, y = 20)

y_lbl.place(x = 10, y = 50)
y_ent.place(x = 90, y = 50)

#btn_place
btn.place(x = 10, y = 70)

root.mainloop()

함수를 매개변수를 받아서 Button의 command로 evnet처리를 하려했으나 버튼 클릭시에 바로 event처리가 발생하는 문제가 있어서 이를 해결하기 위해서는 두 가지 방법이 있었다.첫 번째는 위에 적어낸 방식으로 직접 Entry된 값을 get으로 가져오는 방법이 있고 lambda식으로 풀어내는 방법이 있다. 아래 코드는 lambda식으로 작성한 코드이다. (함수와 Button부분만 아래 코드려 변경하면 된다.)

...
def new_pos(x,y) : #x,y
    current_x = x
    current_y = y
    #이미지의 위치가 event 위젯 영역에 침범하지 않기 위한 if문
    if int(x) > 100 :
        lbl_img.place(x = current_x, y = current_y)
        print("check", current_x, current_y)
    else :
        #초과 될 경우 경고문을 활성
        print("Whatch OUT!!")
...
btn = Button(root, text = "변경", command = lambda : new_pos(x_ent.get(), y_ent.get()))#lambda : new_pos(x_ent.get(), y_ent.get())

해당 코드를 테스트 하기위해서 가단하게 입력 값을 합산하는 코드도 만들어 보았다. 코드는 아래와 같다.

from tkinter import *
root = Tk()
root.title("image 조작하기")
root.geometry("300x250")

def add() :
    #이렇게 직접 받아오는 것 밖에 없다.
    a = int(a_ent.get())
    b = int(b_ent.get())
    result = a+b
    lbl.configure(text = f"result : {a} + {b} = {result}")
    return a+b

def check():
    a_result = a_ent.get()
    b_result = b_ent.get()
    print(a_result)
    print(b_result)
    lbl.configure(text = f"result : {a_result}, {b_result}")
    
#위젯 설정     
a_ent = Entry(root, width = 20)
b_ent = Entry(root, width = 20)
btn = Button(root,text="add",command = add)
lbl = Label(root, text = "result")

a_ent.pack()
b_ent.pack()
btn.pack()
lbl.pack()

root.mainloop()
728x90
Comments