1. 기본 다이얼로그 창
Tkinter는 messagebox라는 내장 모듈을 제공하여 정보 메시지, 경고, 오류 및 확인 요청과 같은 다이얼로그 창을 표시할 수 있어. 이런 다이얼로그는 사용자와 소통하고 알림을 만드는 데 유용해.
messagebox 모듈 연결
from tkinter import messagebox
messagebox의 주요 다이얼로그 유형
- 정보 창
정보 창은 사용자에게 중요한 정보를 알리는 용도로 사용돼.
messagebox.showinfo()함수가 사용돼.def show_info(): messagebox.showinfo("정보", "이것은 정보 메시지야") - 경고
경고 창은 잠재적인 문제나 특정 작업에 주의를 기울이도록 사용자에게 알리는 용도로 사용돼.
messagebox.showwarning()함수가 경고 창을 생성해.def show_warning(): messagebox.showwarning("경고", "이것은 경고 메시지야") - 오류 창
오류 창은 오류가 발생했을 때 사용자에게 알리기 위해 사용돼.
messagebox.showerror()함수가 적합해.def show_error(): messagebox.showerror("오류", "오류가 발생했어!") - 작업 확인 요청
확인 요청은 사용자가 작업을 확인하거나 취소할 수 있게 해줘.
messagebox.askyesno()함수는 사용자의 선택에 따라True또는False를 반환해.def confirm_exit(): response = messagebox.askyesno("종료", "정말 종료할래?") if response: root.quit()
2. 파일 및 폴더 선택
Tkinter는 또한 filedialog 모듈을 제공하며, 이는 사용자가 파일과 폴더를 선택할 수 있게 해줘. 파일을 로드하거나 저장하는 애플리케이션에 유용해.
filedialog 모듈 연결
from tkinter import filedialog
filedialog의 주요 함수
- 파일 열기:
askopenfilename()함수는 사용자가 열 파일을 선택할 수 있게 해줘.def open_file(): file_path = filedialog.askopenfilename( title="파일 열기", filetypes=[("텍스트 파일", "*.txt"), ("모든 파일", "*.*")]) if file_path: print("선택된 파일:", file_path) - 파일 저장:
asksaveasfilename()함수는 사용자가 파일을 저장할 경로와 이름을 선택할 수 있게 해줘.def save_file(): file_path = filedialog.asksaveasfilename( title="파일 저장", defaultextension=".txt", filetypes=[("텍스트 파일", "*.txt"), ("모든 파일", "*.*")]) if file_path: print("파일이 저장되었어:", file_path) - 폴더 선택:
askdirectory()함수는 폴더를 선택할 수 있게 해줘.def select_directory(): directory_path = filedialog.askdirectory(title="폴더 선택") if directory_path: print("선택된 폴더:", directory_path)
3. 사용자 정의 팝업 창
기본 다이얼로그 창 외에도, Tkinter는 Toplevel 위젯을 제공하여 사용자 정의 팝업 창을 만들 수 있어. 이 창은 입력 필드, 버튼 및 기타 인터페이스 요소가 있는 다기능 팝업 창을 만드는 데 사용할 수 있어.
Toplevel을 사용한 팝업 창 생성
import tkinter as tk
# 팝업 창을 여는 함수
def open_popup():
popup = tk.Toplevel(root)
popup.title("팝업 창")
popup.geometry("300x200")
label = tk.Label(popup, text="이름을 입력해주세요:")
label.pack(pady=10)
entry = tk.Entry(popup)
entry.pack(pady=5)
# 창 닫기 버튼
close_button = tk.Button(popup, text="닫기", command=popup.destroy)
close_button.pack(pady=10)
# 메인 창
root = tk.Tk()
root.title("메인 창")
root.geometry("400x300")
# 팝업 창 호출 버튼
open_button = tk.Button(root, text="팝업 창 열기", command=open_popup)
open_button.pack(pady=50)
root.mainloop()
코드 설명
tk.Toplevel(root)는root메인 창 위에 새로운 창을 생성해.- 창 요소들: 팝업 창 내부에는 레이블, 입력 필드, 버튼 등을 추가할 수 있어.
- "닫기" 버튼:
popup.destroy함수는 팝업 창을 닫아줘.
4. 다이얼로그와 팝업 창이 포함된 전체 애플리케이션
이제 다룬 모든 요소를 하나의 애플리케이션에 통합하여, 기본 다이얼로그 창, 파일 선택 및 사용자 정의 팝업 창을 포함한 애플리케이션을 만들어보자.
import tkinter as tk
from tkinter import messagebox, filedialog
# 기본 다이얼로그를 위한 함수
def show_info():
messagebox.showinfo("정보", "이것은 정보 메시지야")
def show_warning():
messagebox.showwarning("경고", "이것은 경고 메시지야")
def show_error():
messagebox.showerror("오류", "오류가 발생했어!")
def confirm_exit():
response = messagebox.askyesno("종료", "정말 종료할래?")
if response:
root.quit()
def open_file():
file_path = filedialog.askopenfilename(title="파일 열기", filetypes=[("텍스트 파일", "*.txt"), ("모든 파일", "*.*")])
if file_path:
messagebox.showinfo("선택된 파일", file_path)
def save_file():
file_path = filedialog.asksaveasfilename(title="파일 저장", defaultextension=".txt", filetypes=[("텍스트 파일", "*.txt"), ("모든 파일", "*.*")])
if file_path:
messagebox.showinfo("파일이 저장됨", file_path)
def select_directory():
directory_path = filedialog.askdirectory(title="폴더 선택")
if directory_path:
messagebox.showinfo("선택된 폴더", directory_path)
# 사용자 정의 팝업 창에 대한 함수
def open_popup():
popup = tk.Toplevel(root)
popup.title("팝업 창")
popup.geometry("300x200")
tk.Label(popup, text="이름을 입력해주세요:").pack(pady=10)
name_entry = tk.Entry(popup)
name_entry.pack(pady=5)
tk.Button(popup, text="닫기", command=popup.destroy).pack(pady=10)
# 메인 창
root = tk.Tk()
root.title("다이얼로그 및 팝업 창 애플리케이션")
root.geometry("400x400")
# 다양한 다이얼로그와 팝업 창 호출 버튼
tk.Button(root, text="정보", command=show_info).pack(pady=5)
tk.Button(root, text="경고", command=show_warning).pack(pady=5)
tk.Button(root, text="오류", command=show_error).pack(pady=5)
tk.Button(root, text="종료 확인", command=confirm_exit).pack(pady=5)
tk.Button(root, text="파일 열기", command=open_file).pack(pady=5)
tk.Button(root, text="파일 저장", command=save_file).pack(pady=5)
tk.Button(root, text="폴더 선택", command=select_directory).pack(pady=5)
tk.Button(root, text="팝업 창 열기", command=open_popup).pack(pady=20)
root.mainloop()
GO TO FULL VERSION