为在python中使用tkinter创建的子框架创建“关闭/退出”选项

时间:2016-02-23 19:57:54

标签: python tkinter tcl

我使用tkinter创建了一个脚本,当你按下按钮时会调出一个子帧。框架占据了我的Mac笔记本电脑的全屏尺寸。现在我需要创建一个退出/关闭这个新框架的选项。这样做的最佳选择是什么?

-Thanks

from Tkinter import *
import tkFont
class App(Frame):
  def __init__(self, *args, **kwargs):
    Frame.__init__(self, *args, **kwargs)
    self.apple = Button(self,
                     text="Apple", command=self.write_apple)
    self.apple.pack(side=LEFT)

def write_apple(self):
    self.customFont = tkFont.Font(family="Helvetica", size=80)
    t = Toplevel(self)
    t.overrideredirect(True)
    t.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
    l = Label(t, text="This is a green apple.",font=self.customFont)
    l.pack(side="top", fill="both", expand=True)

if __name__ == "__main__":
    root = Tk()
    main = App(root)
    main.pack(side="top", fill="both", expand=True)
    root.mainloop()

1 个答案:

答案 0 :(得分:0)

此解决方案处理创建Toplevel的多个实例的情况:

from Tkinter import *
import tkFont
class App(Frame):
    def __init__(self, *args, **kwargs):
        Frame.__init__(self, *args, **kwargs)
        self.apple = Button(self,
                            text="Apple", command=self.write_apple)
        self.apple.pack(side=LEFT)
        self.top_dict = dict()

    def destroy_top(self, event):
        # event.widget is the instance of Label that was clicked
        # Get the instance of Toplevel
        top = self.top_dict[event.widget]
        # Destroy the instance of Toplevel
        top.destroy()
        # Remove the instance of Toplevel from the list
        del self.top_dict[event.widget]

    def write_apple(self):
        self.customFont = tkFont.Font(family="Helvetica", size=80)
        # Create an instance of Toplevel
        top = Toplevel(self)
        top.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
        label = Label(top, text="This is a green apple.",font=self.customFont)
        label.pack(side="top", fill="both", expand=True)
        # Bind the destroy_top method to the mouse-button-1 click
        label.bind('<Button-1>', self.destroy_top)
        # Save the instance of Toplevel using the label as the key
        self.top_dict[label] = top

if __name__ == "__main__":
    root = Tk()
    main = App(root)
    main.pack(side="top", fill="both", expand=True)
    root.mainloop()

注意:正如@Bryan Oakley所说,删除对overrideredirect的调用会向Toplevel的实例添加窗口装饰。