
"Life is too short, You need python"
Tkinter에서 Listbox 사용 시 종종 볼 수 있는 오류로 Listbox 외 Widget의 선택 또는 Drag(Entry 등...) 시 Listbox는 선택값을 잃게 되고(선택 해제) Index 오류가 발생합니다. Listbox의 선택값을 잃게되면 연계 Widget 정보 또한 사라지기 때문에 마우스 드래그로 값을 Copy 하기 위해서는 조치가 필요합니다. 해당 오류 발생 시 어떻게 해결해야 하는지에 대해 알아보도록 하겠습니다.
Tkinter Listbox loses its selection when clicking elsewhere on the form
When a tkinter form includes a listbox and other widgets, clicking on the other widgets (especially if the mouse is dragged) causes the listbox to lose its selection -- meaning that the element(s) that was/were selected/highlighted in the lisbox become unselected.
Index Error: tuple index out of range 의 의미
Index Error: tuple index out of range
Index는 목록이나 문자열과 같은 반복 가능한 객체 내부의 값이며,
'tuple index out of range' 는 존재하지 않는 tuple index에 액세스하려고 할 때 발생하는 오류 메세지 입니다.
- Listbox에서 받아올 값이 없거나
- 해당 Widget을 벗어나 마우스 클릭이나 드래그 시
해당 Listbox의 선택 값을 잃게 됩니다.
1번 Case 처럼 Listbox에 받아올 값이 없는 경우라면 예외처리나 조건문을 통해 해결하면 되겠지만
2번 Case와 같이 widget을 벗어난 click으로 선택 값을 잃게되는 경우에는 어떻게 대처해야 할까요?
불러온 정보들을 Copy & Paste 시 정보가 사라지지 않게 하기 위해서는 어떻게 해야 할까요?
exportselection option
tk.Listbox(window, exportselection = False) or .configure(exportselection = False)
listbox = tk.Listbox(window, listvariable = listbox_val, width = 30, height = 35, yscrollcommand = scroll_listbox.set, selectmode = 'browse', exportselection = 0)
exportselection이 True 혹은 1일 경우 리스트 박스가 2개 이상일 경우 1번 리스트 박스에서 항목 선택 후, 2번 리스트 박스혹은 Entry등의 위젯에서 항목을 선택하게 된다면 리스트 박스의 항목 선택 상태가 해제되게 됩니다.
만약 항목을 유지하기를 원한다면 exportselection = False(exportselection = 0) 옵션을 설정하면 됩니다.
마무리
Listbox의 위젯 외부에서 클릭 시 발생하는 Index Error를 해결하는 방법에 대해 확인해 보았습니다.