본문 바로가기

코딩/파이썬 tkinter

[Tkinter] 5장. Label

tkinter.Label

A label is a widget that displays a textual string, bitmap or image.

 

tkinter.Label에 대한 여러 참고 설명이 있겠으나 본 글은 Tcl Developr Xchange 사이트에서의 설명 일부를 인용합니다.

 

tkinter가 제공하는 위젯 중 하나인 tkinter.Label을 통해 텍스트나 이미지를 화면에 표시할 수 있습니다.

 

Steve Jobs, 1976년 스티브 워즈니악, 로널드 웨인과 함께 애플을 창업하다. (이미지 출처: apple.com)

import tkinter as tk


class MainWin(tk.Tk):
    def __init__(self, topic):
        # super().__init__()
        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='You can\'t connect the dots looking forward.').pack()
        tk.Label(self, text='You can only connect them looking backwards.').pack()
        self.image = tk.PhotoImage(file='data/Steve Jobs.png')
        tk.Label(self, image=self.image).pack()
    # -------------------------------------------------------------------------


if __name__ == '__main__':
    mainwin = MainWin('tkinter.Label')
    mainwin.mainloop()

 

1) tkinter.Label 클래스의 생성자 및 전달인자에 대한 설명은 아래와 같습니다. 여러 옵션 중 text를 통해 화면에 표시할 문자열을 정하게 됩니다.

 

class Label(Widget):
    """Label widget which can display text and bitmaps."""

    def __init__(self, master=None, cnf={}, **kw):
        """Construct a label widget with the parent MASTER.

        STANDARD OPTIONS

            activebackground, activeforeground, anchor,
            background, bitmap, borderwidth, cursor,
            disabledforeground, font, foreground,
            highlightbackground, highlightcolor,
            highlightthickness, image, justify,
            padx, pady, relief, takefocus, text,
            textvariable, underline, wraplength

        WIDGET-SPECIFIC OPTIONS

            height, state, width

        """

 

2) 첫번째 전달인자인 master는 parent라고도 설명하는 글들이 있는데, parent=self로 코드를 작성하면 제 경우엔 오류가 납니다.

 

tk.Label(parent=self, text='You can\'t connect the dots looking forward.').pack()  # --> error
tk.Label(master=self, text='You can\'t connect the dots looking forward.').pack()  # --> okay

 

3) tkinter.Label 생성 시 전달인자 image에 바로 tk.PhotoImage를 전달하면 될 듯하나 제대로 실행되지 않아 self.image 속성(변수)을 사전에 생성합니다. local 변수(self 없이 image 만)도 제대로 동작하지 않고요.

 

tk.Label(self, image=tk.PhotoImage(file='data/Steve Jobs.png')).pack()  # --> not working

image = tk.PhotoImage(file='data/Steve Jobs.png')  # --> not working
tk.Label(self, image=image).pack()                 # --> not working

 

4) 화면에서 구성 요소의 위치를 지정하는 Pack 클래스의 pack(속성이면서 메서드인)은 다른 글에서 다루고자 합니다.