【问题标题】:Class menu in Tkinter GuiTkinter Gui 中的课程菜单
【发布时间】:2011-04-01 00:48:47
【问题描述】:

我正在开发一个 Gui,我想知道是否可以在我的脚本中将窗口的菜单属性作为一个单独的类,以获得更清晰和更易于增强的代码。

我目前的代码是:

class Application(Frame):
   """ main window application """
   def __init__(self, boss = None):
   (...)
   self.menu = Menu(self)
   self.master.config(menu = self.menu)

   self.select = Menu(self.menu)
   self.menu.add_cascade(label = 'Select', menu = self.select)
   self.select.add_command(label = 'Select all', command = self.select_all)
   ...

我更喜欢类似的东西:

class MenuBar:

    # all the content of the menu here

class Application(Frame):
   (...)
   self.menu = MenuBar(self) ?

rgds,

【问题讨论】:

    标签: python user-interface class menu tkinter


    【解决方案1】:

    是的,有可能:

    import tkinter as tk
    # import Tkinter as tk  # if using python 2
    import sys
    
    class MenuBar(tk.Menu):
        def __init__(self, parent):
            tk.Menu.__init__(self, parent)
    
            fileMenu = tk.Menu(self, tearoff=False)
            self.add_cascade(label="File",underline=0, menu=fileMenu)
            fileMenu.add_command(label="Exit", underline=1, command=self.quit)
    
        def quit(self):
            sys.exit(0)
    
    class App(tk.Tk):
        def __init__(self):
            tk.Tk.__init__(self)
            menubar = MenuBar(self)
            self.config(menu=menubar)
    
    if __name__ == "__main__":
        app=App()
        app.mainloop()
    

    【讨论】:

    • 您好,不,它不起作用:我收到错误消息“AttributeError: MenuBar instance has no attribute 'master'”。
    猜你喜欢
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-04
    • 1970-01-01
    相关资源
    最近更新 更多