Tkinter菜单班

时间:2016-02-06 18:45:13

标签: python python-2.7 tkinter

我正在尝试通过创建菜单栏及其内容的类来提高我的代码效率。没有报告错误,但它不会成为障碍。 (我确实让它在没有上课的情况下工作,但似乎无法让它再次工作!)

from Tkinter import *

class MenuBar: #'player' is the name of the Tk window
    def __init__(self, menuname, Label, Drop_Label, Command, Separator = False):
        self.menubar = Menu(player)
        self.menuname = Menu(self.menubar, tearoff = 0)
        self.menuname.add_command(label = Label, command = Command)

        if Separator == True:
            self.menuname.add_separator()

        self.menubar.add_cascade(label = Drop_Label, menu = menuname)

        self.Create()

    def Create(self):
        player.config(menu = self.menubar)

#example menu item
def addMenuBar():
    exitMenu = MenuBar("filemenu", "Exit", "File", onExit, True)
    #More menu items here, function to keep it tidier.

def onExit():
    #Code here

player = Tk()

addMenuBar()

player.mainloop()

这确实绘制了Tk窗口,但没有菜单栏选项,我哪里错了? 欢呼声。

1 个答案:

答案 0 :(得分:1)

__init__功能中,只需创建一个菜单栏 创建一个函数,添加菜单并接受命令作为元组列表:

from Tkinter import *

class MenuBar: #'player' is the name of the Tk window
    def __init__(self, parent):
        self.menubar = Menu(parent)
        self.Create()

    def Create(self):
        player.config(menu = self.menubar)

    def add_menu(self, menuname, commands):
        menu = Menu(self.menubar, tearoff = 0)

        for command in commands:
            menu.add_command(label = command[0], command = command[1])
            if command[2]:
                menu.add_separator()

        self.menubar.add_cascade(label=menuname, menu=menu)

def onExit():
    import sys
    sys.exit()

def onOpen():
    print 'Open'

player = Tk()

menubar = MenuBar(player)

fileMenu = menubar.add_menu("File", commands = [("Open", onOpen, True), ("Exit", onExit, False)])

player.mainloop()