我有一个可以添加菜单栏的可运行应用程序。我已经尝试过在Stackoverflow上其他问题中显示的几种方法,但没有找到有效的解决方案。
我尝试将MenuBar设置为自己的类,将菜单栏代码添加到MainWindow类,将菜单栏定义为函数并将其称为Mainwindow方法。所有想法都来自其他帖子。
# This class defines the Main Window of my working app
class MainWindow(Frame,Menu):
def __init__(self, master):
Frame.__init__(self, master)
self.menubar=MenuBar(self)
self.openButton = Button(self, text="Open", command=self.opencallback)
self.openButton.pack(side=LEFT)
self.fileEntry = Entry(self)
self.fileEntry.pack(side=RIGHT)
self.fileName = None
self.AnalyzeButton = Button(self, text="Analyze", command=self.analyzeCallback)
self.AnalyzeButton.pack(side=LEFT)
self.QuitButton = Button(self, text="Quit", command=self.closeAll)
self.QuitButton.pack(side=RIGHT)
# This class defines how I would like the Menu to look when it appears in the Main application window
class MenuBar(Menu):
def __init__(self, parent):
Menu.__init__(self, parent)
fileMenu = Menu(self, tearoff=False)
self.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="Exit", command=quit)
toolMenu = Menu(self, tearoff=False)
self.add_cascade(label="Tools", menu=toolMenu)
toolMenu.add_command(label="Extract Instructions", command=None)
我希望菜单栏出现在MainWindow的顶部,并带有两个下拉菜单File和Tools。到目前为止,我已经能够自行生成MainWindow(无菜单)和Menu(其本身是空白tk窗口)
答案 0 :(得分:0)
对我来说还不错,只是您没有告诉根窗口有关菜单的信息。请参阅我的示例,__init__()
的最后一行:
from tkinter import * # For Ptyhon 2.7 use Tkinter instead
class MainWindow(Frame):
def __init__(self, master=None):
self.master = master
Frame.__init__(self, master)
self.master.geometry('300x200')
self.pack(fill='both', expand='yes')
self.menubar = MenuBar(self)
self.master.config(menu=self.menubar) # Tell root about the menu
def menu_callback_stop(self):
print('Exit')
def menu_callback_extract(self):
print('Extract Instructions')
class MenuBar(Menu):
def __init__(self, parent):
Menu.__init__(self, parent)
fileMenu = Menu(self, tearoff=False)
self.add_cascade(label="File", menu=fileMenu)
fileMenu.add_command(label="Exit", command=parent.menu_callback_stop)
toolMenu = Menu(self, tearoff=False)
self.add_cascade(label="Tools", menu=toolMenu)
toolMenu.add_command(label="Extract Instructions",
command=parent.menu_callback_extract)
if __name__ == '__main__':
root = Tk()
app = MainWindow(root)
root.mainloop()
我向MainWindow
实例添加了回调。