Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Tkinter에서 MessageBox 위치를 변경하는 방법

Tkinter를 사용하여 대화 상자(Dialog Box)를 만들고 싶다고 가정해 보겠습니다. 대화 상자는 MessageBox 라이브러리를 활용하면 손쉽게 구현할 수 있으며, 이 라이브러리에는 다양한 유형의 대화 상자를 빠르게 생성할 수 있는 함수들이 포함되어 있습니다.

생성된 대화 상자의 위치를 조정하려면 “toplevel” 속성을 사용하면 됩니다. 이 속성은 현재 창에 우선순위를 부여하여 해당 창이 화면 최상단에 나타나고, 나머지 프로세스들은 백그라운드에서 유지되도록 합니다.

Toplevel은 title, message, details 등의 다른 기능들도 함께 제공합니다. MessageBox 위젯의 위치를 변경하려면 geometry 메서드를 사용합니다. geometry 메서드는 "너비x높이+X좌표+Y좌표" 형식으로 작성하여 창의 크기와 화면상의 표시 위치를 동시에 지정할 수 있습니다.

예제 코드

#import the tkinter library

from tkinter import *

#define the messagebox function
def messagebox():

#toplevel function creates MessageBox dialog which appears on top of the screen
   top=Toplevel(win)
   top.title("Click Me")
   #Define the position of the MessageBox
   x_position = 600
   y_position = 400
   top.geometry(f"600x200+{x_position}+{y_position}")
   #Define the property of the messageBox
   l1=Label(top, text= "Hello! TutorialsPoint",bg= "green", fg=
"white",font=('Times New Roman', 24),height=50, width= 50).pack()

#Create an instance of the tkinter frame
#And resize the frame
win = Tk()
win.geometry("600x200")
win.title("Window-1")
Button(win, text="Click Me", command=messagebox,
width=8).pack(pady=80)

win.mainloop()

실행 결과

위 코드를 실행하면 다음과 같은 출력 창이 생성됩니다.

Python Tkinter에서 MessageBox 위치를 변경하는 방법

"Click Me" 버튼을 클릭하면 아래와 같은 대화 상자가 열리며, 코드에서 지정한 좌표(x=600, y=400)에 따라 화면의 원하는 위치에 배치됩니다.

Python Tkinter에서 MessageBox 위치를 변경하는 방법

이처럼 Toplevelgeometry 메서드를 조합하면 MessageBox의 크기와 화면상 위치를 자유롭게 제어할 수 있습니다. 좌표값을 변수로 분리해 두면 상황에 따라 동적으로 위치를 변경하는 것도 가능합니다.