Пример #1
0
def AppendMenu(mbar, text, menu_list):
    button = Menubutton(mbar, text = text)
    button.pack(side = LEFT)

    menu = UpdatedMenu(button, menu_list)
    button.menu = menu
    button['menu'] = menu.menu
    return menu
Пример #2
0
def AppendMenu(mbar, text, menu_list):
    button = Menubutton(mbar, text = text)
    button.pack(side = LEFT)

    menu = UpdatedMenu(button, menu_list)
    button.menu = menu
    button['menu'] = menu.menu
    return menu
Пример #3
0
 def __init__(self, parent=None):
     Frame.__init__(self, borderwidth=2)
     button_file = Menubutton(self, text="File")
     menu_file = Menu(button_file)
     menu_file.add_command(label="New", command=parent.new)
     menu_file.add_command(label="Save", command=parent.save)
     menu_file.add_command(label="Exit", command=parent.exit)
     button_file.configure(menu=menu_file)
     button_file.pack()
Пример #4
0
    def __init__(self, parent=None):
         Frame.__init__(self, borderwidth=2)
         mButtonFile = Menubutton(self, text="Fichier")
         mButtonFile.pack()
         menuFile = Menu(mButtonFile)

         menuFile.add_command(label="Quitter", command=parent.quit)
         menuFile.add_command(label="Sauvegarder", command=parent.save)
         mButtonFile.configure(menu=menuFile)
Пример #5
0
 def __init__(self, master=None):
     Frame.__init__(self, borderwidth=2)
     self.master = master
     button_file = Menubutton(self, text="Fichier", bg="white")
     button_file.pack(side="left")
     menu_file = Menu(button_file)
     menu_file.add_command(label='Effacer',
                           underline=0,
                           command=self.master.delete_circle)
     menu_file.add_command(label='Afficher',
                           underline=0,
                           command=self.master.create_circle)
     menu_file.add_command(label='Terminer',
                           underline=0,
                           command=self.master.quit)
     button_file.configure(menu=menu_file)
Пример #6
0
    def __init__(self,parent=None, width = 800, height = 50):
        """
        Initialise / crée le menu
        """
        Frame.__init__(self,borderwidth=2)

        #Vars
        self.parent = parent
        self.fileOpened = None

        mbuttonFile = Menubutton(self,text='Fichier')
        #mbuttonFile.grid(row=0, column=0)
        mbuttonFile.pack(side=LEFT)
        menuFile=Menu(mbuttonFile)
        menuFile.add_command(label='Nouveau',command=self.new)
        menuFile.add_separator()
        menuFile.add_command(label='Sauvegarder',command=self.save)
        menuFile.add_command(label='Sauvegarder sous...',command=self.saveAs)
        menuFile.add_command(label='Charger...',command=self.load)
        menuFile.add_separator()

        #Search for an exit function on the parent, or take the default one from MenuBar class if not found
        try:
            menuFile.add_command(label='Quitter',command=self.parent.exit)
        except AttributeError:
            menuFile.add_command(label='Quitter',command=self.exit)
            
        mbuttonFile.configure(menu=menuFile)

        mbuttonHelp = Menubutton(self,text='Aide')
        #mbuttonHelp.grid(row=0, column=1)
        mbuttonHelp.pack(side=RIGHT)
        menuHelp = Menu(mbuttonHelp)
        menuHelp.add_command(label='Aide',command=self.infos)
        menuHelp.add_command(label='A propos',command=self.aPropos)
        mbuttonHelp.configure(menu=menuHelp)

        # define options for opening or saving a file
        self.file_opt = options = {}
        options['defaultextension'] = '.txt'
        options['filetypes'] = [('text files', '.txt'),('all files', '.*')]
        options['initialdir'] = 'C:\\'
        options['initialfile'] = 'save.txt'
        options['parent'] = parent
        options['title'] = 'Choissisez le fichier'
Пример #7
0
    def __init__(self, parent=None):
        Frame.__init__(self, borderwidth=2)
        mbuttonFile = Menubutton(self, text="Fichier")
        mbuttonFile.pack(side="left")
        menuFile = Menu(mbuttonFile)
        menuFile.add_command(label="Sauvegarder", command=parent.save)
        menuFile.add_command(label="Charger", command=parent.load)

        menuFile.add_command(label="Quitter", command=parent.quitter)
        mbuttonFile.configure(menu=menuFile)

        mbuttonFileBis = Menubutton(self, text="?")

        menuFileBis = Menu(mbuttonFileBis)
        menuFileBis.add_command(label="A propos", command=parent.about)
        mbuttonFileBis.configure(menu=menuFileBis)

        mbuttonFileBis.pack(side="left")
Пример #8
0
def AppendMenu(mbar, text, menu_list, underline):
	theme = app.uimanager.currentColorTheme
#	button = TMenubutton(mbar, text = text, underline=underline, style='RootMenuButton')
	button = Menubutton(mbar, text=text, underline=underline)
	button['background'] = theme.bg
	button['foreground'] = theme.foreground
	button['activebackground'] = theme.menuselectbackground
	button['activeforeground'] = theme.selectforeground
	button['relief'] = 'flat'
	button['highlightbackground'] = theme.menuselectbackground
	button['highlightcolor'] = theme.menuselectforeground
	button['highlightthickness'] = 0
	button['bd'] = 0
	button.pack(side=LEFT, padx=2, pady=0)

	menu = UpdatedMenu(button, menu_list)
	button.menu = menu
	button['menu'] = menu.menu
	return menu
Пример #9
0
def AppendMenu(mbar, text, menu_list, underline):
    theme = app.uimanager.currentColorTheme
    #	button = TMenubutton(mbar, text = text, underline=underline, style='RootMenuButton')
    button = Menubutton(mbar, text=text, underline=underline)
    button['background'] = theme.bg
    button['foreground'] = theme.foreground
    button['activebackground'] = theme.menuselectbackground
    button['activeforeground'] = theme.selectforeground
    button['relief'] = 'flat'
    button['highlightbackground'] = theme.menuselectbackground
    button['highlightcolor'] = theme.menuselectforeground
    button['highlightthickness'] = 0
    button['bd'] = 0
    button.pack(side=LEFT, padx=2, pady=0)

    menu = UpdatedMenu(button, menu_list)
    button.menu = menu
    button['menu'] = menu.menu
    return menu
Пример #10
0
    def __init__(self, parent):
        Frame.__init__(self, borderwidth=2)
        self.parent = parent

        # File Button Menu
        button_file = Menubutton(self, text="Fichier")
        menu_file = Menu(button_file)
        menu_file.add_command(label="Nouveau", command=self.parent.new)
        menu_file.add_command(label="Ouvrir", command=self.parent.open)
        menu_file.add_command(label="Sauvegarder", command=self.parent.save)
        menu_file.add_command(label="Quitter", command=self.parent.exit)
        button_file.configure(menu=menu_file)
        button_file.pack(side=LEFT, fill="x")

        # Help Button Menu
        button_file = Menubutton(self, text="Aide")
        menu_help = Menu(button_file)
        menu_help.add_command(label="A propos de nous",
                              command=self.parent.help)
        button_file.configure(menu=menu_help)
        button_file.pack(side=LEFT)
Пример #11
0
    def __init__(self, parent=None):
        Frame.__init__(self, borderwidth=2)
        self.parent = parent

        mbuttonFile = Menubutton(self, text="Fichier")
        mbuttonPlus = Menubutton(self, text="Plus")
        mbuttonQuit = Menubutton(self, text="Quitter")

        mbuttonFile.pack(side="left")
        mbuttonPlus.pack(side="left")
        mbuttonQuit.pack(side="left")

        menuFile = Menu(mbuttonFile)
        menuFile.add_command(label="Enregistrer Default",
                             command=self.defaultSave)
        menuFile.add_command(label="Enregistrer", command=self.save)
        menuFile.add_command(label="Charger Default", command=self.defaultLoad)
        menuFile.add_command(label="Charger Choix", command=self.load)

        menuPlus = Menu(mbuttonPlus)
        menuPlus.add_command(label="Infos", command=self.showInfos)

        menuQuit = Menu(mbuttonQuit)
        menuQuit.add_command(label="Quitter", command=parent.quit)
        menuQuit.add_command(label="Quitter avec confirmation",
                             command=self.confirmQuit)

        mbuttonFile.configure(menu=menuFile)
        mbuttonPlus.configure(menu=menuPlus)
        mbuttonQuit.configure(menu=menuQuit)
Пример #12
0
    def __init__(self, parent=None):
        Frame.__init__(self, borderwidth=2)
        mbuttonFile = Menubutton(self, text="Fichier")
        mbuttonFile.pack(side="left")
        menuFile = Menu(mbuttonFile)
        menuFile.add_command(label="Sauvegarder",
                             command=parent.save)
        menuFile.add_command(label="Charger",
                             command=parent.load)
        
        menuFile.add_command(label="Quitter",
                             command=parent.quitter)
        mbuttonFile.configure(menu=menuFile)

        mbuttonFileBis = Menubutton(self, text="?")

        menuFileBis = Menu(mbuttonFileBis)
        menuFileBis.add_command(label="A propos",
                                command=parent.about)
        mbuttonFileBis.configure(menu = menuFileBis)

        mbuttonFileBis.pack(side="left")
Пример #13
0
    def __init__(self, parent=None):
        Frame.__init__(self, bg='green', borderwidth=2)
        file_button = Menubutton(self, text="File")
        file_button.pack(side="left")
        file_menu = Menu(file_button)
        file_button.configure(menu=file_menu)

        file_menu.add_command(label='Save',
                              underline=0,
                              command=parent.file_save)
        # file_menu.add_command(label='Quit', underline=0,
        #                     command=parent.destroy)
        file_menu.add_command(label='Quit',
                              underline=0,
                              command=parent.file_quit)

        edit_button = Menubutton(self, text="Edit")
        edit_button.pack(side="left")
        edit_menu = Menu(edit_button)
        edit_button.configure(menu=edit_menu)

        edit_menu.add_command(label='Hide',
                              underline=0,
                              command=parent.delete_circle)
        edit_menu.add_command(label='Show',
                              underline=0,
                              command=parent.create_circle)

        help_button = Menubutton(self, text="Help")
        help_button.pack(side="right")
        help_menu = Menu(help_button)
        help_button.configure(menu=help_menu)

        help_menu.add_command(label='About Us',
                              underline=0,
                              command=parent.help_us)
        help_menu.add_command(label='About TkInter',
                              underline=0,
                              command=parent.help_tkinter)
Пример #14
0
class ClsWinMain(Tk):
    """
    Главное окно программы.
    """
    def __init__(self, root=None):
        """
        Создание главного окна прогарммы.
        :param root:
        :return:
        """
        def create_self():
            """
            Создание самого окна.
            :return:
            """
            def create_frm_btn():
                """
                Создание кнопок на главном окне.
                :return:
                """
                # укорочение ссылки
                control = self.__root.control
                # нижний фрейм главного окна
                self.frm_btn = Frame(self, border=3, relief='sunken')
                self.frm_btn.pack(side='bottom', fil='x')

                # кнопка "шаг" главного окна
                self.btn_step = Button(self.frm_btn,
                                       text='Step >',
                                       command=control.win_main_step_cpu)
                self.btn_step.pack(side='left')

                # кнопка "Отлдака" главного окна
                self.btn_debug = Button(self.frm_btn,
                                        text='Debug >>',
                                        command=control.win_main_debug)
                self.btn_debug.pack(side='left')

                # кнопка "выход" главного окна
                self.btn_exit = Button(self.frm_btn,
                                       text='Exit [X]',
                                       command=control.exit)
                self.btn_exit.pack(side='right')

                # кнопка для показа экрана виртуального компьютера
                self.btn_show_screen = Button(self.frm_btn,
                                              text='PC Screen',
                                              command=control.show_screen)
                self.btn_show_screen.pack(side='left')

                # кнопка для сброса виртуального компьютера
                self.btn_reset = Button(self.frm_btn,
                                        text='Reset (x)',
                                        command=control.reset_pc)
                self.btn_reset.pack(side='left')

            def create_menu():
                """
                Создание менб для главного окна.
                :return:
                """
                def create_mnu_file():
                    """
                    Создание меню "Файл".
                    :return:
                    """
                    # добавление менюхи файл
                    self.mbt_file = Menubutton(self.frm_menu, text='File',
                                               relief='raised', border=3)
                    self.mbt_file.pack(side='left')

                def create_mnu_edit():
                    """
                    Создание меню "Правка".
                    :return:
                    """
                    # добавление менюхи правка
                    self.mbt_edit = Menubutton(self.frm_menu, text='Edit',
                                               relief='raised', border=3)
                    self.mbt_edit.pack(side='left')

                def create_mnu_custom():
                    """
                    Создание меню "Настройки".
                    :return:
                    """
                    # добавление менюхи настройка
                    self.mbt_custom = Menubutton(self.frm_menu, text='Custom',
                                                 relief='raised', border=3)
                    self.mbt_custom.pack(side='left')

                    self.mnu_custom = Menu(self.mbt_custom)
                    self.mnu_custom.add_command(
                        label=self.lang['win_main_mbt_edit_bp'],
                        accelerator='F11',
                        command=self.__root.control.show_win_edit_bp)
                    self.mnu_custom.add_separator()
                    self.mnu_custom.add_command(
                        label=self.lang['win_main_mbt_edit_disk'],
                        accelerator='F12',
                        command=self.__root.control.show_win_idc)

                    self.mbt_custom.config(menu=self.mnu_custom)

                def create_mnu_help():
                    """
                    Создание меню "Помощь".
                    :return:
                    """
                    # добавление менюхи справка
                    self.btm_help = Menubutton(self.frm_menu,
                                               text=self.lang[
                                                   'win_main_mbt_help_name'],
                                               relief='raised',
                                               border=3)
                    self.btm_help.pack(side='right')

                    self.mnu_help = Menu(self.btm_help)
                    self.mnu_help.add_command(
                        label=self.lang['win_main_mbt_help_help'],
                        accelerator='F1')
                    self.mnu_help.add_separator()
                    self.mnu_help.add_command(
                        label=self.lang['win_main_mbt_help_about'],
                        accelerator='Ctrl-F1', command=self.__root.control.about)

                    self.btm_help.config(menu=self.mnu_help)

                # фрейм меню (в верхней части)
                self.frm_menu = Frame(self, border=3, relief='sunken')
                self.frm_menu.pack(side='top', fil='x')

                create_mnu_file()
                create_mnu_edit()
                create_mnu_custom()
                create_mnu_help()

            def create_frm_cpu():
                """
                Создание ырема для отображения состояния ЦП.
                :return:
                """
                self.frm_cpu = ClsFrmCPU(root=self)

            Tk.__init__(self)
            self.minsize(320, 400)
            self.after(100, self.win_update)

            create_frm_btn()
            create_menu()
            create_frm_cpu()

        self.__root = root
        self.lang = root.res.lang_str.lang_dict
        self.btn_debug = None
        self.frm_cpu = None
        self.btn_reset = None
        self.mbt_edit = None
        self.btm_help = None
        self.mbt_file = None
        self.btn_step = None
        self.mnu_custom = None
        self.frm_menu = None
        self.btn_show_screen = None
        self.frm_button = None
        self.btn_exit = None
        self.mbt_custom = None
        self.frm_btn = None
        self.mnu_help = None

        create_self()

    def win_update(self):
        """
        Обновление окна по таймеру.
        :return:
        """
        self.__root.logic.update_monitor()
        self.after(100, self.win_update)

    def begin(self):
        """
        В целях ухода от конфликтов имён пришлось назвать вот так ))).
        """
        self.mainloop()

    def win_exit(self):
        """
        При закрытии главного окна -- завершается всё приложение.
        :return:
        """
        self.destroy()
Пример #15
0
class lightingPanel(AppShell):
    #################################################################
    # lightingPanel(AppShell)
    # This will create a window to let user
    # create any kinds of lighting into the scene
    #################################################################
    # Override class variables
    appname = 'Lighting Panel'
    frameWidth = 400
    frameHeight = 400
    currentLight = None

    def __init__(self, lightList, parent=None, **kw):
        self.lightList = lightList
        self.lightColor = [0.3 * 255, 0.3 * 255, 0.3 * 255]
        self.type = ''
        INITOPT = Pmw.INITOPT
        optiondefs = (('title', self.appname, None), )
        self.defineoptions(kw, optiondefs)

        # Initialize the superclass
        AppShell.__init__(self)

        # Execute option callbacks
        self.initialiseoptions(lightingPanel)

        self.parent.resizable(
            False, False)  ## Disable the ability to resize for this Window.

    def createInterface(self):
        # Handle to the toplevels interior
        interior = self.interior()
        menuBar = self.menuBar
        self.menuBar.destroy()

        # Create a frame to hold all stuff
        mainFrame = Frame(interior)

        self.listZone = Pmw.Group(mainFrame, tag_pyclass=None)
        self.listZone.pack(expand=0, fill=Tkinter.X, padx=3, pady=3)
        listFrame = self.listZone.interior()

        self.lightEntry = self.createcomponent(
            'Lights List', (),
            None,
            Pmw.ComboBox, (listFrame, ),
            label_text='Light :',
            labelpos=Tkinter.W,
            entry_width=25,
            selectioncommand=self.selectLight,
            scrolledlist_items=self.lightList)
        self.lightEntry.pack(side=Tkinter.LEFT)

        self.renameButton = self.createcomponent('Rename Light', (),
                                                 None,
                                                 Button, (listFrame, ),
                                                 text=' Rename ',
                                                 command=self.renameLight)
        self.renameButton.pack(side=Tkinter.LEFT)

        self.addLighZone = Pmw.Group(listFrame, tag_pyclass=None)
        self.addLighZone.pack(side=Tkinter.LEFT)
        insideFrame = self.addLighZone.interior()
        self.lightsButton = Menubutton(insideFrame,
                                       text='Add light',
                                       borderwidth=3,
                                       activebackground='#909090')
        lightsMenu = Menu(self.lightsButton)
        lightsMenu.add_command(label='Add Ambient Light',
                               command=self.addAmbient)
        lightsMenu.add_command(label='Add Directional Light',
                               command=self.addDirectional)
        lightsMenu.add_command(label='Add Point Light', command=self.addPoint)
        lightsMenu.add_command(label='Add Spotlight', command=self.addSpot)

        self.lightsButton.pack(expand=0)
        self.lightsButton['menu'] = lightsMenu

        self.deleteButton = self.createcomponent('delete Light', (),
                                                 None,
                                                 Button, (listFrame, ),
                                                 text='  Delete  ',
                                                 command=self.deleteLight)
        self.deleteButton.pack(side=Tkinter.LEFT)

        self.lightColor = seColorEntry(mainFrame,
                                       text='Light Color',
                                       value=self.lightColor)
        self.lightColor['command'] = self.setLightingColorVec
        self.lightColor['resetValue'] = [0.3 * 255, 0.3 * 255, 0.3 * 255, 0]
        self.lightColor.pack(fill=Tkinter.X, expand=0)
        self.bind(self.lightColor, 'Set light color')

        # Notebook pages for light specific controls
        self.lightNotebook = Pmw.NoteBook(mainFrame,
                                          tabpos=None,
                                          borderwidth=0)
        ambientPage = self.lightNotebook.add('Ambient')
        directionalPage = self.lightNotebook.add('Directional')
        pointPage = self.lightNotebook.add('Point')
        spotPage = self.lightNotebook.add('Spot')
        # Put this here so it isn't called right away
        self.lightNotebook['raisecommand'] = self.updateLightInfo

        # Directional light controls
        self.dSpecularColor = seColorEntry(directionalPage,
                                           text='Specular Color')
        self.dSpecularColor['command'] = self.setSpecularColor
        self.dSpecularColor.pack(fill=Tkinter.X, expand=0)
        self.bind(self.dSpecularColor, 'Set directional light specular color')
        self.dPosition = Vector3Entry(directionalPage, text='Position')
        self.dPosition['command'] = self.setPosition
        self.dPosition['resetValue'] = [0, 0, 0, 0]
        self.dPosition.pack(fill=Tkinter.X, expand=0)
        self.bind(self.dPosition, 'Set directional light position')
        self.dOrientation = Vector3Entry(directionalPage, text='Orientation')
        self.dOrientation['command'] = self.setOrientation
        self.dOrientation['resetValue'] = [0, 0, 0, 0]
        self.dOrientation.pack(fill=Tkinter.X, expand=0)
        self.bind(self.dOrientation, 'Set directional light orientation')

        # Point light controls
        self.pSpecularColor = seColorEntry(pointPage, text='Specular Color')
        self.pSpecularColor['command'] = self.setSpecularColor
        self.pSpecularColor.pack(fill=Tkinter.X, expand=0)
        self.bind(self.pSpecularColor, 'Set point light specular color')

        self.pPosition = Vector3Entry(pointPage, text='Position')
        self.pPosition['command'] = self.setPosition
        self.pPosition['resetValue'] = [0, 0, 0, 0]
        self.pPosition.pack(fill=Tkinter.X, expand=0)
        self.bind(self.pPosition, 'Set point light position')

        self.pConstantAttenuation = Slider(pointPage,
                                           text='Constant Attenuation',
                                           max=1.0,
                                           resolution=0.01,
                                           value=1.0)
        self.pConstantAttenuation['command'] = self.setConstantAttenuation
        self.pConstantAttenuation.pack(fill=Tkinter.X, expand=0)
        self.bind(self.pConstantAttenuation,
                  'Set point light constant attenuation')

        self.pLinearAttenuation = Slider(pointPage,
                                         text='Linear Attenuation',
                                         max=1.0,
                                         resolution=0.01,
                                         value=0.0)
        self.pLinearAttenuation['command'] = self.setLinearAttenuation
        self.pLinearAttenuation.pack(fill=Tkinter.X, expand=0)
        self.bind(self.pLinearAttenuation,
                  'Set point light linear attenuation')

        self.pQuadraticAttenuation = Slider(pointPage,
                                            text='Quadratic Attenuation',
                                            max=1.0,
                                            resolution=0.01,
                                            value=0.0)
        self.pQuadraticAttenuation['command'] = self.setQuadraticAttenuation
        self.pQuadraticAttenuation.pack(fill=Tkinter.X, expand=0)
        self.bind(self.pQuadraticAttenuation,
                  'Set point light quadratic attenuation')

        # Spot light controls
        self.sSpecularColor = seColorEntry(spotPage, text='Specular Color')
        self.sSpecularColor['command'] = self.setSpecularColor
        self.sSpecularColor.pack(fill=Tkinter.X, expand=0)
        self.bind(self.sSpecularColor, 'Set spot light specular color')

        self.sConstantAttenuation = Slider(spotPage,
                                           text='Constant Attenuation',
                                           max=1.0,
                                           resolution=0.01,
                                           value=1.0)
        self.sConstantAttenuation['command'] = self.setConstantAttenuation
        self.sConstantAttenuation.pack(fill=Tkinter.X, expand=0)
        self.bind(self.sConstantAttenuation,
                  'Set spot light constant attenuation')

        self.sLinearAttenuation = Slider(spotPage,
                                         text='Linear Attenuation',
                                         max=1.0,
                                         resolution=0.01,
                                         value=0.0)
        self.sLinearAttenuation['command'] = self.setLinearAttenuation
        self.sLinearAttenuation.pack(fill=Tkinter.X, expand=0)
        self.bind(self.sLinearAttenuation, 'Set spot light linear attenuation')

        self.sQuadraticAttenuation = Slider(spotPage,
                                            text='Quadratic Attenuation',
                                            max=1.0,
                                            resolution=0.01,
                                            value=0.0)
        self.sQuadraticAttenuation['command'] = self.setQuadraticAttenuation
        self.sQuadraticAttenuation.pack(fill=Tkinter.X, expand=0)
        self.bind(self.sQuadraticAttenuation,
                  'Set spot light quadratic attenuation')

        self.sExponent = Slider(spotPage,
                                text='Exponent',
                                max=1.0,
                                resolution=0.01,
                                value=0.0)
        self.sExponent['command'] = self.setExponent
        self.sExponent.pack(fill=Tkinter.X, expand=0)
        self.bind(self.sExponent, 'Set spot light exponent')

        # MRM: Add frustum controls

        self.lightNotebook.setnaturalsize()
        self.lightNotebook.pack(expand=1, fill=Tkinter.BOTH)

        mainFrame.pack(expand=1, fill=Tkinter.BOTH)

    def onDestroy(self, event):
        messenger.send('LP_close')
        '''
        If you have open any thing, please rewrite here!
        '''
        pass

    def renameLight(self):
        #################################################################
        # renameLight(self)
        # Call Back function
        # This function will be called when user push
        # the "Rename" button on the panel.
        #
        # Then, this function will collect data and send out them with a message
        # "LP_rename"
        # Which will be caught by sceneEditor and pass to dataHolder to
        # complete the renaming.
        #
        #################################################################
        oName = self.currentLight
        nName = self.lightEntry.get()
        messenger.send('LP_rename', [oName, nName])
        return

    def deleteLight(self):
        #################################################################
        # deleteLight(self)
        # Call Back Function.
        # This function will be called when user click on
        # the "Delete" button on the panel.
        #
        # Then, this function will send out a message with current seleted light
        # "LP_removeLight"
        # Which will be caught by sceneEditor and pass to dataHolder to
        # complete the delete process.
        #
        #################################################################
        messenger.send('LP_removeLight', [self.currentLight])
        return

    def updateList(self, list, node=None):
        #################################################################
        # updataList(self, list, node = None)
        # This function will take a list object which contains names of lights in the scene.
        # Also, if user has put node as a parameter,
        # this function will automatically select that node as the current working target.
        #################################################################
        self.lightList = list
        self.lightEntry.setlist(list)
        if node != None:
            self.lightEntry.selectitem(index=node.getName(), setentry=True)
            self.updateDisplay(node)
        elif len(list) > 0:
            self.lightEntry.selectitem(index=0, setentry=True)
            self.selectLight(list[0])
        else:
            self.lightEntry.clear()
        return

    def selectLight(self, lightName):
        #################################################################
        # selectLight(self, lightName)
        # This function will be called each time when
        # user select a light from the list on the panel.
        # Then, this function will send out the message,
        # 'LP_selectLight' to sceneEditorand get the current light information from dataHolder.
        #################################################################
        if lightName in self.lightList:
            messenger.send('LP_selectLight', [lightName])
        return

    def updateDisplay(self, lightNode):
        #################################################################
        # updateDisplay(self, lightNode)
        # This function will update the information showing on the panel.
        # For example, give a lightNode which is a Point Light.
        # This function will switch the page to specify the type.
        # Also, new node is the same type with the previous one,
        # then this is function won't do the page switching,
        # but will call other function to refresh the data to target node.
        #################################################################
        self.currentLight = lightNode
        if self.currentLight != None:
            color = lightNode.getLightColor()
            self.lightColor.set(
                [255 * color.getX(), 255 * color.getY(), 255 * color.getZ()])
            oldType = self.type
            self.type = lightNode.getType()
        else:
            self.lightColor.set([255 * 0.3, 255 * 0.3, 255 * 0.3])
            oldType = self.type
            self.type = 'ambient'

        if self.type == 'ambient':
            self.lightNotebook.selectpage('Ambient')
        elif self.type == 'directional':
            self.lightNotebook.selectpage('Directional')
        elif self.type == 'point':
            self.lightNotebook.selectpage('Point')
        elif self.type == 'spot':
            self.lightNotebook.selectpage('Spot')
        if oldType == self.type:
            # The same type with previous one, call updateLightInfo to refresh the values.
            self.updateLightInfo()
        return

    def updateLightInfo(self, page=None):
        #################################################################
        # updateLightInfo(self, page=None)
        # This function will refresh the data we user have done any selection.
        #################################################################
        if self.currentLight != None:
            light = self.currentLight.getLight()
        if self.type != 'ambient':
            specColor = light.getSpecularColor()
        if self.type == 'directional':
            point = self.currentLight.getPosition()
            dir = self.currentLight.getOrientation()
            self.dSpecularColor.set([
                specColor.getX() * 255,
                specColor.getY() * 255,
                specColor.getZ() * 255
            ])
            self.dPosition.set([point.getX(), point.getY(), point.getZ()])
            self.dOrientation.set([dir.getX(), dir.getY(), dir.getZ()])
        elif self.type == 'point':
            point = self.currentLight.getPosition()
            attenuation = light.getAttenuation()
            self.pSpecularColor.set([
                specColor.getX() * 255,
                specColor.getY() * 255,
                specColor.getZ() * 255
            ])
            self.pPosition.set([point.getX(), point.getY(), point.getZ()])
            self.pConstantAttenuation.set(attenuation.getX())
            self.pLinearAttenuation.set(attenuation.getY())
            self.pQuadraticAttenuation.set(attenuation.getZ())
        elif self.type == 'spot':
            attenuation = light.getAttenuation()
            expo = light.getExponent()
            self.sSpecularColor.set([
                specColor.getX() * 255,
                specColor.getY() * 255,
                specColor.getZ() * 255
            ])
            self.sConstantAttenuation.set(attenuation.getX())
            self.sLinearAttenuation.set(attenuation.getY())
            self.sQuadraticAttenuation.set(attenuation.getZ())
            self.sExponent.set(expo)
        return

    def addAmbient(self):
        #################################################################
        # addAmbient(self)
        # This function will send out a message to
        # ask dataHolder to create a default ambient light
        #################################################################
        messenger.send('LP_addLight', ['ambient'])
        return

    def addDirectional(self):
        #################################################################
        # addDirectional(self)
        # This function will send out a message to
        # sk dataHolder to create a default Directional light
        #################################################################
        messenger.send('LP_addLight', ['directional'])
        return

    def addPoint(self):
        #################################################################
        # addPoint(self)
        # This function will send out a message to
        # ask dataHolder to create a default Point light
        #################################################################
        messenger.send('LP_addLight', ['point'])
        return

    def addSpot(self):
        #################################################################
        # addSpot(self)
        # This function will send out a message to
        # ask dataHolder to create a default Spot light
        #################################################################
        messenger.send('LP_addLight', ['spot'])
        return

    def setLightingColorVec(self, color):
        #################################################################
        # setLightingColorVec(self,color)
        # Call Back function. This will be called
        # when user try to change the color of light.
        #################################################################
        if self.currentLight == None:
            return
        self.currentLight.setColor(
            VBase4((color[0] / 255), (color[1] / 255), (color[2] / 255), 1))
        return

    def setSpecularColor(self, color):
        #################################################################
        # setSpecularColor(self,color)
        # Call Back function. This will be called
        # when user try to change the Specular color of light.
        #################################################################
        if self.currentLight == None:
            return
        self.currentLight.setSpecColor(
            VBase4((color[0] / 255), (color[1] / 255), (color[2] / 255), 1))
        return

    def setPosition(self, position):
        #################################################################
        # setPosition(self,position)
        # Call Back function. This will be called
        # when user try to change the position of light.
        #################################################################
        if self.currentLight == None:
            return
        self.currentLight.setPosition(
            Point3(position[0], position[1], position[2]))
        return

    def setOrientation(self, orient):
        #################################################################
        # setOrientation(self, orient)
        # Call Back function. This will be called
        # when user try to change the orientation of light.
        #################################################################
        if self.currentLight == None:
            return
        self.currentLight.setOrientation(Vec3(orient[0], orient[1], orient[2]))
        return

    def setConstantAttenuation(self, value):
        #################################################################
        # setConstantAttenuation(self, value)
        # Call Back function. This will be called
        # when user try to change the Constant Attenuation of light.
        #################################################################
        self.currentLight.setConstantAttenuation(value)
        return

    def setLinearAttenuation(self, value):
        #################################################################
        # setLinearAttenuation(self, value)
        # Call Back function. This will be called
        # when user try to change the Linear Attenuation of light.
        #################################################################
        self.currentLight.setLinearAttenuation(value)
        return

    def setQuadraticAttenuation(self, value):
        #################################################################
        # setQuadraticAttenuation(self, value)
        # Call Back function. This will be called
        # when user try to change the Quadratic Attenuation of light.
        #################################################################
        self.currentLight.setQuadraticAttenuation(value)
        return

    def setExponent(self, value):
        #################################################################
        # setExponent(self, value)
        # Call Back function. This will be called
        # when user try to change Exponent value of light.
        #################################################################
        self.currentLight.setExponent(value)
        return
Пример #16
0
class lightingPanel(AppShell):
    #################################################################
    # lightingPanel(AppShell)
    # This will create a window to let user
    # create any kinds of lighting into the scene
    #################################################################
    # Override class variables
    appname = 'Lighting Panel'
    frameWidth  = 400
    frameHeight = 400
    currentLight = None

    def __init__(self, lightList, parent = None, **kw):
        self.lightList = lightList
        self.lightColor = [0.3*255,0.3*255,0.3*255]
        self.type = ''
        INITOPT = Pmw.INITOPT
        optiondefs = (
            ('title',               self.appname,       None),
            )
        self.defineoptions(kw, optiondefs)

        # Initialize the superclass
        AppShell.__init__(self)

        # Execute option callbacks
        self.initialiseoptions(lightingPanel)

        self.parent.resizable(False,False) ## Disable the ability to resize for this Window.

    def createInterface(self):
        # Handle to the toplevels interior
        interior = self.interior()
        menuBar = self.menuBar
        self.menuBar.destroy()

        # Create a frame to hold all stuff
        mainFrame = Frame(interior)

        self.listZone = Pmw.Group(mainFrame,tag_pyclass = None)
        self.listZone.pack(expand=0, fill=Tkinter.X,padx=3,pady=3)
        listFrame = self.listZone.interior()

        self.lightEntry = self.createcomponent(
            'Lights List', (), None,
            Pmw.ComboBox, (listFrame,),label_text='Light :',
            labelpos = Tkinter.W, entry_width = 25, selectioncommand = self.selectLight,
            scrolledlist_items = self.lightList)
        self.lightEntry.pack(side=Tkinter.LEFT)

        self.renameButton = self.createcomponent(
            'Rename Light', (), None,
            Button, (listFrame,),
            text = ' Rename ',
            command = self.renameLight)
        self.renameButton.pack(side=Tkinter.LEFT)

        self.addLighZone = Pmw.Group(listFrame,tag_pyclass = None)
        self.addLighZone.pack(side=Tkinter.LEFT)
        insideFrame = self.addLighZone.interior()
        self.lightsButton = Menubutton(insideFrame, text = 'Add light',borderwidth = 3,
                                       activebackground = '#909090')
        lightsMenu = Menu(self.lightsButton)
        lightsMenu.add_command(label = 'Add Ambient Light',
                            command = self.addAmbient)
        lightsMenu.add_command(label = 'Add Directional Light',
                            command = self.addDirectional)
        lightsMenu.add_command(label = 'Add Point Light',
                            command = self.addPoint)
        lightsMenu.add_command(label = 'Add Spotlight',
                            command = self.addSpot)

        self.lightsButton.pack(expand=0)
        self.lightsButton['menu'] = lightsMenu

        self.deleteButton = self.createcomponent(
            'delete Light', (), None,
            Button, (listFrame,),
            text = '  Delete  ',
            command = self.deleteLight)
        self.deleteButton.pack(side=Tkinter.LEFT)

        self.lightColor = seColorEntry(
            mainFrame, text = 'Light Color', value=self.lightColor)
        self.lightColor['command'] = self.setLightingColorVec
        self.lightColor['resetValue'] = [0.3*255,0.3*255,0.3*255,0]
        self.lightColor.pack(fill=Tkinter.X,expand=0)
        self.bind(self.lightColor, 'Set light color')

        # Notebook pages for light specific controls
        self.lightNotebook = Pmw.NoteBook(mainFrame, tabpos = None,
                                          borderwidth = 0)
        ambientPage = self.lightNotebook.add('Ambient')
        directionalPage = self.lightNotebook.add('Directional')
        pointPage = self.lightNotebook.add('Point')
        spotPage = self.lightNotebook.add('Spot')
        # Put this here so it isn't called right away
        self.lightNotebook['raisecommand'] = self.updateLightInfo

        # Directional light controls
        self.dSpecularColor = seColorEntry(
            directionalPage, text = 'Specular Color')
        self.dSpecularColor['command'] = self.setSpecularColor
        self.dSpecularColor.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.dSpecularColor,
                  'Set directional light specular color')
        self.dPosition = Vector3Entry(
            directionalPage, text = 'Position')
        self.dPosition['command'] = self.setPosition
        self.dPosition['resetValue'] = [0,0,0,0]
        self.dPosition.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.dPosition, 'Set directional light position')
        self.dOrientation = Vector3Entry(
            directionalPage, text = 'Orientation')
        self.dOrientation['command'] = self.setOrientation
        self.dOrientation['resetValue'] = [0,0,0,0]
        self.dOrientation.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.dOrientation, 'Set directional light orientation')

        # Point light controls
        self.pSpecularColor = seColorEntry(
            pointPage, text = 'Specular Color')
        self.pSpecularColor['command'] = self.setSpecularColor
        self.pSpecularColor.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.pSpecularColor,
                  'Set point light specular color')

        self.pPosition = Vector3Entry(
            pointPage, text = 'Position')
        self.pPosition['command'] = self.setPosition
        self.pPosition['resetValue'] = [0,0,0,0]
        self.pPosition.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.pPosition, 'Set point light position')

        self.pConstantAttenuation = Slider(
            pointPage,
            text = 'Constant Attenuation',
            max = 1.0,
            resolution = 0.01,
            value = 1.0)
        self.pConstantAttenuation['command'] = self.setConstantAttenuation
        self.pConstantAttenuation.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.pConstantAttenuation,
                  'Set point light constant attenuation')

        self.pLinearAttenuation = Slider(
            pointPage,
            text = 'Linear Attenuation',
            max = 1.0,
            resolution = 0.01,
            value = 0.0)
        self.pLinearAttenuation['command'] = self.setLinearAttenuation
        self.pLinearAttenuation.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.pLinearAttenuation,
                  'Set point light linear attenuation')

        self.pQuadraticAttenuation = Slider(
            pointPage,
            text = 'Quadratic Attenuation',
            max = 1.0,
            resolution = 0.01,
            value = 0.0)
        self.pQuadraticAttenuation['command'] = self.setQuadraticAttenuation
        self.pQuadraticAttenuation.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.pQuadraticAttenuation,
                  'Set point light quadratic attenuation')

        # Spot light controls
        self.sSpecularColor = seColorEntry(
            spotPage, text = 'Specular Color')
        self.sSpecularColor['command'] = self.setSpecularColor
        self.sSpecularColor.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.sSpecularColor,
                  'Set spot light specular color')

        self.sConstantAttenuation = Slider(
            spotPage,
            text = 'Constant Attenuation',
            max = 1.0,
            resolution = 0.01,
            value = 1.0)
        self.sConstantAttenuation['command'] = self.setConstantAttenuation
        self.sConstantAttenuation.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.sConstantAttenuation,
                  'Set spot light constant attenuation')

        self.sLinearAttenuation = Slider(
            spotPage,
            text = 'Linear Attenuation',
            max = 1.0,
            resolution = 0.01,
            value = 0.0)
        self.sLinearAttenuation['command'] = self.setLinearAttenuation
        self.sLinearAttenuation.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.sLinearAttenuation,
                  'Set spot light linear attenuation')

        self.sQuadraticAttenuation = Slider(
            spotPage,
            text = 'Quadratic Attenuation',
            max = 1.0,
            resolution = 0.01,
            value = 0.0)
        self.sQuadraticAttenuation['command'] = self.setQuadraticAttenuation
        self.sQuadraticAttenuation.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.sQuadraticAttenuation,
                  'Set spot light quadratic attenuation')

        self.sExponent = Slider(
            spotPage,
            text = 'Exponent',
            max = 1.0,
            resolution = 0.01,
            value = 0.0)
        self.sExponent['command'] = self.setExponent
        self.sExponent.pack(fill = Tkinter.X, expand = 0)
        self.bind(self.sExponent,
                  'Set spot light exponent')

        # MRM: Add frustum controls

        self.lightNotebook.setnaturalsize()
        self.lightNotebook.pack(expand = 1, fill = Tkinter.BOTH)

        mainFrame.pack(expand=1, fill = Tkinter.BOTH)

    def onDestroy(self, event):
        messenger.send('LP_close')
        '''
        If you have open any thing, please rewrite here!
        '''
        pass

    def renameLight(self):
        #################################################################
        # renameLight(self)
        # Call Back function
        # This function will be called when user push
        # the "Rename" button on the panel.
        #
        # Then, this function will collect data and send out them with a message
        # "LP_rename"
        # Which will be caught by sceneEditor and pass to dataHolder to
        # complete the renaming.
        #
        #################################################################
        oName = self.currentLight
        nName = self.lightEntry.get()
        messenger.send('LP_rename',[oName,nName])
        return

    def deleteLight(self):
        #################################################################
        # deleteLight(self)
        # Call Back Function.
        # This function will be called when user click on
        # the "Delete" button on the panel.
        #
        # Then, this function will send out a message with current seleted light
        # "LP_removeLight"
        # Which will be caught by sceneEditor and pass to dataHolder to
        # complete the delete process.
        #
        #################################################################
        messenger.send('LP_removeLight',[self.currentLight])
        return

    def updateList(self, list, node=None):
        #################################################################
        # updataList(self, list, node = None)
        # This function will take a list object which contains names of lights in the scene.
        # Also, if user has put node as a parameter,
        # this function will automatically select that node as the current working target.
        #################################################################
        self.lightList = list
        self.lightEntry.setlist(list)
        if node!=None:
            self.lightEntry.selectitem(index=node.getName(), setentry=True )
            self.updateDisplay(node)
        elif len(list)>0:
            self.lightEntry.selectitem(index=0, setentry=True )
            self.selectLight(list[0])
        else:
            self.lightEntry.clear()
        return

    def selectLight(self, lightName):
        #################################################################
        # selectLight(self, lightName)
        # This function will be called each time when
        # user select a light from the list on the panel.
        # Then, this function will send out the message,
        # 'LP_selectLight' to sceneEditorand get the current light information from dataHolder.
        #################################################################
        if lightName in self.lightList:
            messenger.send('LP_selectLight',[lightName])
        return

    def updateDisplay(self, lightNode):
        #################################################################
        # updateDisplay(self, lightNode)
        # This function will update the information showing on the panel.
        # For example, give a lightNode which is a Point Light.
        # This function will switch the page to specify the type.
        # Also, new node is the same type with the previous one,
        # then this is function won't do the page switching,
        # but will call other function to refresh the data to target node.
        #################################################################
        self.currentLight = lightNode
        if self.currentLight != None:
            color = lightNode.getLightColor()
            self.lightColor.set([255*color.getX(),255*color.getY(),255*color.getZ()])
            oldType = self.type
            self.type = lightNode.getType()
        else:
            self.lightColor.set([255*0.3,255*0.3,255*0.3])
            oldType = self.type
            self.type = 'ambient'

        if self.type=='ambient':
            self.lightNotebook.selectpage('Ambient')
        elif self.type =='directional':
            self.lightNotebook.selectpage('Directional')
        elif self.type =='point':
            self.lightNotebook.selectpage('Point')
        elif self.type =='spot':
            self.lightNotebook.selectpage('Spot')
        if oldType == self.type:
            # The same type with previous one, call updateLightInfo to refresh the values.
            self.updateLightInfo()
        return

    def updateLightInfo(self, page=None):
        #################################################################
        # updateLightInfo(self, page=None)
        # This function will refresh the data we user have done any selection.
        #################################################################
        if self.currentLight != None:
            light = self.currentLight.getLight()
        if self.type != 'ambient':
            specColor = light.getSpecularColor()
        if self.type =='directional':
            point = self.currentLight.getPosition()
            dir = self.currentLight.getOrientation()
            self.dSpecularColor.set([specColor.getX()*255,specColor.getY()*255,specColor.getZ()*255])
            self.dPosition.set([point.getX(),point.getY(),point.getZ()])
            self.dOrientation.set([dir.getX(),dir.getY(),dir.getZ()])
        elif self.type =='point':
            point = self.currentLight.getPosition()
            attenuation = light.getAttenuation()
            self.pSpecularColor.set([specColor.getX()*255,specColor.getY()*255,specColor.getZ()*255])
            self.pPosition.set([point.getX(),point.getY(),point.getZ()])
            self.pConstantAttenuation.set(attenuation.getX())
            self.pLinearAttenuation.set(attenuation.getY())
            self.pQuadraticAttenuation.set(attenuation.getZ())
        elif self.type =='spot':
            attenuation = light.getAttenuation()
            expo = light.getExponent()
            self.sSpecularColor.set([specColor.getX()*255,specColor.getY()*255,specColor.getZ()*255])
            self.sConstantAttenuation.set(attenuation.getX())
            self.sLinearAttenuation.set(attenuation.getY())
            self.sQuadraticAttenuation.set(attenuation.getZ())
            self.sExponent.set(expo)
        return

    def addAmbient(self):
        #################################################################
        # addAmbient(self)
        # This function will send out a message to
        # ask dataHolder to create a default ambient light
        #################################################################
        messenger.send('LP_addLight',['ambient'])
        return

    def addDirectional(self):
        #################################################################
        # addDirectional(self)
        # This function will send out a message to
        # sk dataHolder to create a default Directional light
        #################################################################
        messenger.send('LP_addLight',['directional'])
        return

    def addPoint(self):
        #################################################################
        # addPoint(self)
        # This function will send out a message to
        # ask dataHolder to create a default Point light
        #################################################################
        messenger.send('LP_addLight',['point'])
        return

    def addSpot(self):
        #################################################################
        # addSpot(self)
        # This function will send out a message to
        # ask dataHolder to create a default Spot light
        #################################################################
        messenger.send('LP_addLight',['spot'])
        return

    def setLightingColorVec(self,color):
        #################################################################
        # setLightingColorVec(self,color)
        # Call Back function. This will be called
        # when user try to change the color of light.
        #################################################################
        if self.currentLight==None:
            return
        self.currentLight.setColor(VBase4((color[0]/255),(color[1]/255),(color[2]/255),1))
        return

    def setSpecularColor(self,color):
        #################################################################
        # setSpecularColor(self,color)
        # Call Back function. This will be called
        # when user try to change the Specular color of light.
        #################################################################
        if self.currentLight==None:
            return
        self.currentLight.setSpecColor(VBase4((color[0]/255),(color[1]/255),(color[2]/255),1))
        return

    def setPosition(self,position):
        #################################################################
        # setPosition(self,position)
        # Call Back function. This will be called
        # when user try to change the position of light.
        #################################################################
        if self.currentLight==None:
            return
        self.currentLight.setPosition(Point3(position[0],position[1],position[2]))
        return

    def setOrientation(self, orient):
        #################################################################
        # setOrientation(self, orient)
        # Call Back function. This will be called
        # when user try to change the orientation of light.
        #################################################################
        if self.currentLight==None:
            return
        self.currentLight.setOrientation(Vec3(orient[0],orient[1],orient[2]))
        return

    def setConstantAttenuation(self, value):
        #################################################################
        # setConstantAttenuation(self, value)
        # Call Back function. This will be called
        # when user try to change the Constant Attenuation of light.
        #################################################################
        self.currentLight.setConstantAttenuation(value)
        return

    def setLinearAttenuation(self, value):
        #################################################################
        # setLinearAttenuation(self, value)
        # Call Back function. This will be called
        # when user try to change the Linear Attenuation of light.
        #################################################################
        self.currentLight.setLinearAttenuation(value)
        return

    def setQuadraticAttenuation(self, value):
        #################################################################
        # setQuadraticAttenuation(self, value)
        # Call Back function. This will be called
        # when user try to change the Quadratic Attenuation of light.
        #################################################################
        self.currentLight.setQuadraticAttenuation(value)
        return

    def setExponent(self, value):
        #################################################################
        # setExponent(self, value)
        # Call Back function. This will be called
        # when user try to change Exponent value of light.
        #################################################################
        self.currentLight.setExponent(value)
        return
Пример #17
0
class ClsGUI(Tk):
    """
    Попытка создать ГУИ для репортера.
    """

    def __init__(self):
        """
        Создаёт интерфейс пользователя для репортера.
        """
        def bind_win():
            """
            Привязка событий к окнам.
            """

            def quit_reporter(event=''):
                """
                Выходит из репортера.
                :param event:
                """
                import sys
                sys.exit()

            def save_reporter(event=''):
                """
                Сохраняет отчёт.
                :param event:
                """
                print '===report==='
                _reporter = ClsSmallReporter()
                self.txt_report.insert('1.0', _reporter.html_data)

            def generate_report(event=''):
                """
                Генерирует отчёт.
                :param event:
                """
                print '===report==='
                reporter = ClsSmallReporter()
                self.txt_report.insert('1.0', reporter.html_data)

            self.bind('<Control-Q>', quit_reporter)
            self.bind('<Control-q>', quit_reporter)

            self.bind('<Control-S>', save_reporter)
            self.bind('<Control-s>', save_reporter)

            self.bind('<Control-G>', generate_report)
            self.bind('<Control-g>', generate_report)

        Tk.__init__(self)
        self.frm_up = Frame(self)
        self.mnu_file = None
        self.mnu_custom = None
        self.btn_exit = None
        self.mnu_help = None
        self.mnu_edit = None
        self.txt_report = None
        self.btn_edit = None
        self.btn_save = None
        self.pnl_menu = None
        self.btn_custom = None
        self.btn_generate = None
        self.btn_file = None
        self.btn_help = None
        self.frm_midle = None
        self.frm_down = None

        self.title(LANG_RU['win_main'])
        self.minsize(GEOMETRY['winMain_minSizeX'], GEOMETRY['winMain_minSizeY'])
        self.maxsize(GEOMETRY['winMain_maxSizeX'], GEOMETRY['winMain_maxSizeY'])
        self.create_up_frame()
        self.create_frm_middle()
        self.create_frm_down()
        bind_win()
        self.mainloop()

    def create_up_frame(self):
        """
        Создаёт верхний фрейм.
        :type self: object
        """
        self.create_menu_bar()
        self.frm_up.pack(side='top', fill='x')

    def create_frm_middle(self):
        """
        Создаёт средний фрейм для отображения.
        """
        self.frm_midle = Frame(self, border=2, relief='raised')
        self.frm_midle.pack(side='top', expand=1, fill='both')
        self.txt_report = Text(self.frm_midle, font='Consolas 9 normal')
        self.txt_report.pack(side='top', fill='both', expand=1)


    def create_frm_down(self):
        """
        Создаёт нижний фрейм репортера.
        """

        def btn_generate_click(event=''):
            """
            Обработчик нижатия кнопки генератора отчёта.
            :param event:
            """
            print '===report==='
            _reporter = ClsSmallReporter()
            self.txt_report.insert('1.0', _reporter.html_data)

        def create_btn_exit():
            """
            Создаёт кнопки выхода из программы.
            """

            def report_exit(event=''):
                """
                Обработчик нажатия кнопки выхода из программы.
                :param event:
                """
                import sys

                sys.exit()

            self.btn_exit = Button(self.frm_down,
                                   text=LANG_RU['btn_exit'],
                                   command=report_exit,
                                   bg='red')
            self.btn_exit.pack(side='left', expand=1, fill='x')

        def create_btn_save():
            """
            Создаёт кнопку для сохранения отчёта.
            """
            self.btn_save = Button(self.frm_down, text=LANG_RU['btn_save'])
            self.btn_save.pack(side='left', expand=1, fill='x')

        def create_btn_generate():
            """
            Создаёт кнопку для генерации отчёта
            """
            self.btn_generate = Button(self.frm_down,
                                       text=LANG_RU['btn_generate'],
                                       command=btn_generate_click)
            self.btn_generate.pack(side='left', expand=1, fill='x')

        self.frm_down = Frame(self)

        create_btn_generate()
        create_btn_save()
        create_btn_exit()

        self.frm_down.pack(side='bottom', fill='x')

    def create_menu_bar(self):
        """
        Создаёт линейку для меню программы.
        """

        def create_mnu_file():
            """
            Создаёт меню файл.
            """
            self.btn_file = Menubutton(self.pnl_menu, text=LANG_RU['mnu_file'],
                                       border=3, relief='groove')
            self.mnu_file = Menu(self.btn_file)
            self.btn_file.config(menu=self.mnu_file)
            self.mnu_file.add_command(label=LANG_RU['mnuFile_New'],
                                      accelerator='Ctrl+N')
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Open'],
                                      accelerator='Ctrl+O')
            self.mnu_file.add_separator()
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Save'],
                                      accelerator='Ctrl+S')
            self.mnu_file.add_command(label=LANG_RU['mnuFile_SaveAs'])
            self.mnu_file.add_separator()
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Print'],
                                      accelerator='Ctrl+P')
            self.mnu_file.add_separator()
            self.mnu_file.add_command(label=LANG_RU['mnuFile_Exit'],
                                      accelerator='Ctrl+Q')
            self.btn_file.pack(side='left')

        def create_mnu_edit():
            """
            Создаёт меню "Правка".
            """
            self.btn_edit = Menubutton(self.pnl_menu,
                                       text=LANG_RU['mnu_edit'],
                                       border=3,
                                       relief='groove')
            self.mnu_edit = Menu(self.btn_edit)
            self.btn_edit.config(menu=self.mnu_edit)
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Undo'],
                                      accelerator='Ctrl+Z')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Redo'])
            self.mnu_edit.add_separator()
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Copy'],
                                      accelerator='Ctrl+C')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Cut'],
                                      accelerator='Ctrl+X')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Paste'],
                                      accelerator='Ctrl+V')
            self.mnu_edit.add_separator()
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Find'],
                                      accelerator='Ctrl+F')
            self.mnu_edit.add_command(label=LANG_RU['mnuEdit_Replace'],
                                      accelerator='Ctrl+R')
            self.btn_edit.pack(side='left')

        def create_mnu_custom():
            """
            Создаёт меню нстроек.
            """
            self.btn_custom = Menubutton(self.pnl_menu, text='mnu_custom',
                                         border=3, relief='groove')
            self.mnu_custom = Menu(self.btn_custom)
            self.btn_custom.config(menu=self.mnu_custom)
            self.mnu_custom.add_command(label='Type files',
                                        accelerator='Ctrl+D')
            self.mnu_custom.add_command(label='--1')
            self.mnu_custom.add_separator()
            self.mnu_custom.add_command(label='--2', accelerator='---')
            self.mnu_custom.add_command(label='--3', accelerator='---')
            self.mnu_custom.add_command(label='--4', accelerator='---')
            self.mnu_custom.add_separator()
            self.btn_custom.pack(side='left')

        def create_mnu_help():
            """
            Создаёт меню "Справка".
            """
            self.btn_help = Menubutton(self.pnl_menu,
                                       text='mnu_help',
                                       border=3,
                                       relief='groove')
            self.mnu_help = Menu(self.btn_help)
            self.btn_help.config(menu=self.mnu_help)
            self.mnu_help.add_command(label='Type files', accelerator='Ctrl+D')
            self.mnu_help.add_command(label='--1')
            self.mnu_custom.add_separator()
            self.btn_help.pack(side='left')

        self.pnl_menu = PanedWindow(self.frm_up, border=2, relief='raised')
        create_mnu_file()
        create_mnu_edit()
        create_mnu_custom()
        create_mnu_help()

        self.pnl_menu.pack(side='left', expand=1, fill='x')
Пример #18
0
Файл: booru.py Проект: Reyuu/abd
class Main(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.current_image = posts[0]
        self.posts = posts
        self.initUI()
        self.current_booru = None

    def initUI(self):
        self.parent.title("Booru")
        self.pack(fill=Y, expand=0, side=LEFT)
        myicon = ImageTk.PhotoImage(file="sbooru.ico")
        self.current_booru_var = StringVar()
        self.mb = Menubutton(self,
                             textvariable=self.current_booru_var,
                             relief=RAISED,
                             image=myicon,
                             compound=LEFT)
        self.mb.image = myicon
        self.mb.pack(side=TOP)
        self.mb.menu = Menu(self.mb, tearoff=0)
        self.mb["menu"] = self.mb.menu
        self.current_booru_var.set("Safebooru")

        def change_booru(booru):
            self.current_booru = booru
            if self.current_booru == 0:
                self.current_booru_var.set("Danbooru")
            if self.current_booru == 1:
                self.current_booru_var.set("Safebooru")

        self.mb.menu.add_command(label="Danbooru",
                                 command=lambda: change_booru(0))
        self.mb.menu.add_command(label="Safebooru",
                                 command=lambda: change_booru(1))

        self.mb.pack()

        image = Image.open(
            get_image_from_internet_binary(
                u"%s%s" % (main_url, self.posts[0][u"preview_file_url"])))
        photo = ImageTk.PhotoImage(image)
        self.label = Label(self, image=photo)
        self.label.image = photo
        self.label.pack(fill=Y, expand=0, side=TOP)

        self.lb = Listbox(self)
        for i in self.posts:
            self.lb.insert(END, i["id"])
        self.lb.bind("<<ListboxSelect>>", self.onSelect)
        self.lb.pack(pady=15, fill=Y, expand=0, side=LEFT)

        self.description = Labelframe(self,
                                      text="Description",
                                      height=350,
                                      width=350)
        self.description.pack(pady=15, expand=0)
        #artist
        self.artist_v = StringVar()
        self.artist = Label(self.description,
                            textvariable=self.artist_v,
                            justify=LEFT,
                            wraplength=350,
                            anchor=W)
        self.artist.pack()
        #md5
        self.md5_v = StringVar()
        self.md5 = Label(self.description,
                         textvariable=self.md5_v,
                         justify=LEFT,
                         wraplength=350,
                         anchor=W)
        self.md5.pack()
        #source
        self.source_v = StringVar()
        self.source = Label(self.description,
                            textvariable=self.source_v,
                            justify=LEFT,
                            wraplength=350,
                            anchor=W)
        self.source.pack()
        #wxh
        self.wxh_v = StringVar()
        self.wxh = Label(self.description,
                         textvariable=self.wxh_v,
                         justify=LEFT,
                         wraplength=350,
                         anchor=W)
        self.wxh.pack()
        #tags (for now all)
        self.tags_v = StringVar()
        self.tags = Label(self.description,
                          textvariable=self.tags_v,
                          justify=LEFT,
                          wraplength=350,
                          anchor=W)
        self.tags.pack()
        #uploader
        self.uploader_v = StringVar()
        self.uploader = Label(self.description,
                              textvariable=self.uploader_v,
                              justify=LEFT,
                              wraplength=350,
                              anchor=W)
        self.uploader.pack()
        idx = (0, 0)
        try:
            self.artist_v.set(u"Artist:\t%s" %
                              self.posts[idx[0]][u"tag_string_artist"])
        except KeyError:
            self.artist_v.set(u"Artist:\t")
        try:
            self.md5_v.set(u"MD5:\t%s" % self.posts[idx[0]][u"md5"])
        except KeyError:
            self.md5_v.set(u"MD5:\t")
        try:
            self.source_v.set(u"Source:\t%s" % self.posts[idx[0]][u"source"])
        except KeyError:
            self.source_v.set(u"Source:\t")
        try:
            self.wxh_v.set(u"Size:\t%sx%s" %
                           (self.posts[idx[0]][u"image_width"],
                            self.posts[idx[0]][u"image_height"]))
        except KeyError:
            self.wxh_v.set(u"Size:\t")
        try:
            self.tags_v.set(u"Tags:\t%s" % self.posts[idx[0]][u"tag_string"])
        except KeyError:
            self.tags_v.set(u"Tags:\t")
        try:
            self.uploader_v.set(u"Uploader:\t%s" %
                                self.posts[idx[0]][u"uploader_name"])
        except KeyError:
            self.uploader_v.set(u"Uploader:\t")

        self.button_frame = Frame(self.description)
        self.button_frame.pack(fill=Y, expand=0, side=LEFT)

        def download_image_current():
            def download():
                urllib.urlretrieve(
                    "%s%s" % (main_url, self.current_image[u"file_url"]),
                    "%s_%s.%s" %
                    (self.current_image[u"id"], self.current_image[u"md5"],
                     self.current_image[u"file_ext"]))

            t1 = Thread(target=download, args=())
            t1.start()

        self.download_button = Button(self.button_frame,
                                      text="Download",
                                      command=download_image_current)
        self.download_button.pack(side=LEFT)

        def bigger_preview():
            image = Image.open(
                get_image_from_internet_binary(
                    u"%s%s" % (main_url, self.current_image[u"file_url"])))
            photo = ImageTk.PhotoImage(image)
            self.bigpreview = Toplevel(self)
            labelu = Label(self.bigpreview, image=photo)
            labelu.image = photo
            labelu.pack(fill=Y, expand=0, side=LEFT)

        self.preview_button = Button(self.button_frame,
                                     text="Preview",
                                     command=bigger_preview)
        self.preview_button.pack(side=RIGHT)

        def onRefresh():
            def method():
                query_args["page"] = self.current_page.get()
                self.posts = get_posts("posts.json", query_args)
                self.lb.delete(0, END)
                for i in self.posts:
                    self.lb.insert(END, i["id"])

            t1 = Thread(target=method, args=())
            t1.start()

        self.refresh = Button(self.button_frame,
                              text="Refresh posts",
                              command=onRefresh)
        self.refresh.pack(side=LEFT)

        page_control = Frame(self)
        page_control.pack(pady=15, side=BOTTOM)
        self.current_page = IntVar()
        self.current_page.set(1)

        def forward_f():
            self.current_page.set(self.current_page.get() + 1)
            onRefresh()

        forward = Button(page_control, text=">>", command=forward_f)
        forward.pack(side=RIGHT)

        def backward_f():
            self.current_page.set((self.current_page.get() - 1) if (
                self.current_page.get() - 1 > 0) else self.current_page.get())
            onRefresh()

        backward = Button(page_control, text="<<", command=backward_f)
        backward.pack(side=LEFT)
        curpaglabl = Label(page_control,
                           textvariable=self.current_page,
                           background="orange")
        curpaglabl.pack(pady=15, side=BOTTOM)

    def onSelectFileBrowser(self, val):
        sender = val.widget
        idx = sender.curselection()

        def get_image_and_cover_it(self):
            with open(sender.get(idx), "r") as fre:
                image = Image.open(fre.read())
                photo = ImageTk.PhotoImage(image)
                self.label.configure(image=photo)
                self.label.image = photo

        t1 = Thread(target=get_image_and_cover_it, args=(self, ))
        t1.start()

    def onSelect(self, val):
        sender = val.widget
        idx = sender.curselection()
        self.current_image = self.posts[idx[0]]
        try:
            self.artist_v.set(u"Artist:\t%s" %
                              self.posts[idx[0]][u"tag_string_artist"])
        except KeyError:
            self.artist_v.set(u"Artist:\t")
        try:
            self.md5_v.set(u"MD5:\t%s" % self.posts[idx[0]][u"md5"])
        except KeyError:
            self.md5_v.set(u"MD5:\t")
        try:
            self.source_v.set(u"Source:\t%s" % self.posts[idx[0]][u"source"])
        except KeyError:
            self.source_v.set(u"Source:\t")
        try:
            self.wxh_v.set(u"Size:\t%sx%s" %
                           (self.posts[idx[0]][u"image_width"],
                            self.posts[idx[0]][u"image_height"]))
        except KeyError:
            self.wxh_v.set(u"Size:\t")
        try:
            self.tags_v.set(u"Tags:\t%s" % self.posts[idx[0]][u"tag_string"])
        except KeyError:
            self.tags_v.set(u"Tags:\t")
        try:
            self.uploader_v.set(u"Uploader:\t%s" %
                                self.posts[idx[0]][u"uploader_name"])
        except KeyError:
            self.uploader_v.set(u"Uploader:\t")

        def get_image_and_cover_it(self):
            image = Image.open(
                get_image_from_internet_binary(
                    u"%s%s" %
                    (main_url, self.posts[idx[0]][u"preview_file_url"])))
            photo = ImageTk.PhotoImage(image)
            self.label.configure(image=photo)
            self.label.image = photo

        t1 = Thread(target=get_image_and_cover_it, args=(self, ))
        t1.start()