대화 상자는 모든 응용 프로그램의 매우 필수적인 구성 요소입니다. 일반적으로 사용자 및 응용 프로그램 인터페이스와 상호 작용하는 데 사용됩니다. Toplevel 창 및 기타 위젯을 사용하여 모든 tkinter 응용 프로그램에 대한 대화 상자를 만들 수 있습니다. 최상위 창은 다른 모든 창 위에 항목을 표시합니다. 따라서 대화 상자를 작성하기 위해 최상위 창에 더 많은 항목을 추가할 수 있습니다.
예
이 예에서는 두 부분으로 구성된 모달 대화 상자를 만들었습니다.
- 최상위 창 초기화
- 팝업 대화 상자 이벤트에 대한 함수 정의.
- 최상위 창에 위젯 추가
- 대화 상자 옵션에 대한 기능 정의.
# Import required libraries
from tkinter import *
from tkinter import ttk
# Create an instance of tkinter frame
win = Tk()
# Set the window size
win.geometry("700x350")
style = ttk.Style()
style.theme_use('clam')
# Define a function to implement choice function
def choice(option):
pop.destroy()
if option == "yes":
label.config(text="Hello, How are You?")
else:
label.config(text="You have selected No")
win.destroy()
def click_fun():
global pop
pop = Toplevel(win)
pop.title("Confirmation")
pop.geometry("300x150")
pop.config(bg="white")
# Create a Label Text
label = Label(pop, text="Would You like to Proceed?",
font=('Aerial', 12))
label.pack(pady=20)
# Add a Frame
frame = Frame(pop, bg="gray71")
frame.pack(pady=10)
# Add Button for making selection
button1 = Button(frame, text="Yes", command=lambda: choice("yes"), bg="blue", fg="white")
button1.grid(row=0, column=1)
button2 = Button(frame, text="No", command=lambda: choice("no"), bg="blue", fg="white")
button2.grid(row=0, column=2)
# Create a Label widget
label = Label(win, text="", font=('Aerial', 14))
label.pack(pady=40)
# Create a Tkinter button
ttk.Button(win, text="Click Here", command=click_fun).pack()
win.mainloop() 출력
위의 코드를 실행하면 모달 대화 상자를 여는 버튼이 있는 창이 표시됩니다.

버튼을 클릭하면 모달 대화 상자가 열립니다.
