Python tkinter Listbox ( 목록창 )

Python tkinter Listbox 위젯에 대해 살펴보겠습니다.

Listbox는 여러 아이템(요소, 항목)들이 표시된 목록 창입니다.

 

Listbox 만들기

Listbox는 tkinter에 Listbox(window) 함수로 생성합니다. 매개변수로 Listbox가 출력될 window를 넣어줘야 합니다.

생성한 후 listbox.pack() 함수로 Listbox를 window내에 배치합니다.

import tkinter
win = tkinter.Tk();

# Listbox 생성
listbox = tkinter.Listbox(win, width=10, height=5);
listbox.config(borderwidth=3);
listbox.pack();

win.mainloop();

옵션은 다른 위젯들과 마찬가지로 생성하면서 파라미터로 설정해도 되고, config() 함수로 설정할 수 도 있습니다.

 

위처럼 Listbox를 생성하면 비어있는 목록이 됩니다.

목록이라 함은 당연히 요소들이 있어야겠죠??

Listbox.insert() 함수와 Listbox.delete() 함수로 요소를 추가 및 삭제할 수 있습니다.

# Listbox에 요소 추가하기
listbox.insert(0, '0번 Item');
listbox.insert(1, '1번 Item');
listbox.insert(2, '2번 Item');
listbox.insert(3, '3번 Item');
listbox.insert(4, '4번 Item');


# Listbox에 요소 삭제하기
listbox.delete(0);    #0번 index 요소 삭제
listbox.delete(3,4);  #3~4번 index 요소 삭제

 

Listbox의 함수들

이름 기능
insert(index, item) index 위치에 item추가 ( item 은 str로 자동 형변환 됩니다. )
delete(start_index, end_index) start_index 부터, end_index까지 삭제
파라미터를 1개만 넘길경우 해당 index요소 삭제
size() 요소 개수 반환
activate(index) index 에 해당하는 요소 선택
curselection() 선택된 요소들을 튜플로 반환
get(start_index, end_index) start_index 부터 end_index 까지 요소들을 튜플로 반환
nearest(val) 현재 보이는 리스트박스 요소들 중 val에 가장 가까운 값 반환
see(index) index 에 해당하는 요소가 보이도록 리스트박스 위치조정
xview() 가로스크롤 연결
xview_moveto(num) 가로스크롤을 이동 ( 0~1 )
yview() 세로스크롤 연결
yview_moveto(num) 세로스크롤 이동 ( 0~1 )

 

Listbox의 옵션들

1. Listbox의 디자인 관련

이름 기능 기본값 속성
font Listbox의 글꼴 설정 TkDefaultFont font
cursor Listbox의 마우스 커서모양   pointer, arrow등 cursor속성
width Listbox의 길이 20 숫자
height Listbox의 높이 10 숫자
relief Listbox의 테두리 설정 flat flat, solid, ridge, sunken, raised, groove
setgrid Listbox의 격자크기 조정가능 여부 False Boolean
borderwidth Listbox의 테두리 두께 2 숫자
foreground Listbox의 문자열 색상 SystemButtonFace color
background Listbox의 배경 색상 SystemButtonFace color
selectbackground Listbox의 선택된요소 블록의 배경색상 SystemHIghlight color
selectforeground Listbox의 선택된요소 블록의 문자열 색상 SystemHighlight color
selectborderwidth Listbox의 선택된요소 블록의 테두리 두께 0 숫자
disabledforeground Listbox의 disabled 상태일때 문자열 색상 SystemDisabledText color
highlightcolor Listbox가 선택되었을때 하이라이트 색상 SystemWindowFrame color
highlightbackground Listbox가 선택되지 않았을때 하이라이트 색상 SystemButtonFace color
highlightthickness Listbox가 선택되었을때 하이라이트 두께 0 숫자
activestyle Listbox내 선택된 요소의 표시형태 설정 underline underline, none, dotbox

 

2. Listbox의 동작 관련

이름 기능 기본값 속성
state Listbox의 상태설정 normal normal, readonly, disabled
exportselection Listbox내 요소 선택 유지 True Boolean
takefocus Tab키 위젯이동 허용여부 True Boolean
selectmode Listbox의 요소 선택방법 browse browse, extended, single, multiple
xscrollcommand Listbox의 가로스크롤 위젯 적용   Scrollbar위젯.set
yscrollcommand Listbox의 세로스크롤 위젯 적용   Scrollbar위젯.set