본문 바로가기

코딩/파이썬 tkinter

[Tkinter] 8장. Pack

tkinter.Pack.pack

tkinter.Label을 예로 tkinter.Pack 클래스의 pack() 메서드를 사용하는 방식에 대하여 간략히 소개합니다.

 

우선 pack() 메서드에 대하여 사용 가능한 전달인자(=옵션)는 Pack 클래스의 pack_configure() 메서드 내에서 간단히 확인 가능합니다.

 

class Pack:
    """Geometry manager Pack.

    Base class to use the methods pack_* in every widget."""

    def pack_configure(self, cnf={}, **kw):
        """Pack a widget in the parent widget. Use as options:
        after=widget - pack it after you have packed widget
        anchor=NSEW (or subset) - position widget according to
                                  given direction
        before=widget - pack it before you will pack widget
        expand=bool - expand widget if parent size grows
        fill=NONE or X or Y or BOTH - fill widget if widget grows
        in=master - use master to contain this widget
        in_=master - see 'in' option description
        ipadx=amount - add internal padding in x direction
        ipady=amount - add internal padding in y direction
        padx=amount - add padding in x direction
        pady=amount - add padding in y direction
        side=TOP or BOTTOM or LEFT or RIGHT -  where to add this widget.
        """
    
    pack = configure = config = pack_configure

 

아래 표를 통해 주요하게 사용될 수 있는 옵션 및 설정값을 확인할 수 있습니다. (참고 : tkinter.constants 모듈)

 

옵션 설정값
anchor N='n' 
S='s' 
W='w' 
E='e' 
NW='nw' 
SW='sw' 
NE='ne' 
SE='se' 
NS='ns' 
EW='ew' 
NSEW='nsew' 
CENTER='center'
expand NO=FALSE=OFF= # 또는 False 
YES=TRUE=ON= # 또는 True 
fill NONE='none'
X='x'
Y='y'
BOTH='both'
side LEFT='left' 
TOP='top' 
RIGHT='right' 
BOTTOM='bottom'
padx 픽셀값
pady 픽셀값

anchor

anchor는 상위(=부모=master) 객체를 기준으로 왼쪽, 오른쪽, 위, 아래의 위치를 정의할 때 사용합니다. 아래의 코드를 예로 들면, 각 Label은 MainWin의 가로, 세로 크기를 기준으로 객체를 생성한 순서에 따라 순차적으로 화면에 표시됩니다.

 

import tkinter as tk


class MainWin(tk.Tk):
    def __init__(self, topic):
        tk.Tk.__init__(self)
        self.win_settings(topic)
        self.tkinter_ttk_basics()

    def win_settings(self, topic):
        self.title(f'tkinter / {topic}')
        self.geometry('480x320+200+200')
        self.minsize(200, 200)

    # -------------------------------------------------------------------------
    def tkinter_ttk_basics(self):
        tk.Label(self, text='팩의 효능은', relief=tk.GROOVE).pack()
        tk.Label(self, text='피부 영양 공급', relief=tk.GROOVE).pack(anchor=tk.CENTER)
        tk.Label(self, text='진정, 보습', relief=tk.GROOVE).pack(anchor=tk.W)
        tk.Label(self, text='수렴 및 청정', relief=tk.GROOVE).pack(anchor=tk.E)
    # -------------------------------------------------------------------------


if __name__ == '__main__':
    mainwin = MainWin('tkinter.Pack in tkinter widgets')
    mainwin.mainloop()

 

 

1) 첫번째로 생성한 Label 객체에 대하여 pack() 메서드 호출 시 anchor 값을 지정하지 않았는데, Lable이 가운데로 정렬됩니다.

2) 두번째 Label 객체에 대해선 anchor=tk.CENTER로 작성하니 첫번째와 동일하게 Label이 가운데로 정렬됩니다.

3) tk.W는 'west'를, tk.E는 'east'를 의미합니다.

fill & expand

아래는 anchor 포함 fill과 expand 옵션의 사용 예입니다.

 

import tkinter as tk


class MainWin(tk.Tk):
    def __init__(self, topic):
        tk.Tk.__init__(self)
        self.win_settings(topic)
        self.tkinter_ttk_basics()

    def win_settings(self, topic):
        self.title(f'tkinter / {topic}')
        self.geometry('480x320+200+200')
        self.minsize(200, 200)

    # -------------------------------------------------------------------------
    def tkinter_ttk_basics(self):
        tk.Label(self, text='참치의 공식 명칭은 다랑어', relief=tk.GROOVE).pack(anchor=tk.W, fill=tk.X)
        tk.Label(self, text='참다랑어', relief=tk.GROOVE).pack(anchor=tk.E, fill=tk.Y)
        tk.Label(self, text='눈다랑어', relief=tk.GROOVE).pack(fill=tk.BOTH, expand=True)
        tk.Label(self, text='황다랑어', relief=tk.GROOVE).pack(fill=tk.Y, expand=True)
    # -------------------------------------------------------------------------


if __name__ == '__main__':
    mainwin = MainWin('tkinter.Pack in tkinter widgets')
    mainwin.mainloop()

 

padx, pady & side

다음은 padx, pady 및 side 옵션을 설정한 예입니다.

 

import tkinter as tk


class MainWin(tk.Tk):
    def __init__(self, topic):
        tk.Tk.__init__(self)
        self.win_settings(topic)
        self.tkinter_ttk_basics()

    def win_settings(self, topic):
        self.title(f'tkinter / {topic}')
        self.geometry('480x320+200+200')
        self.minsize(200, 200)

    # -------------------------------------------------------------------------
    def tkinter_ttk_basics(self):
        tk.Label(self, text='top 1', relief=tk.GROOVE).pack(side=tk.TOP, fill=tk.BOTH, expand=tk.TRUE)
        tk.Label(self, text='top 2', relief=tk.GROOVE).pack(padx=10, pady=10, side=tk.TOP)

        tk.Label(self, text='left 1', relief=tk.GROOVE).pack(side=tk.LEFT, fill=tk.BOTH, expand=tk.TRUE)
        tk.Label(self, text='left 2', relief=tk.GROOVE).pack(padx=10, pady=10, side=tk.LEFT)

        tk.Label(self, text='right 1', relief=tk.GROOVE).pack(padx=10, pady=10, side=tk.RIGHT, fill=tk.BOTH, expand=tk.TRUE)
        tk.Label(self, text='right 2', relief=tk.GROOVE).pack(side=tk.RIGHT)

        tk.Label(self, text='bottom 1', relief=tk.GROOVE).pack(side=tk.BOTTOM, fill=tk.BOTH, expand=tk.TRUE)
        tk.Label(self, text='bottom 2', relief=tk.GROOVE).pack(padx=10, pady=10, side=tk.BOTTOM)
    # -------------------------------------------------------------------------


if __name__ == '__main__':
    mainwin = MainWin('tkinter.Pack in tkinter widgets')
    mainwin.mainloop()

 

아래 그림과 같이 side 옵션을 사용하면 위젯은 가장자리(바깥쪽)부터 배치됩니다.

 

 

'코딩 > 파이썬 tkinter' 카테고리의 다른 글

[Tkinter] 10장. Label 2단계  (0) 2020.11.08
[Tkinter] 9장. Grid  (0) 2020.11.08
[Tkinter] 7장. Geometry Manager  (0) 2020.11.07
[Tkinter] 6장. Label (ttk)  (0) 2020.11.06
[Tkinter] 5장. Label  (0) 2020.11.05