TTK笔记本选项卡关闭方法

时间:2018-04-04 08:15:26

标签: python tkinter ttk

我有一个TTK笔记本,其中标签上有关闭按钮,类似于互联网浏览器标签关闭按钮的方式,但我希望能够将自定义方法绑定到各个关闭按钮,以便我可以显示提示,如'你想在关闭之前保存吗?或者'您确定要关闭此标签吗?'取决于已关闭的选项卡。

我遇到的问题是我不确定如何为单个按钮创建自定义关闭方法,因为虽然可以使用tkMessageBox进行一般化的是/否提示,但我不确定我是怎么做的可以为每个选项卡创建特殊方法。

例如,表单会有一个个性化的方法,询问用户是否要保存所做的更改,然后调用适当的方法来保存表单,而常规选项卡可能没有与何时相关的方法完全关闭了。

我目前用于在我的标签上创建关闭按钮的代码如下:

try:
    import Tkinter as tk
    import ttk
except ImportError:  # Python 3
    import tkinter as tk
    from tkinter import ttk

class CustomNotebook(ttk.Notebook):
    """A ttk Notebook with close buttons on each tab"""
    __initialized = False

    def __init__(self, *args, **kwargs):
        if not self.__initialized:
            self.__initialize_custom_style()
            self.__inititialized = True

        kwargs["style"] = "CustomNotebook"
        ttk.Notebook.__init__(self, *args, **kwargs)

        self._active = None

        self.bind("<ButtonPress-1>", self.on_close_press, True)
        self.bind("<ButtonRelease-1>", self.on_close_release)

    def on_close_press(self, event):
        """Called when the button is pressed over the close button"""

        element = self.identify(event.x, event.y)

        if "close" in element:
            index = self.index("@%d,%d" % (event.x, event.y))
            self.state(['pressed'])
            self._active = index

    def on_close_release(self, event):
        """Called when the button is released over the close button"""
        if not self.instate(['pressed']):
            return

        element =  self.identify(event.x, event.y)
        index = self.index("@%d,%d" % (event.x, event.y))

        if "close" in element and self._active == index:
            self.forget(index)
            self.event_generate("<<NotebookTabClosed>>")

        self.state(["!pressed"])
        self._active = None

    def __initialize_custom_style(self):
        style = ttk.Style()
        self.images = (
            tk.PhotoImage("img_close", data='''
            R0lGODlhCAAIAMIBAAAAADs7O4+Pj9nZ2Ts7Ozs7Ozs7Ozs7OyH+EUNyZWF0ZWQg
            d2l0aCBHSU1QACH5BAEKAAQALAAAAAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU
            5kEJADs=
            '''),
            tk.PhotoImage("img_closeactive", data='''
            R0lGODlhCAAIAMIEAAAAAP/SAP/bNNnZ2cbGxsbGxsbGxsbGxiH5BAEKAAQALAAA
            AAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU5kEJADs=
            '''),
            tk.PhotoImage("img_closepressed", data='''
            R0lGODlhCAAIAMIEAAAAAOUqKv9mZtnZ2Ts7Ozs7Ozs7Ozs7OyH+EUNyZWF0ZWQg
            d2l0aCBHSU1QACH5BAEKAAQALAAAAAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU
            5kEJADs=
        ''')
    )

        style.element_create("close", "image", "img_close",
                        ("active", "pressed", "!disabled", "img_closepressed"),
                        ("active", "!disabled", "img_closeactive"), border=8, sticky='')
        style.layout("CustomNotebook", [("CustomNotebook.client", {"sticky": "nswe"})])
        style.layout("CustomNotebook.Tab", [
        ("CustomNotebook.tab", {
            "sticky": "nswe", 
            "children": [
                ("CustomNotebook.padding", {
                    "side": "top", 
                    "sticky": "nswe",
                    "children": [
                        ("CustomNotebook.focus", {
                            "side": "top", 
                            "sticky": "nswe",
                            "children": [
                                ("CustomNotebook.label", {"side": "left", "sticky": ''}),
                                ("CustomNotebook.close", {"side": "left", "sticky": ''}),
                            ]
                    })
                ]
            })
        ]
    })
])
if __name__ == "__main__":
    root = tk.Tk()
    notebook = CustomNotebook(width=200, height=200)
    notebook.pack(side="top", fill="both", expand=True)
    for color in ("red", "orange", "green", "blue", "violet"):
        frame = tk.Frame(notebook, background=color)
        notebook.add(frame, text=color)
    root.mainloop()

1 个答案:

答案 0 :(得分:0)

在on_close_release中打开一个tkMessageBox并检查结果:

#make sure to use 
import tkMessageBox

#[...]
        # ask the question
        result = tkMessageBox.askyesno("Really?", "Really really?")

        # check result as well
        if "close" in element and self._active == index and result:
            self.forget(index)
            self.event_generate("<<NotebookTabClosed>>")