Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Collapsible Pane (Khung thu gọn) trong Tkinter Python

Tkinter là thư viện xây dựng GUI của Python. Trong bài viết này, chúng ta sẽ thấy cách tạo một collapsible pane (khung thu gọn/mở rộng). Chúng hữu ích khi có lượng lớn dữ liệu cần hiển thị trên canvas GUI nhưng không muốn hiển thị luôn. Làm cho nó có thể thu gọn để hiển thị khi cần.

Chương trình dưới tạo collapsible pane, hiển thị kết quả cả khi mở rộng và thu gọn mũi tên. Comment trong code chỉ ra cách tiếp cận tại mỗi bước.

Ví dụ

from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter.ttk import *

class cpane(ttk.Frame):
    def __init__(self, MainWindow, expanded_text, collapsed_text):
        ttk.Frame.__init__(self, MainWindow)
        # Biến lớp
        self.MainWindow = MainWindow
        self._expanded_text = expanded_text
        self._collapsed_text = collapsed_text
        # Weight=1 để mở rộng kích thước khi cần
        self.columnconfigure(1, weight=1)
        self._variable = tk.IntVar()
        # Tạo Checkbutton
        self._button = ttk.Checkbutton(self, variable=self._variable,
            command=self._activate, style="TButton")
        self._button.grid(row=0, column=0)
        # Tạo đường kẻ ngang
        self._separator = ttk.Separator(self, orient="horizontal")
        self._separator.grid(row=0, column=1, sticky="we")
        self.frame = ttk.Frame(self)
        # Kích hoạt lớp
        self._activate()

    def _activate(self):
        if not self._variable.get():
            # Xóa widget này khi nút được nhấn
            self.frame.grid_forget()
            # Hiện text thu gọn
            self._button.configure(text=self._collapsed_text)
        elif self._variable.get():
            # Mở rộng khu vực frame theo nhu cầu
            self.frame.grid(row=1, column=0, columnspan=2)
            self._button.configure(text=self._expanded_text)

    def toggle(self):
        self._variable.set(not self._variable.get())
        self._activate()

# Tạo cửa sổ gốc
root = Tk()
root.geometry('300x300')

# Tạo đối tượng Collapsible Pane Container
cpane_obj = cpane(root, 'Close Me', 'Open Me!')
cpane_obj.grid(row=0, column=0)

# Nút xuất hiện trong collapsible pane
b = Button(cpane_obj.frame, text=" Frame Expanded").grid(row=1, column=2, pady=20)
b = Checkbutton(cpane_obj.frame, text="Hi There ! How are you doing?").grid(row=3, column=4, pady=20)

mainloop()

Kết quả

Chạy đoạn code trên cho kết quả sau:

Collapsible Pane (Khung thu gọn) trong Tkinter Python

Collapsible Pane (Khung thu gọn) trong Tkinter Python