웹사이트 검색

고급 Tkinter: 클래스 작업


오늘 우리는 Tkinter에서 수업을 할 것입니다. 이전에 Tkinter로 작업한 적이 있다면 응용 프로그램을 만드는 데 사용할 수 있는 GUI 기능이 많이 있다는 것을 알고 있을 것입니다.

그러나 응용 프로그램을 만들면서 눈에 보이는 것보다 모듈에 더 많은 것이 있다는 것을 금방 깨닫게 됩니다.

tkinter에는 숨겨진 기능이 많이 있는데 그 중 하나가 모듈에서 클래스를 사용하는 방법입니다.

Tkinter 모듈 설정

tkinter 모듈은 표준 Python 라이브러리의 일부이므로 모듈을 설치할 필요가 없습니다.

다만, 이 글은 tkinter 모듈의 약간 고급 형태를 다룰 예정이므로 초급 시리즈로 진행하는 것을 추천한다.

따라서 계속 진행하기 전에 여기에서 TKinter의 기본 자습서를 읽는 것을 잊지 마십시오.

  • Tkinter 파트 - 1
  • Tkinter 파트 - 2
  • Tkinter 파트 - 3

기본 튜토리얼을 마쳤으면 tkinter 모듈 작업을 시작하겠습니다.

클래스로 작업하려면 tkinter 모듈을 가져와야 합니다.

# Importing the tkinter module
import tkinter as tk

# Used for styling the GUI
from tkinter import tkk

또한 사용 편의성을 위해 ttk 패키지를 별도로 가져올 것입니다.

Tkinter에서 클래스 작업

Tkinter에서 클래스로 작업하는 방법을 이해합시다. 응용 프로그램이 작동하는 방식은 매우 간단합니다.

먼저 루트 창을 만들고 그 위에 단일 프레임을 배치합니다.

다른 창이 있는 응용 프로그램처럼 보이도록 한 프레임에서 다른 프레임으로 전환하는 기능도 만들 것입니다.

이는 사용자에게 다른 창/탭으로 리디렉션되고 있다는 착각을 주지만 실제로는 프레임 사이를 전환할 뿐입니다.

작업할 프레임은 MainPage, SidePageCompletionScreen입니다.

이들 사이를 전환하는 데 사용할 메서드는 show_frame() 메서드입니다.

코드 작업

시작하기 위해 다른 모든 클래스/프레임에 액세스할 기본 클래스를 만들어 봅시다.

# Allowing us to extend from the Tk class
class testClass(tk.Tk):

tk.Tk 클래스에서 확장하면 Tk() 클래스에 있는 구성 요소로 작업할 수 있습니다.

1. 클래스 초기화

클래스를 초기화하기 위해 __init__ 함수를 사용합니다. 이렇게 하면 클래스에서 개체를 형성할 때 자체적으로 실행되는 메서드가 생성됩니다.

비슷한 방식으로 tk.Tk __init__을 통해서도 클래스를 초기화하고 있습니다.

import tkinter as tk
from tkinter import ttk

class windows(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        # Adding a title to the window
        self.wm_title("Test Application")

        # creating a frame and assigning it to container
        container = tk.Frame(self, height=400, width=600)
        # specifying the region where the frame is packed in root
        container.pack(side="top", fill="both", expand=True)

        # configuring the location of the container using grid
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        # We will now create a dictionary of frames
        self.frames = {}
        # we'll create the frames themselves later but let's add the components to the dictionary.
        for F in (MainPage, SidePage, CompletionScreen):
            frame = F(container, self)

            # the windows class acts as the root window for the frames.
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")

        # Using a method to switch frames
        self.show_frame(MainPage)

2. 뷰 프레임 전환 방법 생성

이제 __init__를 생성하고 사용할 프레임도 지정했으므로 보고 있는 프레임을 전환하는 메서드를 생성할 수 있습니다.

    def show_frame(self, cont):
        frame = self.frames[cont]
        # raises the current frame to the top
        frame.tkraise()

3. 프레임에 대한 여러 클래스 만들기

이제 show_frame() 메서드를 사용하여 전환되는 프레임 역할을 하는 다양한 클래스를 만듭니다.

class MainPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Main Page")
        label.pack(padx=10, pady=10)

        # We use the switch_window_button in order to call the show_frame() method as a lambda function
        switch_window_button = tk.Button(
            self,
            text="Go to the Side Page",
            command=lambda: controller.show_frame(SidePage),
        )
        switch_window_button.pack(side="bottom", fill=tk.X)


class SidePage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="This is the Side Page")
        label.pack(padx=10, pady=10)

        switch_window_button = tk.Button(
            self,
            text="Go to the Completion Screen",
            command=lambda: controller.show_frame(CompletionScreen),
        )
        switch_window_button.pack(side="bottom", fill=tk.X)


class CompletionScreen(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Completion Screen, we did it!")
        label.pack(padx=10, pady=10)
        switch_window_button = ttk.Button(
            self, text="Return to menu", command=lambda: controller.show_frame(MainPage)
        )
        switch_window_button.pack(side="bottom", fill=tk.X)

알아차리셨다면 이러한 클래스는 self.frames 변수를 사용하여 기본 클래스에 추가됩니다.

__name__==\main\에서 클래스를 구현하는 명령을 유지하지만 직접 사용할 수도 있습니다.

if __name__ == "__main__":
    testObj = windows()
    testObj.mainloop()

앞으로 나아가 다

이제 클래스와 메서드 정의를 완료했으며 이 스크립트를 실행할 수 있습니다.

이렇게 하면 버튼 클릭으로 프레임 사이를 전환할 수 있는 작은 창이 나타납니다.

더 높은 수준에서는 응용 프로그램 상단의 메뉴 표시줄에서 프레임 간에 전환하는 기능을 가질 수도 있습니다.

결론

tkinter 모듈의 클래스로 작업하면 새 애플리케이션을 만들고 작업할 수 있는 많은 문이 열립니다.

우리는 오늘 꽤 많은 코드 작업을 했고, 그래서 우리는 같은 페이지에 있습니다. 요점은 다음과 같습니다!

라이브 예제를 보려면 내 프로젝트 SQLite3를 확인하십시오.

참조

  • Tkinter 문서
  • Tkinter 클래스