Ejemplo n.º 1
0
 def OnLocal(self, event):
     Setting.setLocalResolution("%s" % self.localres.GetValue())
     Setting.save()
     if self.localres.GetValue() == True:
         self.combo.Enable(False)
     else:
         self.combo.Enable(True)
Ejemplo n.º 2
0
    def __init__(self, parent=None):
        """ Initializes the GUI Object
		
		@param parent
		"""
        Tkinter.Tk.__init__(self, parent)
        self.screen = {
            'width': self.winfo_screenwidth(),
            'height': self.winfo_screenheight()
        }
        self.widgets, self.menus = {}, {}
        self.title('AllMyServos')
        self.parent = parent
        self.setting = Setting()
        if (PreFlight.status()):
            self.specification = self.getClass(
                'Specification.Specification').GetInstance(
                )  #avoids importing before preflight checks
            self.scheduler = Scheduler.GetInstance()
            self.motionScheduler = self.getClass('Motion.MotionScheduler')(
                self.specification, self.scheduler)
            self.initTheme()
            self.initFrames()
            self.trayIcon = TrayIcon.TrayIcon(self.scheduler)
            self.setup()
        else:
            self.initTheme()
            self.initFrames()
            self.setupPreFlight()
Ejemplo n.º 3
0
    def get_rdpsetting(self):
        if Setting.getAllow_device().lower() == 'true':
            arg_device = '/drive:USB,/run/media/root '
        else:
            arg_device = ''

        #if Setting.getAuto_connect().lower() == 'true':
        #    arg_auto = '+auto-reconnect '
        #else:
        #    arg_auto = ''

        #if Setting.getHeadset_micro().lower() == 'true':
        #    arg_head_mic = '/sound:sys:pulse /microphone:sys:pulse '
        #else:
        #    arg_head_mic = ''

        if Setting.getRemotefx().lower() == 'true':
            arg_rem = '/codec-cache:jpeg /gfx '
        else:
            arg_rem = ''

        if Setting.getPublic().lower() == 'true':
            arg_net = '/network:wan '
        else:
            arg_net = '/network:lan '

        arg = ' '.join([arg_device, arg_rem, arg_net])
        return arg
Ejemplo n.º 4
0
    def run(self):
        while not self.cancel:
            if self.refresh > 0:
                self.lock.acquire()
                self.refreshVM()
                self.lock.release()
                self.refresh = self.refresh - 1
            else:
                if self.tenRefresh == 0:
                    # Del by wangderan 20150525 start
                    #Session.logout()
                    # Del by wangderan 20150525 end

                    url = 'http://%s%s' % (Setting.getServer(), ":5000/v2.0")
                    _auth_url = url

                    username = Setting.getLastLogin()
                    _user = username

                    _password = LoginFrame.PassWord()

                    ret, reason, detail = Session.login(
                        _auth_url, _user, _password)
                    Logger.info("ReLogin Status: Result: %s", ret)

                    self.lock.acquire()
                    self.refreshVM()
                    self.lock.release()
                    self.tenRefresh = 900
                else:
                    self.tenRefresh = self.tenRefresh - 1
                    wx.Sleep(2)
Ejemplo n.º 5
0
    def __init__(self, parent):
        wx.Panel.__init__(self, parent)
        
        sizer = wx.FlexGridSizer(cols = 2, hgap = 10, vgap = 15)
        sizer.AddGrowableCol(1)
        sizer.Add(wx.StaticText(self, -1, u'服务器地址:'),
                  0, wx.ALIGN_CENTER_VERTICAL | wx.ALIGN_RIGHT)
        self.server = wx.TextCtrl(self, -1, 
                             Setting.getServer())
        sizer.Add(self.server, 0, wx.EXPAND )

        self.public = wx.CheckBox(self, -1, u'公网连接')
        if Setting.getPublic().lower() == 'true':
            self.public.SetValue(True)
        else:
            self.public.SetValue(False)
        sizer.Add(self.public, 0, wx.EXPAND)

        box = wx.StaticBox(self, -1, u'虚拟化服务器设置')
        midSizer = wx.StaticBoxSizer(box, wx.VERTICAL)


        midSizer.Add(Util.CreateCenterSizer(sizer, 10), 
                     1, wx.EXPAND)
        
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        help = wx.StaticText(self, -1, u'在首次使用之前请正确设置服务器地址和端口。如果你\
不了解这些设置,请联系你的网络管理员。')
        mainSizer.Add(help, 0, wx.EXPAND)
        mainSizer.AddSpacer((20, 20))
        mainSizer.Add(midSizer, 0, wx.EXPAND)
        
        self.SetSizer(Util.CreateCenterSizer(mainSizer, 10))
Ejemplo n.º 6
0
    def __init__(self, parent):
        wx.Dialog.__init__(self, parent, -1, u"系统设置",
                           style = wx.BORDER_DOUBLE, size = (520, 520)
                           )
        
        Setting.load()
        
        bmp = wx.StaticBitmap(self, -1, Resource.ui_banner)
        panel = wx.Panel(self)
        panel.SetBackgroundColour('#B3B2B3')
        
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(bmp, 0)
        sizer.Add(panel, 1, flag = wx.EXPAND)
        
        nb = ZopleNoteBook(self)
        self.noteBook = nb
        
        mainSizer = wx.BoxSizer(wx.VERTICAL)
        mainSizer.Add(sizer, 0, flag = wx.EXPAND)
        mainSizer.AddSpacer(10)
        mainSizer.Add(nb, 1, flag = wx.EXPAND)

        sizer = wx.FlexGridSizer(cols = 2, hgap = 15, vgap = 20)
        btn_ok = wx.Button(self, wx.ID_OK, u'确定')
        btn_ok.SetDefault()
        btn_cancel = wx.Button(self, wx.ID_CANCEL, u'取消')
        sizer.Add(btn_ok, 0)
        sizer.Add(btn_cancel, 0)
        
        mainSizer.AddSpacer(10)
        mainSizer.Add(sizer, 0, flag = wx.ALIGN_BOTTOM | wx.ALIGN_RIGHT)
        
        self.SetSizer(Util.CreateCenterSizer(mainSizer, 10))
Ejemplo n.º 7
0
def GetUrl():
    url = Setting.getServer()
    if Setting.getSecure() == 'True':
        url = 'https://' + url
    else:
        url = 'http://' + url

    return url
Ejemplo n.º 8
0
def start(startPage, endPage):
    api = 'http://www.xiaohongshu.com/fe_api/burdock/weixin/v2/search/notes?keyword={}&sortBy=general&page={}&pageSize=20&needGifCover=true&sid=session.1575338664880906512653'
    user_input = input('输入需要搜索的关键词: \n')
    keyword = urllib.parse.quote(user_input)
    print('Start!')
    for page in range(startPage, endPage):
        time.sleep(5)
        url = api.format(keyword, page)
        Setting.getData(Setting.getBookId(url))
Ejemplo n.º 9
0
	def __init__(self, parent, gui, **options):
		""" Initializes TkSettingManager object
		
		@param parent
		@param gui
		@param options
		"""
		super(TkSettingManager,self).__init__(parent, gui, **options)
		self.s = Setting()
Ejemplo n.º 10
0
def autoHeal():

    if getHealth < healthFull:
        if getHealth <= Healing.percentage(percentLow, healthFull):
            pyautogui.hotkey(HTK_Low)
            #print('Low')
        elif getHealth <= Healing.percentage(percentMedium, healthFull):
            pyautogui.hotkey(HTK_Medium)
            #print('Medium')
        elif getHealth <= Healing.percentage(percentHigh, healthFull):
            pyautogui.hotkey(HTK_High)
Ejemplo n.º 11
0
    def OnLogin(self, event):
        global PASSWORD
        PASSWORD = self.password.GetValue()
        # Valid Check
        if self.username.GetValue() == '' or self.password.GetValue() == '':
            Util.MessageBox(self, u'缺少用户名或密码!', u'错误', wx.OK | wx.ICON_ERROR)
            return

        dlg = ProgressDialog.ProgressDialog(self, u'连接服务器...')

        url = 'http://%s:5000/v2.0' % (Setting.getServer())

        RestartDeviceRequests()

        loginthread = LoginThread(dlg, url, self.username.GetValue(),
                                  self.password.GetValue())
        loginthread.start()
        #ret = dlg.ShowModal()
        #dlg.Destroy()
        if dlg.ShowModal() == wx.ID_CANCEL:
            loginthread.stop()
            return
        if loginthread:
            loginthread.stop()
        dlg.Destroy()

        Logger.info("Connect to %s", url)
        Logger.info("UserId: %s, Password: ******", self.username.GetValue())
        ret, reason, detail = loginthread.getReturnValue()
        Logger.info("Result: %s, reason: %s, detail: %s", ret, reason, detail)

        if Setting.getSign().lower() == 'false':
            self.password.SetValue('')

        self.password.SetFocus()

        if not ret:
            Util.MessageBox(self, detail, reason, wx.OK | wx.ICON_ERROR)
            Session.logout()
        else:
            Setting.setLastLogin(FirstUser['firstuser'].username)
            if self.sign.GetValue() == True:
                Setting.setPasswd(self.password.GetValue())
            else:
                Setting.setPasswd('1df#$!cd123~')
            Setting.save()
            area = wx.Display().GetGeometry()
            width = area.GetWidth()
            height = area.GetHeight()
            f = MainFrame.MainFrame(self.GetParent(), (width, height))

            f.ShowFullScreen(True)
            self.GetParent().Hide()
Ejemplo n.º 12
0
 def OnSign(self, evt):
     Setting.setSign("%s" % self.sign.GetValue())
     if self.sign.GetValue() != True:
         self.auto.SetValue(False)
         Setting.setAuto("%s" % self.auto.GetValue())
     Setting.setPasswd(self.password.GetValue())
     Setting.save()
Ejemplo n.º 13
0
 def OnRempass(self, event):
     Setting.setVPNRem(self.rempassCheck.GetValue())
     Setting.setVPNPass(self.passText.GetValue())
     if self.rempassCheck.GetValue() != True:
         self.autologCheck.SetValue(False)
         Setting.setVPNAuto('%s' % self.autologCheck.GetValue())
     Setting.save()
Ejemplo n.º 14
0
 def OnAutologin(self, event):
     Setting.setVPNAuto(self.autologCheck.GetValue()) 
     Setting.setVPNPass(self.passText.GetValue())
     if self.autologCheck.GetValue() == True:
         self.rempassCheck.SetValue(True)
         Setting.setVPNRem(True)
     Setting.save()
Ejemplo n.º 15
0
    def autoLogin(self):
        if Setting.getSign().lower() == 'false':
            return False
        if Setting.getAuto().lower() == 'true':
            pass
        else:
            return False

        username = Setting.getLastLogin()
        passwd = Setting.getPasswd()
        if username == '' or passwd == '':
            Util.MessageBox(self, u'缺少用户名或密码!', u'错误', wx.OK | wx.ICON_ERROR)
            return

        dlg = ProgressDialog.ProgressDialog(self, u'连接服务器...')
        dlg.CenterOnScreen()

        url = 'http://%s:5000/v2.0' % (Setting.getServer())

        RestartDeviceRequests()

        loginthread = LoginThread(dlg, url, username, passwd)
        loginthread.start()
        #dlg.SetPosition((100,100))
        #dlg.Move((Resource.screenX-dlg.))
        #dlg.CenterOnScreen()
        #ret = dlg.ShowModal()
        #dlg.Destroy()
        if dlg.ShowModal() == wx.ID_CANCEL:
            loginthread.stop()
            return
        if loginthread:
            loginthread.stop()
        dlg.Destroy()

        Logger.info("Connect to %s", url)
        Logger.info("UserId: %s, Password: ******", username)
        ret, reason, detail = loginthread.getReturnValue()
        Logger.info("Result: %s, reason: %s, detail: %s", ret, reason, detail)

        if not ret:
            Util.MessageBox(self, detail, reason, wx.OK | wx.ICON_ERROR)
            self.ShowFullScreen(True)
            Session.logout()
        else:
            f = MainFrame.MainFrame(self.GetParent(), wx.ScreenDC().GetSize())
            f.ShowFullScreen(True)
            self.GetParent().Hide()
Ejemplo n.º 16
0
    def OnSave(self):
        Setting.setServer(self.server.GetValue())
        Setting.setPublic('%s' % self.public.GetValue())

        #sp = self.server.GetValue().split(".") 
        #if len(sp) == 4:
        #    if sp[0] in LAN:
        #        Setting.setPublic("False") 
        #    else:
        #        Setting.setPublic("True") 
        #elif len(sp) == 2 or len(sp) == 3:
        #    Setting.setPublic("True")
        #elif len(sp) == 1:
        #    Setting.setPublic("False") 

        RestartDeviceRequests()
Ejemplo n.º 17
0
    def on_mouse_press(self, _x, _y, button, _modifiers):

        menu_hit_list = arcade.check_for_collision_with_list(
            self.mouse_sprite, self.menu_list)

        for menu_index in menu_hit_list:

            if button == arcade.MOUSE_BUTTON_LEFT:

                if menu_index == self.menu_list[0]:  # start
                    game_view = Game.GameView()
                    game_view.setup()
                    self.window.show_view(game_view)

                if menu_index == self.menu_list[1]:  # setting
                    setting_view = Setting.SettingView()
                    setting_view.setup()
                    self.window.show_view(setting_view)

                if menu_index == self.menu_list[2]:  # map edit
                    mapedit_view = Mapedit.MapeditView()
                    mapedit_view.setup()
                    self.window.show_view(mapedit_view)

                if menu_index == self.menu_list[3]:  # quit
                    arcade.close_window()
                    return 0

                if menu_index == self.menu_list[4]:  # back
                    return 0
Ejemplo n.º 18
0
def get_setting_names_data(data_files, names_file, result_dir, Setting):
    """
    Data preprocessing
    :param data_files: the pathname of the data files
    :param names_file: the pathname of the names file
    :param result_dir: the pathname of the result directory
    :param result_dir: the Setting module
    :return: the setting, names, and data object
    """

    data_file = data_files[0].replace('.train', '')
    data_file = data_file.replace('.test', '')

    # Get the Setting object
    # If data_file and names_file are in ./data/current/
    if os.path.basename(os.path.dirname(os.path.dirname(data_file))) == 'data':
        result_dir += os.path.basename(os.path.dirname(data_file)) + '/'
    # If data_file and names_file are in ./data/parent/current/
    else:
        result_dir += os.path.basename(
            os.path.dirname(
                os.path.dirname(data_file))) + '/' + os.path.basename(
                    os.path.dirname(data_file)) + '/'
    setting = Setting.Setting(names_file, result_dir)

    # Get the Names object
    names = get_names(names_file)

    # Get the Data object
    get_data(data_files, setting, names)
Ejemplo n.º 19
0
    def _handle_write_multiple_registers_request(self, request_data_from_hook):
        slave, bytes_data = request_data_from_hook
        # 获取地址和数据(uint16)
        address, values = Setting.solve_multiple_request(bytes_data)

        #  进行处理
        if address in [Setting.Pi_Time_stamp_Address, Setting.Pi_Time_stamp_Address+1]:
            values_old = self._get_holding_registers_values(Setting.Pi_Time_stamp_Address, 2)
            if address == Setting.Pi_Time_stamp_Address and len(values) == 2:
                time_stamp = values[0] + values[1] * 2 ** 16
                SetPiTime.linux_set_time(time_stamp)
                print(time_stamp)
            elif address == Setting.Pi_Time_stamp_Address and len(values) == 1:
                time_stamp = values[0] + values_old[1]*2**16
                SetPiTime.linux_set_time(time_stamp)
                print(time_stamp)
            elif address == Setting.Pi_Time_stamp_Address+1 and len(values) == 1:
                time_stamp = values_old[0] + values[0]*2**16
                SetPiTime.linux_set_time(time_stamp)
                print(time_stamp)
        elif address == Setting.Extern_Zigbee_Address_Address and len(values) == 4:
            extern_address = values[0] + values[1] * 2**16 + values[2] * 2**32 + values[3] * 2**48

            # 写入队列编号
            self.queue.put(['set extern address', extern_address])

        # elif address == Setting.Hidden_Address and len(values) == 13:
        #     address_begin = Setting.get_sensor_address(values[0])
        #     values = values[1:]
        #     self.__set_analog_inputs_values(address_begin, values)
        else:
            pass
Ejemplo n.º 20
0
def url_for(User, service_type, endpoint_type=None):
    if endpoint_type is None:
        endpoint_type = 'publicURL'
        
    fallback_endpoint_type = None

    #catalog = User.service_catalog
    catalog = User.token.serviceCatalog
    service = get_service_from_catalog(catalog, service_type)
    if service:
        url = get_url_for_service(service,
                                  'regionone',
                                  endpoint_type)
        if not url and fallback_endpoint_type:
            url = get_url_for_service(service,
                                      'regionone',
                                      fallback_endpoint_type)
        if url:
            server = Setting.getServer()
            a = url[:4]
            b = str('//%s' % server)
            c = url.split(':')[2]
            d = [a, b, c]
            m = ':'.join(d)
            return m
Ejemplo n.º 21
0
def analy_host():
    server_dict = {}
    f=open(base64.decodestring(Setting.getFilename()))
    bufs= f.readlines()
    f.close()
    for line in bufs:
        if line.startswith('127.0.0.1') or \
            line.startswith('::1'):
            continue
        splits = line.split()
        if len(splits) == 0:
            pass
        elif len(splits) <= 3:
            key = " ".join(splits[1:])
            server_dict[key] = splits[0]
        
    client_dict = {}
    localname = open('/etc/hosts')
    bufs = localname.readlines()
        
    for line in bufs:
        if line.startswith('127.0.0.1') or \
            line.startswith('::1') or \
            line.startswith('#') :
            continue
        splits = line.split()
        if len(splits) >= 2:
            key = " ".join(splits[1:])
            client_dict[key] = splits[0]
    localname.close()

    for key in server_dict:
        client_dict[key] = server_dict[key]
    update_hosts(client_dict)
Ejemplo n.º 22
0
    def push(self):
        """ push notice
		"""
        if (Setting.get('notifier_archive', False)):
            self.metric.value = {'type': Notifier.type, 'text': Notifier.text}
        if (Notifier.display):
            Notifier.callback()
Ejemplo n.º 23
0
 def onBtn_Setting(self, str):
     if finish == 1:
         set = Setting.SettingUi(str)
         set.exec()
     else:
         reply = WarningBox.WarningBox('初始化未完成')
         reply.show()
Ejemplo n.º 24
0
def Check_hosts():
    if Setting.getServer() == '':
        return None

    url = Update.GetUrl()
    try:
        remote = urllib2.urlopen(url + ':5009/hosts')
        Logger.info("Read the hosts file successful!")
    except:
        Logger.info("Read the hosts file unsuccessful!")
        return
    server_dict = {}

    while True:
        buf = remote.readline()
        if not buf:
            break
        if buf.startswith("#") or \
            buf.startswith("127.0.0.1") or \
            buf.startswith("::1"):
            pass
        else:
            splits = buf.split()
            if len(splits) >= 2:
                key = " ".join(splits[1:])
                server_dict[key] = splits[0]

    update_hosts(server_dict)
Ejemplo n.º 25
0
    def worker(self, ch, method, properties, msg):
        try:
            if properties.type == "cmd":
                if properties.headers.get(
                        'host') == Setting.syncn().config["id"]:
                    # if self.debug: print(msg, properties.headers.get('host'), Setting.syncn().config["id"])
                    print("is me!!!!! no exit!!!!")
                    ch.basic_ack(delivery_tag=method.delivery_tag)
                else:
                    print("Another Computer connected!!")
                    ch.basic_ack(delivery_tag=method.delivery_tag)
                    print("is not me!!!!! exit!!!!")
                    self.exitSignal.emit(True)
            else:
                self.killSignal.emit(True)
                DAO = NoteSql.DAO()
                if DAO.sync(json.loads(msg)["res"])["res"]:
                    self.execSignal.emit(True)
                    print("[+] OK - sync send mail")

                if self.once:
                    ch.cancel()
                    ch.close()
                    self.once = False
                    print("end worker no ack so 1 msg in queue")
                    return
                else:
                    ch.basic_ack(delivery_tag=method.delivery_tag)
                    print("ack")
        except Exception as e:
            ch.cancel()
            ch.close()
            print("worker, check this {0}".format(e))
Ejemplo n.º 26
0
def preprocess(config_path, contest):
    config_path = os.path.join(config_path, "*.json")
    config_list = glob.glob(config_path)
    config_list = sorted(config_list)
    for config in config_list:
        is_train = True
        if "Test" in config:
            is_train = False
        name = config.split(os.path.sep)[-1][:-5]
        setting = Setting(path=config, name=name)
        path = setting.rawDataPath
        path = os.path.join(path, name)
        data = Data()
        feature = Feature(setting)
        for sequence in range(setting.splitNum):
            X_train, y_train = data.processSubject(
                path,
                is_train=is_train,
                contest=contest,
                split_number=setting.splitNum,
                sequence=sequence)
            X_pca_train, y_pca_train = feature.pca(X_train,
                                                   y_train,
                                                   window_length=30)
            feature.saveToDisk(feature_name="pca",
                               name=str(sequence),
                               is_train=is_train)
            X_fft_train, y_fft_train = feature.fft(X_train,
                                                   y_train,
                                                   window_length=30)
            feature.saveToDisk(feature_name="fft",
                               name=str(sequence),
                               is_train=is_train)
 def __init__(self, subjectName, settingPath):
     self.subjectName = subjectName
     self.setting = Setting(settingPath).loadSettings(name=subjectName)
     self.resultArrayX = None
     self.resultArrayY = None
     self.classZeroHistogram = None  #for paper "Epileptic seizure prediction using relative spectral power features"
     self.classOneHistogram = None  #for paper "Epileptic seizure prediction using relative spectral power features"
Ejemplo n.º 28
0
    def write_time_to_zigbee(self):
        """通过串口向zigbee写系统时间(bytes)
        """

        time_bytes = Setting.get_time_bytes()
        self._ser.write(b'$settime$' + time_bytes)
        logger.info('$settime$ ' + str(time_bytes))
Ejemplo n.º 29
0
    def _init_system_parameter(self):
        """系统参数数据初始化,通过定义
        """

        address_begin, values = Setting.get_system_parameter_address_and_values()
        self._set_analog_inputs_values(address_begin, values)
        print("system_parameter初始化成功")
Ejemplo n.º 30
0
 def AutoLogin(self, event):
     Logger.info("VPN Status : Autologin VPN account!")
     Setting.setVPNAuto(self.autologCheck.GetValue())
     if self.autologCheck.GetValue() == True:
         self.rempassCheck.SetValue(True)
         Setting.setVPNRem(True)
     Setting.save()
     thread = threading.Thread(target=self.LoginVPN(Setting.getVPNServer(), Setting.getVPNUser(), Setting.getVPNPass()))
     thread.start()
Ejemplo n.º 31
0
def admin_settings():
    available_themes = [
        x.identifier for x in get_themes_list() if x.identifier != 'admin']
    settings = Setting.all()
    for setting in settings:
        if setting.name == 'blog-theme':
            setting.allowed = json.dumps(available_themes)
    return render_template('settings.html', settings=settings)
Ejemplo n.º 32
0
def get_settings():
    '''
    Gets all the settings for the app.
    '''
    settings = {}
    all_settings = Setting.all()
    for setting in all_settings:
        settings[setting.name.strip()] = setting.val

    return settings
Ejemplo n.º 33
0
def admin_settings_post():
    return_value = success('All settings have been updated.')
    payload = get_payload(request)

    for key in payload:
        setting = Setting.filter(Setting.name == key).first()
        setting.value = payload[key]
        setting.insert()

    safe_commit()

    return jsonify(return_value)
Ejemplo n.º 34
0
	def __init__(self, log = False, display = True):
		try:
			Notifier.display
		except:
			Notifier.display = display
			Notifier.type = 'notice'
			Notifier.text = ''
			Notifier.time = 0
			Notifier.callback = self.printNotice
		self.now = lambda: int(round(time.time() * 1000))
		if(Setting.get('notifier_archive', False)):
			self.metric = NotifierMetric()
Ejemplo n.º 35
0
	def __init__(self,parent):
		Tkinter.Tk.__init__(self,parent)
		self.screen = { 'width': self.winfo_screenwidth(), 'height': self.winfo_screenheight() }
		self.widgets, self.menus = {}, {}
		self.title('AllMyServos')
		self.parent = parent
		self.setting = Setting()
		if(PreFlight.status()):
			self.specification = self.getClass('Specification.Specification')() #avoids importing before preflight checks
			self.scheduler = Scheduler()
			self.motionScheduler = self.getClass('Motion.MotionScheduler')(self.specification, self.scheduler)
			self.initTheme()
			self.initFrames()
			self.setup()
		else:
			self.initTheme()
			self.initFrames()
			self.setupPreFlight()
Ejemplo n.º 36
0
	def push(self):
		if(Setting.get('notifier_archive', False)):
			self.metric.value = { 'type': Notifier.type, 'text': Notifier.text }
		if(Notifier.display):
			Notifier.callback()
Ejemplo n.º 37
0
def get_setting(name, default):
    setting = Setting.filter(Setting.name == name).first()
    if setting and setting.val is not None and setting.val is not "":
        return setting.val
    else:
        return default
Ejemplo n.º 38
0
	def OnAddSettingClick(self):
		self.setting = Setting()
		self.editSetting()
Ejemplo n.º 39
0
class TkSettingManager(TkPage):
	def __init__(self, parent, gui, **options):
		super(TkSettingManager,self).__init__(parent, gui, **options)
		self.s = Setting()
	def setup(self):
		try:
			self.gui.menus['settings']
		except:
			self.gui.menus['settings'] = Tkinter.Menu(self.gui.menubar, tearoff=0, bg=self.colours['menubg'], fg=self.colours['menufg'], activeforeground=self.colours['menuactivefg'], activebackground=self.colours['menuactivebg'])
			self.addMenu(label="Settings", menu=self.gui.menus['settings'])
		self.gui.menus['settings'].insert_separator(1)
		self.gui.menus['settings'].insert_command(label="All Settings", index=2, command=self.OnListSettingsClick)
	
	#=== VIEWS ===#
	def listSettings(self):
		self.open()
		self.gridrow = 0
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Setting Manager / Settings', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		self.widgets['addsetting'] = Tkinter.Button(self.widgets['tframe'],text=u"Add Setting", image=self.images['add'], command=self.OnAddSettingClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['addsetting'].grid(column=1,row=self.gridrow)
		self.gridrow += 1
		self.settings = self.s.query(order = 'name', keyindex= False)

		self.widgets['settingFrame'] = Tkinter.Frame(self.widgets['tframe'], borderwidth=0, highlightthickness=0, bg=self.colours['bg'])
		self.widgets['settingFrame'].grid(column=0,row=self.gridrow, columnspan=2,sticky='E')
		
		if(len(self.settings) > 0):
			self.widgets['nameLabel'] = Tkinter.Label(self.widgets['settingFrame'],text='Name', bg=self.colours['bg'], fg=self.colours['fg'])
			self.widgets['nameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
			self.widgets['typeLabel'] = Tkinter.Label(self.widgets['settingFrame'],text='Type', bg=self.colours['bg'], fg=self.colours['fg'])
			self.widgets['typeLabel'].grid(column=1,row=self.gridrow,sticky='EW')
			self.widgets['valueLabel'] = Tkinter.Label(self.widgets['settingFrame'],text='Value', bg=self.colours['bg'], fg=self.colours['fg'])
			self.widgets['valueLabel'].grid(column=2,row=self.gridrow,sticky='EW')
			self.widgets['editLabel'] = Tkinter.Label(self.widgets['settingFrame'],text='Edit', bg=self.colours['bg'], fg=self.colours['fg'])
			self.widgets['editLabel'].grid(column=3,row=self.gridrow,sticky='EW')
			self.widgets['deleteLabel'] = Tkinter.Label(self.widgets['settingFrame'],text='Delete', bg=self.colours['bg'], fg=self.colours['fg'])
			self.widgets['deleteLabel'].grid(column=4,row=self.gridrow,sticky='EW')
			self.gridrow += 1
			rowcount = 0
			for s in self.settings:
				rowcolour = self.colours['rowbg']
				if(rowcount % 2 == 0):
					rowcolour = self.colours['rowaltbg']
				rowcount += 1
				self.widgets['name'+str(self.gridrow)] = Tkinter.Label(self.widgets['settingFrame'],text=self.settings[s].name, bg=rowcolour, fg=self.colours['fg'], height=2)
				self.widgets['name'+str(self.gridrow)].grid(column=0,row=self.gridrow,sticky='EW')
				self.widgets['type'+str(self.gridrow)] = Tkinter.Label(self.widgets['settingFrame'],text=self.settings[s].type, bg=rowcolour, fg=self.colours['fg'], height=2)
				self.widgets['type'+str(self.gridrow)].grid(column=1,row=self.gridrow,sticky='EW')
				self.widgets['value'+str(self.gridrow)] = Tkinter.Label(self.widgets['settingFrame'],text=self.settings[s].value, bg=rowcolour, fg=self.colours['fg'], height=2)
				self.widgets['value'+str(self.gridrow)].grid(column=2,row=self.gridrow,sticky='EW')
				self.widgets['edit'+str(self.gridrow)] = Tkinter.Button(self.widgets['settingFrame'],text=u"Edit Setting", image=self.images['process'], bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'], command=lambda x = self.settings[s].name:self.OnEditSettingClick(x))
				self.widgets['edit'+str(self.gridrow)].grid(column=3,row=self.gridrow,sticky='EW')
				self.widgets['delete'+str(self.gridrow)] = Tkinter.Button(self.widgets['settingFrame'],text=u"Delete Setting", image=self.images['delete'], bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'], command=lambda x = self.settings[s].name:self.OnDeleteSettingClick(x))
				self.widgets['delete'+str(self.gridrow)].grid(column=4,row=self.gridrow,sticky='EW')
				self.gridrow += 1
			
			self.widgets['egg'] = Tkinter.Button(self.widgets['settingFrame'], bg=self.colours['bg'], activebackground='#000000', highlightbackground=self.colours['bg'], highlightthickness=0, borderwidth=0, command=self.OnEggClick, height=1, width=1)
			self.widgets['egg'].grid(column=4,row=self.gridrow,sticky='EW')
		else:
			self.widgets['emptylabel'] = Tkinter.Label(self.widgets['settingFrame'], text="There are currently no settings", bg=self.colours['bg'], fg=self.colours['fg'], height=2)
			self.widgets['emptylabel'].grid(column=0,row=self.gridrow,sticky='EW')
			self.gridrow += 1
	def editSetting(self):
		self.open()
		self.gridrow = 0
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Edit Setting', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,columnspan=2,sticky='EW')
		self.gridrow += 1
		
		self.widgets['nameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Name', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['nameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['name'] = Tkinter.StringVar()
		self.widgets['nameentry'] = Tkinter.Entry(self.widgets['tframe'], textvariable=self.variables['name'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
		self.widgets['nameentry'].grid(column=1,row=self.gridrow,sticky='EW')
		if hasattr(self.setting, 'rowid'):
			self.variables['name'].set(self.setting.name)
		
		self.gridrow += 1
		
		self.widgets['typeLabel'] = Tkinter.Label(self.widgets['tframe'],text='Type', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['typeLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.variables['type'] = Tkinter.StringVar()
		self.widgets['typeentry'] = Tkinter.OptionMenu(self.widgets['tframe'],self.variables['type'], 'string', 'int', 'long', 'float', 'complex', 'bool', command=self.OnChangeType)
		self.widgets['typeentry'].config(bg=self.colours['inputbg'], fg=self.colours['inputfg'], activeforeground=self.colours['activefg'], activebackground=self.colours['activebg'])
		self.widgets['typeentry'].grid(column=1,row=self.gridrow,sticky='EW')
		if hasattr(self.setting, 'rowid'):
			self.variables['type'].set(self.setting.type)
		
		self.gridrow += 1
		
		self.widgets['valueLabel'] = Tkinter.Label(self.widgets['tframe'],text='Value', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['valueLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.valueframerow = self.gridrow
		
		self.OnChangeType()
		
		self.gridrow += 1
		
		self.widgets['optionsFrame'] = Tkinter.Frame(self.widgets['tframe'], bg=self.colours['bg'])
		self.widgets['optionsFrame'].grid(column=0,row=self.gridrow,columnspan=2, sticky='EW')
		
		self.gridrow = 0
		
		self.widgets['backLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Back', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['backLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		self.widgets['saveLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Save', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['saveLabel'].grid(column=1,row=self.gridrow,sticky='EW')
		if hasattr(self.setting, 'rowid'):
			self.widgets['deleteLabel'] = Tkinter.Label(self.widgets['optionsFrame'],text='Delete', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
			self.widgets['deleteLabel'].grid(column=2,row=self.gridrow,sticky='EW')
		self.gridrow += 1
		self.widgets['back'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Back", image=self.images['back'], command=self.listSettings, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['back'].grid(column=0,row=self.gridrow)
		self.widgets['savesetting'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Save Setting", image=self.images['save'], command=self.OnSaveSettingClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['savesetting'].grid(column=1,row=self.gridrow)
		if hasattr(self.setting, 'rowid'):
			self.widgets['deletesetting'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Delete Setting", image=self.images['delete'], command=self.OnDeleteSettingClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
			self.widgets['deletesetting'].grid(column=2,row=self.gridrow)
	def egg(self):
		self.open()
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Congratulations, you found an eggy wegg!', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,columnspan=2,sticky='EW')
		self.gridrow += 1
		self.e = Egg.EggyWegg.open()
		self.widgets['typeLabel'] = Tkinter.Label(self.widgets['tframe'],image=self.e['yolk'], bg=self.colours['bg'], fg=self.colours['fg'])
		self.widgets['typeLabel'].grid(column=0,row=self.gridrow,sticky='EW')
	def deleteSetting(self):
		self.open()
		self.gridrow = 0
		self.widgets['frameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Delete Setting', anchor=NW, bg=self.colours['bg'], fg=self.colours['headingfg'], font=self.fonts['heading'])
		self.widgets['frameLabel'].grid(column=0,row=self.gridrow,columnspan=2,sticky='EW')
		self.gridrow += 1
		
		self.widgets['confirmLabel'] = Tkinter.Label(self.widgets['tframe'],text='Are you sure you want to delete this setting?', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['confirmLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['nameLabel'] = Tkinter.Label(self.widgets['tframe'],text='Name', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['nameLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['nameData'] = Tkinter.Label(self.widgets['tframe'],text=self.setting.name, bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['nameData'].grid(column=1,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['typeLabel'] = Tkinter.Label(self.widgets['tframe'],text='Type', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['typeLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['typeData'] = Tkinter.Label(self.widgets['tframe'],text=self.setting.type, bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['typeData'].grid(column=1,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['valueLabel'] = Tkinter.Label(self.widgets['tframe'],text='Value', bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['valueLabel'].grid(column=0,row=self.gridrow,sticky='EW')
		
		self.widgets['valueData'] = Tkinter.Label(self.widgets['tframe'],text=self.setting.value, bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['valueData'].grid(column=1,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['optionsFrame'] = Tkinter.Frame(self.widgets['tframe'], bg=self.colours['bg'])
		self.widgets['optionsFrame'].grid(column=0,row=self.gridrow,columnspan=2, sticky='EW')
		
		self.gridrow = 0
		
		self.widgets['backlabel'] = Tkinter.Label(self.widgets['optionsFrame'],text="Back", bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['backlabel'].grid(column=0,row=self.gridrow,sticky='EW')
		self.widgets['acceptlabel'] = Tkinter.Label(self.widgets['optionsFrame'],text="Accept", bg=self.colours['bg'], fg=self.colours['fg'], height=2)
		self.widgets['acceptlabel'].grid(column=1,row=self.gridrow,sticky='EW')
		
		self.gridrow += 1
		
		self.widgets['cancelbutton'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Cancel", image=self.images['back'], command=self.OnCancelDeleteClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['cancelbutton'].grid(column=0,row=self.gridrow)
		self.widgets['confirmbutton'] = Tkinter.Button(self.widgets['optionsFrame'],text=u"Delete", image=self.images['accept'], command=self.OnDeleteSettingConfirmClick, bg=self.colours['buttonbg'], activebackground=self.colours['buttonhighlightbg'], highlightbackground=self.colours['buttonborder'])
		self.widgets['confirmbutton'].grid(column=1,row=self.gridrow)
	
	#=== ACTIONS ===#
	def OnChangeType(self, value = None):
		try:
			self.widgets['valueframe'].grid_forget()
		except:
			pass
		self.widgets['valueframe'] = Frame(self.widgets['tframe'],bg=self.colours['bg'])
		self.widgets['valueframe'].grid(column=1,row=self.valueframerow,sticky='EW')
		if(self.variables['type'].get() == 'bool'):
			self.variables['value'] = Tkinter.BooleanVar()
			self.widgets['valueentry'] = Tkinter.Checkbutton(self.widgets['valueframe'], text="Value", variable=self.variables['value'], bg=self.colours['inputbg'], fg=self.colours['inputfg'], activebackground=self.colours['activebg'], selectcolor=self.colours['inputbg'])
			self.widgets['valueentry'].grid(column=1,row=0,sticky='EW')
			if hasattr(self.setting, 'rowid'):
				self.variables['value'].set(bool(self.setting.value))
		else:
			self.variables['value'] = Tkinter.StringVar()
			self.widgets['valueentry'] = Tkinter.Entry(self.widgets['valueframe'], textvariable=self.variables['value'], bg=self.colours['inputbg'], fg=self.colours['inputfg'])
			self.widgets['valueentry'].grid(column=1,row=0,sticky='EW')
			if hasattr(self.setting, 'rowid'):
				self.variables['value'].set(self.setting.value)
	def OnListSettingsClick(self):
		self.listSettings()
	def OnEditSettingClick(self, name):
		self.setting = self.s.loadBy({'name': name})
		self.editSetting()
	def OnAddSettingClick(self):
		self.setting = Setting()
		self.editSetting()
	def OnSaveSettingClick(self):
		if(len(self.variables['name'].get()) == 0):
			self.editSetting()
			return False
		self.setting.name = self.variables['name'].get()
		val = self.variables['value'].get()
		try:
			if(self.variables['type'].get() == 'bool'):
				val = bool(self.variables['value'].get())
			elif(self.variables['type'].get() == 'int'):
				val = int(self.variables['value'].get())
			elif(self.variables['type'].get() == 'long'):
				val = long(self.variables['value'].get())
			elif(self.variables['type'].get() == 'float'):
				val = float(self.variables['value'].get())
			elif(self.variables['type'].get() == 'complex'):
				val = complex(self.variables['value'].get())
		except:
			self.editSetting()
			return False
		self.setting.value = val #auto saves
		self.notifier.addNotice('Setting saved')
		self.listSettings()
	def OnDeleteSettingClick(self, name = None):
		if(name != None):
			self.setting = self.s.loadBy({'name': name})
		self.deleteSetting()
	def OnDeleteSettingConfirmClick(self):
		self.setting.delete()
		self.setting = None
		self.notifier.addNotice('Setting deleted')
		self.listSettings()
	def OnCancelDeleteClick(self):
		self.listSettings()
	def OnEggClick(self):
		self.egg()
Ejemplo n.º 40
0
class GUI(Tkinter.Tk):
	def __init__(self,parent):
		Tkinter.Tk.__init__(self,parent)
		self.screen = { 'width': self.winfo_screenwidth(), 'height': self.winfo_screenheight() }
		self.widgets, self.menus = {}, {}
		self.title('AllMyServos')
		self.parent = parent
		self.setting = Setting()
		if(PreFlight.status()):
			self.specification = self.getClass('Specification.Specification')() #avoids importing before preflight checks
			self.scheduler = Scheduler()
			self.motionScheduler = self.getClass('Motion.MotionScheduler')(self.specification, self.scheduler)
			self.initTheme()
			self.initFrames()
			self.setup()
		else:
			self.initTheme()
			self.initFrames()
			self.setupPreFlight()
	def setupPreFlight(self):
		'''
		initializes the interface for pre flight checks
		'''
		self.menubar = Tkinter.Menu(self, bg=self.colours['menubg'], fg=self.colours['menufg'], activeforeground=self.colours['menuactivefg'], activebackground=self.colours['menuactivebg'])
		#logo
		c = self.getClass('TkPreFlightManager.TkPreFlightLogo')
		w = {
			'name': 'TkPreFlightManager.TkPreFlightLogo',
			'row': 0,
			'column': 0,
			'width': None,
			'height': None,
			'rowspan': None, 
			'columnspan': None, 
			'padx': 0, 
			'pady': 0, 
			'sticky': 'NS', 
			'scrollable': False,
			'rowweight': 1, 
			'columnweight': 1,
			'menuindex': 1
		}
		self.widgets['main'] = { c.__name__ : c(parent=self.frames['left'], gui=self, **w) }
		#checks
		c = self.getClass('TkPreFlightManager.TkPreFlightManager')
		w = {
			'name': 'TkPreFlightManager.TkPreFlightManager',
			'row': 0,
			'column': 0,
			'width': None,
			'height': None,
			'rowspan': None, 
			'columnspan': None, 
			'padx': 10, 
			'pady': 10, 
			'sticky': 'WENS', 
			'scrollable': False,
			'rowweight': 1, 
			'columnweight': 1,
			'menuindex': 1
		}
		self.widgets['main'] = { c.__name__ : c(parent=self.frames['main'], gui=self, **w) }
		self.config(menu=self.menubar)
		self.widgets['main']['TkPreFlightManager'].OnChecksClick()
		#screens
		c = self.getClass('TkPreFlightManager.TkPreFlightScreens')
		w = {
			'name': 'TkPreFlightManager.TkPreFlightScreens',
			'row': 0,
			'column': 0,
			'width': None,
			'height': None,
			'rowspan': None, 
			'columnspan': None, 
			'padx': 0, 
			'pady': 0, 
			'sticky': 'NS', 
			'scrollable': False,
			'rowweight': 1, 
			'columnweight': 1,
			'menuindex': 1
		}
		self.widgets['main'] = { c.__name__ : c(parent=self.frames['right'], gui=self, **w) }
	def setup(self):
		'''
		initializes the menubar and adds frames and widgets from the theme profile
		'''
		self.menubar = Tkinter.Menu(self, bg=self.colours['menubg'], fg=self.colours['menufg'], activeforeground=self.colours['menuactivefg'], activebackground=self.colours['menuactivebg'])

		for f in self.theme.profile['frames']: # each frame in the profile
			self.widgets[f['name']] = {} # make a slot for this frame
			for w in f['widgets']: # each widget in the frame
				c = self.getClass(w['name']) # get a reference to the class
				self.widgets[f['name']][c.__name__] = c(parent=self.frames[f['name']], gui=self, **w) # initialize the class with attributes from the profile
		self.config(menu=self.menubar)
		if(len(self.specification.servos) > 0):
			self.widgets['main']['TkMotionManager'].OnListMotionsClick() # if servos exist in this specification open the motion manager
		else:
			self.widgets['main']['TkServoManager'].OnListServosClick() # otherwise open the servo manager
	def initTheme(self):
		'''
		loads the current theme
		'''
		self.theme = Theme(self.setting.get('gui_theme_name','DarkBlue'), self.screen)
		self.theme.load()
		self.images, self.colours, self.fonts = {}, {}, {}
		for k, v in self.theme.images.iteritems():
			self.images[k] = Tkinter.PhotoImage(file = os.path.join(self.theme.basepath, v))
		self.colours = self.theme.colours
		for k, v in self.theme.fonts.iteritems():
			self.fonts[k] = tkFont.Font(family=v['family'], size=v['size'])
	def initFrames(self):
		'''
		creates frames according to the profile
		'''
		self.frames = {}
		if(self.theme.profile != None):
			profile = self.theme.profile
			self.frames['appWrap'] = Tkinter.Frame(self, bg=self.colours['bg'], borderwidth=0, highlightthickness=0)
			self.frames['appWrap'].pack(fill=BOTH, expand=1)
			self.frames['appWrap'].columnconfigure(0, weight=1)
			self.frames['appWrap'].rowconfigure(0, weight=1)
			self.frames['appCanvas'] = Tkinter.Canvas(self.frames['appWrap'], borderwidth=0, bg=self.colours['bg'], highlightthickness=0)
			self.frames['appCanvas'].grid(column=0,row=0, padx= 10,sticky='WENS')
			self.frames['app'] = Tkinter.Frame(self.frames['appCanvas'], bg=self.colours['bg'], borderwidth=0, highlightthickness=0)
			self.frames['app'].pack(fill=BOTH, expand=1)
			if(profile['scrollable']): #makes the whole window scrollable for accessibility
				self.frames['appyScroller'] = Tkinter.Scrollbar(self.frames['appWrap'], orient=VERTICAL, command=self.frames['appCanvas'].yview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
				self.frames['appyScroller'].grid(column=1, row=0, sticky="NS")
				self.frames['appxScroller'] = Tkinter.Scrollbar(self.frames['appWrap'], orient=HORIZONTAL, command=self.frames['appCanvas'].xview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
				self.frames['appxScroller'].grid(column=0, row=1, sticky="EW")
				self.frames['appCanvas'].configure(yscrollcommand=self.frames['appyScroller'].set, xscrollcommand=self.frames['appxScroller'].set, bg=self.colours['bg'])
				self.frames['appCanvas'].create_window((0,0),window=self.frames['app'], anchor=NW)
				self.frames['app'].bind("<Configure>", self.scroll)
			for f in profile['frames']:
				self.frames['{0}{1}'.format(f['name'], 'Wrap')] = Tkinter.Frame(self.frames['app'], bg=self.colours['bg'], borderwidth=0, highlightthickness=0)
				self.frames['{0}{1}'.format(f['name'], 'Wrap')].grid(column=f['column'],row=f['row'],columnspan=f['columnspan'],rowspan=f['rowspan'],sticky=f['sticky'])
				if (f['columnweight'] > 0):
					self.frames['app'].columnconfigure(f['column'], weight=f['columnweight'])
				if (f['rowweight'] > 0):
					self.frames['app'].rowconfigure(f['row'], weight=f['rowweight'])
				self.frames['{0}{1}'.format(f['name'], 'Wrap')].columnconfigure(0, weight=1)
				self.frames['{0}{1}'.format(f['name'], 'Wrap')].rowconfigure(0, weight=1)
				self.frames['{0}{1}'.format(f['name'], 'Canvas')] = Tkinter.Canvas(self.frames['{0}{1}'.format(f['name'], 'Wrap')], borderwidth=0, bg=self.colours['bg'], highlightthickness=0)
				self.frames['{0}{1}'.format(f['name'], 'Canvas')].grid(column=0,row=0,sticky='WENS')
				self.frames['{0}{1}'.format(f['name'], 'Canvas')].columnconfigure(0, weight=1)
				self.frames['{0}{1}'.format(f['name'], 'Canvas')].rowconfigure(0, weight=1)
				self.frames[f['name']] = Tkinter.Frame(self.frames['{0}{1}'.format(f['name'], 'Canvas')], bg=self.colours['bg'], borderwidth=0, highlightthickness=0)
				self.frames[f['name']].grid(column=0,row=0,sticky='WENS')
				self.frames[f['name']].columnconfigure(0, weight=1)
				self.frames[f['name']].rowconfigure(0, weight=1)
				if(f['scrollable']): # makes this frame scrollable
					self.frames['{0}{1}'.format(f['name'], 'yScroller')] = Tkinter.Scrollbar(self.frames['{0}{1}'.format(f['name'], 'Wrap')], orient=VERTICAL, command=self.frames['{0}{1}'.format(f['name'], 'Canvas')].yview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
					self.frames['{0}{1}'.format(f['name'], 'yScroller')].grid(column=1, row=0, sticky="NS")
					self.frames['{0}{1}'.format(f['name'], 'xScroller')] = Tkinter.Scrollbar(self.frames['{0}{1}'.format(f['name'], 'Wrap')], orient=HORIZONTAL, command=self.frames['{0}{1}'.format(f['name'], 'Canvas')].xview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
					self.frames['{0}{1}'.format(f['name'], 'xScroller')].grid(column=0, row=1, sticky="EW")
					self.frames['{0}{1}'.format(f['name'], 'Canvas')].configure(yscrollcommand=self.frames['{0}{1}'.format(f['name'], 'yScroller')].set, xscrollcommand=self.frames['{0}{1}'.format(f['name'], 'xScroller')].set)
					self.frames['{0}{1}'.format(f['name'], 'Canvas')].create_window((0,0),window=self.frames[f['name']], anchor=NW)
					self.frames[f['name']].bind("<Configure>", self.scroll)
		else:
			# fallback layout
			self.frames['header'] = Tkinter.Frame(self, borderwidth=0, bg = self.colours['bg'])
			self.frames['header'].grid(row = 0, column = 0, rowspan = 1, columnspan = 3, padx= 10, sticky = "WENS")
			self.frames['left'] = Tkinter.Frame(self, borderwidth=0, bg = self.colours['bg'])
			self.frames['left'].grid(row = 1, column = 0, sticky = "WENS")
			
			self.frames['mainWrap'] = Tkinter.Frame(self, bg=self.colours['bg'], borderwidth=0, highlightthickness=0)
			self.frames['mainWrap'].grid(column=1,row=1,sticky='NW')
			
			self.frames['mainCanvas'] = Tkinter.Canvas(self.frames['mainWrap'], borderwidth=0, bg=self.colours['bg'], highlightthickness=0, width=920, height=710)
			self.frames['mainCanvas'].grid(column=0,row=0, padx= 10,sticky='NE')
			
			self.frames['main'] = Tkinter.Frame(self.frames['mainCanvas'], bg=self.colours['bg'], borderwidth=0, highlightthickness=0)
			self.frames['main'].grid(column=0,row=0,sticky='NW')
			
			self.frames['yScroller'] = Tkinter.Scrollbar(self.frames['mainWrap'], orient=VERTICAL, command=self.frames['mainCanvas'].yview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
			self.frames['yScroller'].grid(column=1, row=0, sticky="NS")
			self.frames['xScroller'] = Tkinter.Scrollbar(self.frames['mainWrap'], orient=HORIZONTAL, command=self.frames['mainCanvas'].xview, bg=self.colours['bg'], activebackground=self.colours['handle'], troughcolor=self.colours['trough'])
			self.frames['xScroller'].grid(column=0, row=1, sticky="EW")
			
			self.frames['mainCanvas'].configure(yscrollcommand=self.frames['yScroller'].set, xscrollcommand=self.frames['xScroller'].set, bg=self.colours['bg'])
			self.frames['mainCanvas'].create_window((0,0),window=self.frames['main'], anchor=NW)
			self.frames['main'].bind("<Configure>", self.scroll)
			

			self.frames['right'] = Tkinter.Frame(self, borderwidth=0, bg = self.colours['bg'])
			self.frames['right'].grid(row = 1, column = 2, sticky = "WENS")
			
			self.frames['footerwrap'] = Tkinter.Frame(self, borderwidth=0, bg = self.colours['bg'])
			self.frames['footerwrap'].grid(row = 2, column = 0, columnspan= 3, sticky = "WENS")
			
			self.frames['footer'] = Tkinter.Frame(self.frames['footerwrap'], borderwidth=0, bg = self.colours['bg'])
			self.frames['footer'].grid(row = 0, column = 0, sticky = "WENS")
		
		self.configure(bg=self.colours['bg'], borderwidth=0)
		self.geometry('{}x{}'.format(self.screen['width'], self.screen['height']))
	def scroll(self, event):
		'''
		generic function to handle scrolling
		'''
		event.widget.master.configure(scrollregion=event.widget.master.bbox(ALL))
	def reset(self):
		'''
		resets the scrollbar to the top when changing widget in the main frame
		'''
		self.frames['mainCanvas'].yview('moveto', 0)
	def clearMain(self):
		'''
		convenience function which closes all widgets in the 'main' frame
		'''
		if('main' in self.widgets.keys()):
			for k, v in self.widgets['main'].iteritems():
				v.close()
		self.reset()
	def getClass(self, name):
		'''
		returns in uninstantiated class object from a string ([MODULE].[CLASS]). e.g. 'Logo.Logo'
		'''
		ns = name.split(".")
		modname = ns[0]
		classname = ns[1]
		if(len(ns) > 2):
			modname = '.'.join(ns[0:-2])
			classname = ns[-1]
		mod = __import__(modname)
		return getattr(mod, classname)
	def getModule(self, name):
		return __import__(name)
Ejemplo n.º 41
0
	def __init__(self, parent, gui, **options):
		super(TkSettingManager,self).__init__(parent, gui, **options)
		self.s = Setting()