Tkinter Python 中的可折叠面板
Tkinter 是 Python 的 GUI 构建库。在本文中,我们将看到如何创建可折叠面板。当我们需要在GUI画布上显示大量数据但不希望一直显示时,它们非常有用。它是可折叠的,因此可以在需要时显示。
下面的程序创建了可折叠面板,我们可以在展开和折叠箭头后看到结果。代码注释指出了我们在每个步骤中采取的方法。
示例
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)
# 类变量
self.MainWindow = MainWindow
self._expanded_text = expanded_text
self._collapsed_text = collapsed_text
# Weight=1 可根据需要增大大小
self.columnconfigure(1, weight=1)
self._variable = tk.IntVar()
# 创建 Checkbutton
self._button = ttk.Checkbutton(self, variable=self._variable,
command=self._activate, style="TButton")
self._button.grid(row=0, column=0)
# 创建横线
self._separator = ttk.Separator(self, orient="horizontal")
self._separator.grid(row=0, column=1, sticky="we")
self.frame = ttk.Frame(self)
# 激活类
self._activate()
def _activate(self):
if not self._variable.get():
# 按下按钮后删除此 widget。
self.frame.grid_forget()
# 显示折叠文字
self._button.configure(text=self._collapsed_text)
elif self._variable.get():
# 根据需要增加框架区域
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()
# 创建根窗口或 MainWindow
root = Tk()
root.geometry('300x300')
# 创建可折叠面板容器的对象
cpane_obj = cpane(root, '关闭', '展开')
cpane_obj.grid(row=0, column=0)
# 出现在可折叠面板上的按钮
b = Button(cpane_obj.frame, text="扩展的框架").grid(
row=1, column=2, pady=20)
b = Checkbutton(cpane_obj.frame, text="你好! 最近过得怎么样?").grid(
row=3, column=4, pady=20)
mainloop()
Python
输出
运行上面的代码会给我们以下结果 –