Tkinter菜单栏类

2024-04-20 12:58:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图通过创建一个菜单栏及其内容的类来提高代码的效率。没有错误被报告,但它不会成功。(我确实让它不用上课就可以工作了,但似乎不能再让它工作了!)在

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窗口,但没有菜单栏选项,我哪里出错了? 干杯。在


Tags: theselfadddeflabelcommandtkdrop
1条回答
网友
1楼 · 发布于 2024-04-20 12:58:56

__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()

相关问题 更多 >