본문 바로가기
Python/GUI(tkinter)

독학 Python tkinter(GUI) - 12.Text(+scrollbar)

by To올라운더 2023. 11. 10.
반응형

이제 우리는 앞선 포스팅에서 Entry를 통해 [예/아니오] 와 같은 버튼보다 확장된 형태의 정보를 주고 받을 수 있게 되었다.

 

그런데, Entry는 태생적인 제한이 있는데,

바로 줄바꿈을 사용하지 못한다는 것이다.

 

어떠한 정보를 전달하는데 있어 줄바꿈(Enter)가 없으면 여러 면에서 불편하다.

가장 큰 불편함은 텍스트들이 단위별로 구분되지 않는다는 것인데,

이런 부분을 해소해줄 수 있는 요소(위젯)이 Text이다.

 

Text는 사실 크게 어렵지 않다. 

하지만 Text만으로는 GUI상에서 조금 부족한 부분이 있기 때문에 

scrollbar와 함께 표현을 해줘야 좀 더 디테일이 살아있는 GUI가 될 수 있다.

 

1. Text 사용하기

from tkinter import *
import tkinter.messagebox as msb
from tkinter import filedialog # 파일 open 기능 사용

root = Tk()
root.title('To올라운드의 알찬 GUI 강의')


root.geometry("300x200") # 가로 X 세로 / 대문자X 하면 실행안됨

msb.showinfo('Welcome','안녕하세요. To올라운더와 함께 하는 GUI입니다.')

body_frame = Frame(root, relief='solid', bd=2, background='orange', padx=5, pady=5)
body_frame.pack(fill='both', expand=True)


text_window = Text(body_frame, height=5)
text_window.pack()

quit_btn = Button(body_frame, text='종료', command=quit)
quit_btn.pack()


root.resizable(False,False) # x너비, y 변경 허용 여부
root.mainloop()

-

 - Text 요소(위젯)을 넣는 건 앞선 Label 등과 다르지 않다. Text(위치, 파라미터)를 할당하게 되는데,

   여기서 주의 깊게 봐야 할 부분이 height 이다.

 - height는 GUI에서 한번에 보여주는 창의 높이라고 생각할 수도 있는데, 해당 값을 5로 할당하였을 때, 

   1~5까지 5줄이 보이는 것을 알 수 있다.

 - 그런데, 만약 사용자가 GUI상에서 10까지 추가로 입력하면 어떻게 될까?

 - 말 그대로 5줄을 GUI상에서 보여주기만 할 뿐 현재 보고 있는 텍스트의 위치가 어디쯤인지, 끝인지 뒤에 내용이 더 있는지 등의 정보를 확인할 수 없어 다소 부족한 모습을 갖게된다.

 - 이런 부족한 부분을 보완 해줄 수 있는 요소(위젯)가 scrollbar이다.

반응형

 

3. scrollbar 추가하기

from tkinter import *
import tkinter.messagebox as msb
from tkinter import filedialog # 파일 open 기능 사용

root = Tk()
root.title('To올라운드의 알찬 GUI 강의')


root.geometry("300x200") # 가로 X 세로 / 대문자X 하면 실행안됨

msb.showinfo('Welcome','안녕하세요. To올라운더와 함께 하는 GUI입니다.')

body_frame = Frame(root, relief='solid', bd=2, background='orange', padx=5, pady=5)
body_frame.pack(fill='both', expand=True)


# Text 추가할 Frame 생성
text_frame = Frame(body_frame)
text_frame.pack(fill='x', expand=True)

# scrollbar y축(세로축) 추가하기
scrollbar_text_view_y = Scrollbar(text_frame)
scrollbar_text_view_y.pack(side="right", fill="y")

text_window = Text(text_frame, height=5, yscrollcommand=scrollbar_text_view_y.set)
text_window.pack(fill='x')
scrollbar_text_view_y.config(command=text_window.yview)



quit_btn = Button(body_frame, text='종료', command=quit)
quit_btn.pack()


root.resizable(False,False) # x너비, y 변경 허용 여부
root.mainloop()

 

 - scrollbar(스크롤바)를 구성하기 위한 3가지 단계이다.

  1) Frame 별도 생성하기

     : Text와 Scrollbar가 합쳐져야 하는 형태이기 때문에 별도로 구성하기 위해 text_frame을 만든다.

     : text_window 의 height 값을 확인하기 위해 fill 파라미터는 x만 지정하였지만, 해당 영역을 전체 사용하기 위해 both를 사용해도 무관하다.

 

 

  2) scrollbar 생성하기

    : text와 연계할 scrollbar를 생성한다. 생성시 위치는 1)에서 만든 text_frame에 위치하고

      일반적으로 세로 축은 오른쪽(side='right'), 가로 축은 아래(side='bottom')으로 생성하는 형태가 보기좋다.

 

 

  3) Text 생성하기

    : 이제 실제 텍스트를 입력할 text_window 요소를 생성한다.

    : 이때 yscrollcommand 파라미터를 할당하게 되는데, 2)에서 생성한 srcollbar를 지정한다.

      여기까지만 진행하면 text_window에 내용이 입력되거나 커서가 이동함에 따라 우측의 세로축 스크롤바가 따라 움직이는 것을 볼 수 있다. 그런데 반대로 스크롤 바를 움직이면 text_window가 이동하지 않는 증상을 볼 수 있는데 이를 해결 하기 위해 마지막 27라인을 추가해줘야 한다.

     : 27라인의 코드는 scrollbar에서 동작을 할 때 해당 값이 text_window의 y축(세로축)이 함께 움직이도록 설정하는 항목이다.

 

이제 해당 내용을 바탕으로 가로 축도 설정해보겠다.

 

위의 코드에서 y와 관련된 값들을 x로 변경하여 추가하고, 위치(side='bottom')와 fill 등 몇가지 설정만을 변경해주면 

어렵지 않게 scrollbar 가 나타난다.

 

 - 그런데 뭔가 예상했던것과 다르게 상하로 나타나는 것을 보게 되는데,

   scrollbar의 기본 방향이 위아래로 되어 있기 때문에 해당 값을 주지 않으면 위의 그림처럼 나타나게 된다.

 

 - 아래 코드 28라인처럼 Scrollbar를 생성할 때, orient 파라미터에 'horizontal' 을 적용해주면

   아래의 그림과 같이 가로로 길게 뻗은 scrollbar가 생성된다.

 

 

 

 - 전체 코드는 아래와 같습니다.

from tkinter import *
import tkinter.messagebox as msb
from tkinter import filedialog # 파일 open 기능 사용

root = Tk()
root.title('To올라운드의 알찬 GUI 강의')


root.geometry("300x200") # 가로 X 세로 / 대문자X 하면 실행안됨

#msb.showinfo('Welcome','안녕하세요. To올라운더와 함께 하는 GUI입니다.')

body_frame = Frame(root, relief='solid', bd=2, background='orange', padx=5, pady=5)
body_frame.pack(fill='both', expand=True)


# Text 추가할 Frame 생성
text_frame = Frame(body_frame)
#text_frame.pack(fill='x', expand=True)
text_frame.pack()

# scrollbar y축(세로축) 추가하기
scrollbar_text_view_y = Scrollbar(text_frame)
scrollbar_text_view_y.pack(side="right", fill="y")


# scrollbar x축(가로축) 추가하기
scrollbar_text_view_x = Scrollbar(text_frame, orient='horizontal')
scrollbar_text_view_x.pack(side="bottom", fill="x")


text_window = Text(text_frame, height=5, yscrollcommand=scrollbar_text_view_y.set, xscrollcommand=scrollbar_text_view_x.set)
text_window.pack(fill='both')

scrollbar_text_view_y.config(command=text_window.yview)
scrollbar_text_view_x.config(command=text_window.xview)




quit_btn = Button(body_frame, text='종료', command=quit)
quit_btn.pack()


root.resizable(False,False) # x너비, y 변경 허용 여부
root.mainloop()

 

 

4. Text 값 가져오기 / 수정하기 / 삭제하기

 -  scrollbar를 설명하다보니, 본론을 잠시 벗어난 듯 하지만,

   잊지 않고 Text 의 기능을 마무리해보겠다.

 - Entry와 비교했을 때 Text의 값을 가져오거나 수정하는 건 크게 다르지 않다.

 - 다만 1줄인 Entry의 경우 Index 위치 값을 확인하여 적용하면 되지만, 

   Text의 경우에는 여러줄인 만큼 몇번째 줄인지도 표현해줘야한다. 

from tkinter import *
import tkinter.messagebox as msb
from tkinter import filedialog # 파일 open 기능 사용

root = Tk()
root.title('To올라운드의 알찬 GUI 강의')

def get_text():
    print(text_window.get('1.0',END))


def delete_text():
    text_window.delete('1.0', END)

def insert_text():
    text_window.insert('2.0','해당 내용이 추가 됩니다.\n')

root.geometry("300x200") # 가로 X 세로 / 대문자X 하면 실행안됨

#msb.showinfo('Welcome','안녕하세요. To올라운더와 함께 하는 GUI입니다.')

body_frame = Frame(root, relief='solid', bd=2, background='orange', padx=5, pady=5)
body_frame.pack(fill='both', expand=True)


# Text 추가할 Frame 생성
text_frame = Frame(body_frame)
#text_frame.pack(fill='x', expand=True)
text_frame.pack()

# scrollbar y축(세로축) 추가하기
scrollbar_text_view_y = Scrollbar(text_frame)
scrollbar_text_view_y.pack(side="right", fill="y")


# scrollbar x축(가로축) 추가하기
scrollbar_text_view_x = Scrollbar(text_frame, orient='horizontal')
scrollbar_text_view_x.pack(side="bottom", fill="x")


text_window = Text(text_frame, height=5, yscrollcommand=scrollbar_text_view_y.set, xscrollcommand=scrollbar_text_view_x.set)
text_window.pack(fill='both')

scrollbar_text_view_y.config(command=text_window.yview)
scrollbar_text_view_x.config(command=text_window.xview)


get_text_btn = Button(body_frame, text ='Text 값 가져오기', command=get_text)
get_text_btn.pack(fill='x')

delete_text_btn = Button(body_frame, text='Text 값 지우기', command=delete_text)
delete_text_btn.pack(fill='x')

insert_text_btn = Button(body_frame, text='Text 추가', command=insert_text)
insert_text_btn.pack(fill='x')

quit_btn = Button(body_frame, text='종료', command=quit)
quit_btn.pack(fill='x')


root.resizable(False,False) # x너비, y 변경 허용 여부
root.mainloop()

 

 - 해당 코드를 실행해보면, get_text, delete_text, insert_text 로 3개의 메서드를 추가했는데,

  1) text 값 가져오기(get_text)

    : text_window.get('1.0' , END) 에서 앞의 1은 몇번째 줄인지 나타내는 값이며, 0은 해당 줄은 index 값이다.

      그래서 해당 메서드로 값을 출력하면 1번째줄 처음부터 끝까지 모두를 print 하게 된다.

 

  2) text 값 삭제하기(delete_text)

    : get 메서드와 동일하다. delete를 사용할 때에도 어디부터 어디까지인지를 설정하는데,

      text_window.delete('1.0', END)를 입력하면 1번째줄 처음 글자부터 끝까지를 삭제하는 기능을 가진다.

 

  3) text 값 추가하기(insert_text)

    : text_window.insert('2.0', '입력 내용') 을 추가하게되면, 

     2번째줄 첫번째 위치부터 해당 내용을 입력하게된다.

 

Text와 Scrollbar까지 진행하니 우리의 GUI가 좀 더 사용하기에 적합해 보이는 느낌이 들지 않으신가요?

이제 약간의 디테일만 더하면 우리가 원하는 GUI를 100% 만들 수 있는 환경이 될 수 있습니다.

 

정말 끝이 보이네요. 조금만 더 화이팅!!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

반응형