Python Tkinter - 3. 고급 위젯과 데이터 관리

2025. 2. 3. 13:43프로그래밍 언어/Python

이론

고급 위젯

Tkinter에서는 기본 위젯 외에도 복잡한 UI를 구성할 수 있도록 다양한 고급 위젯을 제공합니다.

1. Checkbutton, Radiobutton: 다중 및 단일 선택

  • Checkbutton: 여러 개의 항목을 선택할 수 있는 체크박스.
  • Radiobutton: 하나의 그룹에서 단 하나의 항목만 선택할 수 있는 라디오 버튼.

예제:

import tkinter as tk

root = tk.Tk()
root.title("Checkbutton & Radiobutton 예제")

# Checkbutton 예제
chk_var1 = tk.IntVar()
chk_var2 = tk.IntVar()
chk1 = tk.Checkbutton(root, text="옵션 1", variable=chk_var1)
chk2 = tk.Checkbutton(root, text="옵션 2", variable=chk_var2)
chk1.pack()
chk2.pack()

# Radiobutton 예제
radio_var = tk.StringVar(value="옵션 1")
tk.Radiobutton(root, text="옵션 1", variable=radio_var, value="옵션 1").pack()
tk.Radiobutton(root, text="옵션 2", variable=radio_var, value="옵션 2").pack()

root.mainloop()

2. Listbox, Combobox: 리스트 형태의 데이터 관리

  • Listbox: 여러 항목을 리스트 형태로 표시.
  • Combobox: 드롭다운 목록에서 선택할 수 있도록 제공.

예제:

from tkinter import ttk

listbox = tk.Listbox(root)
listbox.insert(1, "항목 1")
listbox.insert(2, "항목 2")
listbox.pack()

combo = ttk.Combobox(root, values=["옵션 A", "옵션 B", "옵션 C"])
combo.pack()

3. Scrollbar: 긴 내용 표시 및 스크롤 처리

예제:

text = tk.Text(root, height=5, width=40)
scrollbar = tk.Scrollbar(root, command=text.yview)
text.configure(yscrollcommand=scrollbar.set)
text.pack(side="left")
scrollbar.pack(side="right", fill="y")

데이터 관리

Tkinter는 SQLite와 함께 사용하여 GUI 기반 데이터 관리 애플리케이션을 개발할 수 있습니다.

1. Tkinter와 SQLite 연동

SQLite는 Python 내장 데이터베이스로, 파일 하나로 간단한 데이터 저장이 가능합니다.
예제:

import sqlite3

conn = sqlite3.connect("example.db")
cursor = conn.cursor()

# 작업이 끝난 후 연결을 종료하는 것이 중요합니다.
def close_connection():
    close_connection()
cursor = conn.cursor()

# 테이블 생성
cursor.execute("""
CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY,
    name TEXT,
    age INTEGER
)
""")

# 데이터 삽입
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ("홍길동", 30))
conn.commit()

# 데이터 조회
cursor.execute("SELECT * FROM users")
print(cursor.fetchall())

conn.close()

실습

1. 설문조사 폼

  • Checkbutton과 Radiobutton을 활용하여 다중 선택 설문조사 폼을 제작.

예제:

def submit():
    print("선택된 옵션:", var1.get(), var2.get(), radio_var.get())

var1 = tk.IntVar()
var2 = tk.IntVar()
radio_var = tk.StringVar(value="A")

chk1 = tk.Checkbutton(root, text="항목 1", variable=var1)
chk2 = tk.Checkbutton(root, text="항목 2", variable=var2)
chk1.pack()
chk2.pack()

radio1 = tk.Radiobutton(root, text="A", variable=radio_var, value="A")
radio2 = tk.Radiobutton(root, text="B", variable=radio_var, value="B")
radio1.pack()
radio2.pack()

btn = tk.Button(root, text="제출", command=submit)
btn.pack()

2. 로그 뷰어

  • Scrollbar를 사용하여 스크롤 가능한 텍스트 뷰어 제작.

예제:

def log_message():
    text.insert(tk.END, "새로운 로그 메시지\n")
    text.yview(tk.END)

text = tk.Text(root, height=10, width=50)
scroll = tk.Scrollbar(root, command=text.yview)
text.configure(yscrollcommand=scroll.set)
text.pack()
scroll.pack(side="right", fill="y")

log_btn = tk.Button(root, text="로그 추가", command=log_message)
log_btn.pack()

3. 데이터베이스 연동 주소록 애플리케이션

SQLite를 활용한 간단한 주소록.

def add_contact():
    if not entry_name.get().strip() or not entry_phone.get().strip():
        print("이름과 전화번호를 모두 입력해야 합니다.")
        return
    name = entry_name.get()
    phone = entry_phone.get()
    cursor.execute("INSERT INTO contacts (name, phone) VALUES (?, ?)", (name, phone))
    conn.commit()

conn = sqlite3.connect("contacts.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY, name TEXT, phone TEXT)")

entry_name = tk.Entry(root)
entry_phone = tk.Entry(root)
entry_name.pack()
entry_phone.pack()
btn = tk.Button(root, text="추가", command=add_contact)
btn.pack()

과제

간단한 블로그 애플리케이션

  • 글 작성, 저장, 조회 기능 구현.
  • SQLite를 활용하여 글 관리.

예제 코드:

def save_post():
    if not entry_title.get().strip() or not text_content.get("1.0", tk.END).strip():
        print("제목과 내용을 입력해야 합니다.")
        return
    title = entry_title.get()
    content = text_content.get("1.0", tk.END)
    cursor.execute("INSERT INTO posts (title, content) VALUES (?, ?)", (title, content))
    conn.commit()

conn = sqlite3.connect("blog.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS posts (id INTEGER PRIMARY KEY, title TEXT, content TEXT)")

entry_title = tk.Entry(root)
text_content = tk.Text(root)
entry_title.pack()
text_content.pack()
btn_save = tk.Button(root, text="저장", command=save_post)
btn_save.pack()

기대 효과

  • Tkinter의 고급 위젯을 활용하여 더욱 풍부한 GUI 애플리케이션을 제작할 수 있습니다.
  • 데이터베이스를 활용한 CRUD 기능을 익혀 데이터 관리 능력을 향상할 수 있습니다.