def make_window(): global win_num win_num += 1 win = TestWindow(size=(260, 200), title="Text fields %d" % (win_num)) win.tf1 = TextField(position=(20, 20), width=200) #say("Field 1 Height =", win.tf1.height) ### win.tf2 = TextField(position=(20, win.tf1.bottom + 10), width=200, text="Spam\nGlorious Spam", multiline=True, lines=2) #say("Field 2 Height =", win.tf2.height) ### win.tf3 = TextField(position=(20, win.tf2.bottom + 10), width=200, font=fancy) show_but = Button("Show", position=(20, win.tf3.bottom + 20), action=(show_text, win)) sel_but = Button("Select", position=(show_but.right + 5, win.tf3.bottom + 20), action=(select_text, win)) new_but = Button("New", position=(sel_but.right + 5, win.tf3.bottom + 20), action=make_window) win.add(win.tf1) win.add(win.tf2) win.add(win.tf3) win.add(show_but) win.add(sel_but) win.add(new_but) win.height = show_but.bottom + 20 win.tf1.become_target() win.show() return win
def __init__(self): """This method is the constructor for a new credentials dialog.""" ModalDialog.__init__(self) #default the credentials information self._user = None self._password = None label = Label("Please enter your credentials.") self._ok_button = Button("OK", action = "ok", style = "default") self._cancel_button = Button("Cancel", style = "cancel", action = "cancel") self._user_box = TextField(width = 150) self._password_box = TextField(width = 150, password = "******", select_action = "password_click") self.place(label, left = 20, top = 20) self.place(self._user_box, top = label + 10, right = label.right) self.place(self._password_box, top = self._user_box.bottom + 10, right = label.right) self.place(self._ok_button, top = self._password_box.bottom + 20, right = label.right) self.place(self._cancel_button, top = self._ok_button.top, right = self._ok_button.left - 20) self.shrink_wrap(padding = (20, 20)) self._message_label = None #the parent class will use this function to set the title self.set_title( "Google Credentials" ) self._password_box.width = 150 self._Set_Text() self._user_canceled = False
def key_down(self, event): TextField.key_down(self, event) if not self.text: if self.emptyaction: self.emptyaction(*self.emptyactionargs) else: if self.action: self.action(*self.actionargs)
def main(): global cb1, cb2, rg win = Window(title="Place Me By Your Side", width=720, height=500) view1 = TestDrawing(width=320, height=200) cb1 = CheckBox(title="Check Me!", action=checked_it) cb2 = CheckBox(title="Check Me Too!", action=checked_it) rbs = [] for i in range(1, 4): rb = RadioButton(title="Hoopy Option %d" % i, value=i) rbs.append(rb) rg = RadioGroup(rbs, action=option_chosen) pb = Button(title="Push Me!", action=pushed_it) view2 = TestScrollableDrawing(width=300, height=300) label = Label(text="Flavour:") entry = TextField(width=200) win.place(view1, left=10, top=10, border=1) win.place_row([cb1, cb2], left=10, top=(view1, 20), spacing=20) win.place_column(rbs, left=view1 + 20, top=10) win.place(pb, right=-20, bottom=-10, anchor='rb') win.place(view2, left=rbs[0] + 20, top=10, right=-20, bottom=pb - 10, scrolling='hv', anchor='ltrb', border=1) win.place(label, left=10, top=(cb1, 20)) win.place( entry, left=10, top=(label, 10), #border = 1 ) entry.become_target() win.show() import GUI GUI.run()
def setupComponents(self, parent): separation = 5 bottom = self.height - 50 inventoryHeight = ((INVENTORYSLOTS - 1) / 8 + 1) * (30 + separation) descriptionHeight = 110 #EquipmentTopLeft = (10, 10) #InventoryTopLeft = (10, bottom - inventoryHeight) #InvDescriptionTopLeft = (10, bottom - inventoryHeight - descriptionHeight) #EquipDescriptionTopLeft = (10, bottom - inventoryHeight - descriptionHeight * 2) InventoryTopLeft = (10, 10) InvDescriptionTopLeft = (10, 10 + inventoryHeight) EquipmentTopLeft = (10, 10 + inventoryHeight + 10 + descriptionHeight + 20) EquipDescriptionTopLeft = (10, 10 + inventoryHeight + 10 + descriptionHeight + 20 + 2 * (30 + separation)) self.equipmentSlots = [] for i in range(EQUIPMENTSLOTS): on = len(self.equipmentSlots) esl = InventorySlot( position=(EquipmentTopLeft[0] + (30 + separation) * (on % 7), EquipmentTopLeft[1] + (30 + separation) * (on / 7))) self.equipmentSlots += [esl] esl.setupComponents(self, [EQUIPMENTSLOT, on]) self.add(esl) self.inventorySlots = [] for i in range(INVENTORYSLOTS): on = len(self.inventorySlots) isl = InventorySlot( position=(InventoryTopLeft[0] + (30 + separation) * (on % 8), InventoryTopLeft[1] + (30 + separation) * (on / 8))) self.inventorySlots += [isl] isl.setupComponents(self, [INVENTORYSLOT, on]) self.add(isl) self.inventoryDescriptionField = TextField( multiline=True, size=(self.width - InvDescriptionTopLeft[0] * 2, 100), position=InvDescriptionTopLeft, enabled=False) self.add(self.inventoryDescriptionField) self.equippedDescriptionField = TextField( multiline=True, size=(self.width - EquipDescriptionTopLeft[0] * 2, 100), position=EquipDescriptionTopLeft, enabled=False) self.add(self.equippedDescriptionField) ViewWithBackButton.setupComponents(self, parent)
def modal_dialog(): #global dlog ### dlog = ModalDialog(title="Spanish Inquisition", size=(200, 140)) dlog.place(Label(text="Surprise!!!"), left=20, top=20) field = TextField() dlog.place(field, left=20, top=60, right=-20) field.become_target() dlog.default_button = DefaultButton() dlog.cancel_button = CancelButton() dlog.place(dlog.default_button, right=-20, bottom=-20) dlog.place(dlog.cancel_button, left=20, bottom=-20) dlog.center() result = dlog.present() say("Result =", result) dlog.destroy()
def modal_dialog(): #global dlog ### dlog = ModalDialog(title = "Spanish Inquisition", size = (200, 140)) dlog.place(Label(text = "Surprise!!!"), left = 20, top = 20) field = TextField() dlog.place(field, left = 20, top = 60, right = -20) field.become_target() dlog.default_button = DefaultButton() dlog.cancel_button = CancelButton() dlog.place(dlog.default_button, right = -20, bottom = -20) dlog.place(dlog.cancel_button, left = 20, bottom = -20) dlog.center() result = dlog.present() say("Result =", result) dlog.destroy()
def main(): f = None args = sys.argv[1:] if args: fontsize = int(args[0]) sf = StdFonts.system_font f = Font(sf.family, fontsize, sf.style) #showfont("Using font", f) win = Window(title="Heights") if f: kwds = {'font': f} else: kwds = {} controls = [ Label(text="Label", **kwds), TextField(text="Text", **kwds), CheckBox(title="Check", **kwds), RadioButton(title="Radio", **kwds), Slider(orient='h', width=50), #Button(title = "Button", **kwds), ] #for ctl in controls: # say("Height of %r is %s" % (ctl, ctl.height)) win.place_row(controls, left=10, top=10) win.shrink_wrap(padding=(10, 10)) win.show() run()
def __init__(self, action, **kwargs): title = 'Password' self._action = action lbl_text = action.get_pass_desc() ModalDialog.__init__(self, title=title) label = Label(lbl_text) self.txt_passwd = TextField(multiline=False, password=True) self.ok_button = Button("Connect", action="ok", enabled=True, style='default') self.cancel_button = Button("Cancel", enabled=True, style='cancel', action='cancel') self.place(label, left=padding, top=padding) self.place(self.txt_passwd, left=padding, top=label + padding, right=label.right if label.right > 260 else 260) self.place(self.cancel_button, top=self.txt_passwd + padding, right=self.txt_passwd.right) self.place(self.ok_button, top=self.txt_passwd + padding, right=self.cancel_button - padding) self.shrink_wrap(padding=(padding, padding))
def make_window(): win = Window(size=(240, 100), title="Password") tf = TextField(position=(20, 20), width=200, password=True) ok = Button("OK", position=(20, 60), action=(show, tf)) win.add(tf) win.add(ok) win.show()
def __init__(self, emptyaction=None, action=None, **kwargs): if isinstance(emptyaction, tuple): self.emptyaction = emptyaction[0] self.emptyactionargs = emptyaction[1:] else: self.emptyaction = emptyaction self.emptyactionargs = [] if isinstance(action, tuple): self.action = action[0] self.actionargs = action[1:] else: self.action = action self.actionargs = [] TextField.__init__(self, **kwargs)
def _Create_Overall_Player_Frame( self ): """This method is used to create the overall player frame used when displaying the players.""" #retrieve the main frame from the GUI main_frame = self._main_gui.Get_Main_Frame() #create the overall player frame self._overall_player_frame = \ Frame( container = main_frame, anchor = "ltrb", size = ( main_frame.width, main_frame.height ) ) #create the search button self._player_search_button = Button( "Player Search", action = "Player_Search", style = "default" ) #put the button in the frame self._overall_player_frame.place( self._player_search_button, left = 0, top = 0 ) #create the text box self._player_search_field = \ TextField( width = number_constants.text_box_width ) #put the field on the frame self._overall_player_frame.place( \ self._player_search_field, left = self._player_search_button.right )
def make_row(align): return Row([ CheckBox("One"), Label("Two"), TextField(text="Three", size=(100, 50)), Button("Four"), ], expand=2, align=align)
def test(): def bing(): say("Bing!") #fld._win_dump_flags() win = Window(title = "Shrink Wrap", resizable = 0) but = Button("Bing!", action = bing) cbx = CheckBox("Spam") fld = TextField(width = 100) win.place(but, left = 20, top = 20) win.place(cbx, left = but + 20, top = 20) win.place(fld, left = 20, top = but + 20) win.shrink_wrap() win.show() application().run()
def setupComponents(self, parent): self.learnedAbilities = [] separation = 5 bottom = self.height - 50 inventoryHeight = ( (ABILITYDISPLAYSLOTS - 1) / 8 + 1) * (40 + separation) descriptionHeight = 110 EquipmentTopLeft = (self.width / 2, 10) InventoryTopLeft = (10, 10 + (40 + separation) + descriptionHeight + 10 * 2) EquipDescriptionTopLeft = (10, 10 + (40 + separation) + 10 * 1) self.abilitySlots = [] for i in range(ABILITYSLOTS): on = len(self.abilitySlots) abilSlot = AbilitySlot( position=(EquipmentTopLeft[0] + (40 + separation) * on - (40 + separation) * ABILITYSLOTS / 2, EquipmentTopLeft[1])) self.abilitySlots += [abilSlot] abilSlot.setupComponents(self, [EQUIPPEDSLOT, on]) self.add(abilSlot) self.learnedSlots = [] for i in range(ABILITYDISPLAYSLOTS): on = len(self.learnedSlots) isl = AbilitySlot( position=(InventoryTopLeft[0] + (40 + separation) * (on % 6), InventoryTopLeft[1] + (40 + separation) * (on / 6))) self.learnedSlots += [isl] isl.setupComponents(self, [LEARNEDSLOT, on]) self.add(isl) self.equippedDescriptionField = TextField( multiline=True, size=(self.width - EquipDescriptionTopLeft[0] * 2, 100), position=EquipDescriptionTopLeft, enabled=False) self.add(self.equippedDescriptionField) ViewWithBackButton.setupComponents(self, parent)
def open_create_ultimate_teams_window(window_x, window_y, db_dict, win_previous, player_judge_list=None, team_judge_list=None, file_name=None, roster=None, input_formation=None): display_items = [] # Get create ultimate team configuration values with open(config_filename, 'r') as f: settings = json.load(f)['ultimate_team_configs'] f.close() # Set the attributes lists if player_judge_list is not None: settings['player_sort_attributes'] = player_judge_list if team_judge_list is not None: settings['team_sort_attributes'] = team_judge_list if roster is None: roster = {} settings['roster'] = roster # Assign input formation, or lack thereof, to settings settings['input_formation'] = input_formation # ========== Window ========== win_ultimate_teams = Window() win_ultimate_teams.title = create_ultimate_teams_win_title win_ultimate_teams.auto_position = False win_ultimate_teams.position = (window_x, window_y) win_ultimate_teams.size = (win_width, win_height) win_ultimate_teams.resizable = 0 win_ultimate_teams.name = create_ultimate_teams_title + " Window" # ========== Window Image View ========== class CreateUltimateTeamsWindowImageView(View): def draw(self, c, r): c.backcolor = view_backcolor c.erase_rect(r) view = CreateUltimateTeamsWindowImageView(size=win_ultimate_teams.size) # ========== Title ========== title = Label(text=create_ultimate_teams_title) title.font = title_font title.width = title_width title.height = title_height title.x = (win_width - title_width) / 2 title.y = top_border title.color = title_color title.just = 'center' display_items.append(title) # ========== Settings ========== # ========== Current player list and formation list ========== file_name_width = 125 file_button_width = 200 # Functions for picking files def player_list_current_btn_func(): save_settings() settings['file_type'] = 'current_player_list' settings['file_changes'] = False settings['prev_window'] = 'team_creation' settings['prev_window_value'] = win_previous settings['create_team_name'] = team_list_name_tf.value PickFile.open_pick_file_window(win_ultimate_teams.x, win_ultimate_teams.y, db_dict, settings) win_ultimate_teams.hide() def player_db_current_btn_func(): save_settings() settings['file_type'] = 'current_player_db' settings['file_changes'] = False settings['prev_window'] = 'team_creation' settings['prev_window_value'] = win_previous settings['create_team_name'] = team_list_name_tf.value PickFile.open_pick_file_window(win_ultimate_teams.x, win_ultimate_teams.y, db_dict, settings) win_ultimate_teams.hide() def formation_list_current_btn_func(): save_settings() settings['file_type'] = 'current_formation_list' settings['file_changes'] = False settings['prev_window'] = 'team_creation' settings['prev_window_value'] = win_previous settings['create_team_name'] = team_list_name_tf.value PickFile.open_pick_file_window(win_ultimate_teams.x, win_ultimate_teams.y, db_dict, settings) win_ultimate_teams.hide() player_list_label = Label(text="Player List:", font=std_tf_font_bold, width=file_name_width, height=std_tf_height, x=(win_width-file_name_width-file_button_width-5)/2, y=title.bottom + title_border*3, color=title_color, just='right') display_items.append(player_list_label) player_list_button = Button(title=db_dict['player_list'][0], font=small_tf_font, width=file_button_width, height=std_tf_height, x=player_list_label.right + 5, y=player_list_label.top, color=title_color, just='center', action=player_list_current_btn_func) display_items.append(player_list_button) player_db_label = Label(text="Player DB:", font=std_tf_font_bold, width=file_name_width, height=std_tf_height, x=player_list_label.left, y=player_list_label.bottom + title_border, color=title_color, just='right') display_items.append(player_db_label) player_db_button = Button(title=db_dict['player_db'][0], font=small_tf_font, width=file_button_width, height=std_tf_height, x=player_list_label.right + 5, y=player_db_label.top, color=title_color, just='center', action=player_db_current_btn_func) display_items.append(player_db_button) formation_list_label = Label(text="Formation List:", font=std_tf_font_bold, width=file_name_width, height=std_tf_height, x=player_list_label.left, y=player_db_label.bottom + title_border, color=title_color, just='right') display_items.append(formation_list_label) formation_list_button = Button(title=db_dict['formation_list'][0], font=small_tf_font, width=file_button_width, height=std_tf_height, x=formation_list_label.right + 5, y=formation_list_label.top, color=title_color, just='center', action=formation_list_current_btn_func) display_items.append(formation_list_button) if input_formation is not None and input_formation['name'] != 'Generic': formation_list_button.enabled = 0 formation_list_button.title = input_formation['name'] settings_indent = 3*win_width/7 # ========== Team Name ========== tf_width = 235 team_name_label_width = 130 disabled_msg = "Disabled" team_list_name_label = Label(text="Team List Name: ", font=std_tf_font_bold, width=team_name_label_width, height=std_tf_height, x=settings_indent - team_name_label_width, y=formation_list_label.bottom + title_border*2, color=title_color, just='right') display_items.append(team_list_name_label) team_list_name_tf = TextField(font=std_tf_font, width=tf_width, height=std_tf_height + 5, x=team_list_name_label.right + small_button_spacing, y=team_list_name_label.top) display_items.append(team_list_name_tf) if file_name is not None: team_list_name_tf.value = file_name radio_btn_width = 75 radio_btn_space = 5 # ========== Process Type Label ========== process_type_label = Label(text="Processing Type: ", font=std_tf_font_bold, width=std_tf_width, height=std_tf_height, x=settings_indent - std_tf_width, y=team_list_name_label.bottom + title_border, color=title_color, just='right') display_items.append(process_type_label) def get_process_type_rg(): settings['process_type'] = process_type_radio_group.value win_ultimate_teams.become_target() process_type_radio_group = RadioGroup(action=get_process_type_rg) # Process Type Radio Buttons multi_process_radio_btn = RadioButton('Multi', width=radio_btn_width, x=process_type_label.right + radio_btn_space, y=process_type_label.top, group=process_type_radio_group, value='multi') display_items.append(multi_process_radio_btn) single_process_radio_btn = RadioButton('Single', width=radio_btn_width, x=multi_process_radio_btn.right + radio_btn_space, y=process_type_label.top, group=process_type_radio_group, value='single') display_items.append(single_process_radio_btn) process_type_radio_group.value = settings['process_type'] # If building a team based on one formation, there is no benefit to using multiple processes. if input_formation is not None: if input_formation['name'] != 'Generic': process_type_radio_group.value = 'single' settings['process_type'] = 'single' multi_process_radio_btn.enabled = 0 single_process_radio_btn.enabled = 0 # ========== Chemistry Matters Label ========== chemistry_matters_label = Label(text="Chemistry Matters: ", font=std_tf_font_bold, width=std_tf_width, height=std_tf_height, x=settings_indent - std_tf_width, y=process_type_label.bottom + title_border, color=title_color, just='right') display_items.append(chemistry_matters_label) def get_chemistry_matters_rg(): settings['chemistry_matters'] = chemistry_matters_radio_group.value win_ultimate_teams.become_target() chemistry_matters_radio_group = RadioGroup(action=get_chemistry_matters_rg) # Process Type Radio Buttons multi_process_radio_btn = RadioButton('Yes', width=radio_btn_width, x=chemistry_matters_label.right + radio_btn_space, y=chemistry_matters_label.top, group=chemistry_matters_radio_group, value=True) display_items.append(multi_process_radio_btn) single_process_radio_btn = RadioButton('No', width=radio_btn_width, x=multi_process_radio_btn.right + radio_btn_space, y=chemistry_matters_label.top, group=chemistry_matters_radio_group, value=False) display_items.append(single_process_radio_btn) chemistry_matters_radio_group.value = settings['chemistry_matters'] # ========== Judging Teams Label ========== judging_teams_label = Label(text="How to Judge Teams: ", font=std_tf_font_bold, width=std_tf_width, height=std_tf_height, x=settings_indent - std_tf_width, y=chemistry_matters_label.bottom + title_border, color=title_color, just='right') display_items.append(judging_teams_label) judging_teams_attributes = Label(font=std_tf_font, width=std_tf_width, height=std_tf_height, x=judging_teams_label.right + radio_btn_space, y=judging_teams_label.top, color=title_color, just='left') judging_teams_attributes_text = '' for attr in settings['team_sort_attributes']: judging_teams_attributes_text += format_attr_name(attr) + ', ' # Remove extra comma and space judging_teams_attributes_text = judging_teams_attributes_text[:-2] # Truncate if too long if len(judging_teams_attributes_text) > 26: judging_teams_attributes_text = judging_teams_attributes_text[:26] + '...' judging_teams_attributes.text = judging_teams_attributes_text display_items.append(judging_teams_attributes) # Judging Teams Edit Button def judging_teams_edit_btn_func(): save_settings() attr_dict = {} attr_list = settings['team_sort_attributes'] attr_type = 'team_sort' attribute_settings = {'window': 'ultimate_team_judging', 'file_name': team_list_name_tf.value, 'roster': roster, 'input_formation': input_formation, 'prev_window_value': win_previous} AddAttribute.open_attribute_window( win_ultimate_teams.x, win_ultimate_teams.y, db_dict, attr_dict, attr_list, attr_type, attribute_settings) win_ultimate_teams.hide() judging_edit_btn_width = 40 judging_teams_edit_btn = Button("Edit", #x=teams_to_return_tf.right - judging_edit_btn_width, x=judging_teams_attributes.right, y=judging_teams_label.top, height=small_button_height-7, width=judging_edit_btn_width, font=small_button_font, action=judging_teams_edit_btn_func, style = 'default', color=button_color, just='right') display_items.append(judging_teams_edit_btn) # ========== Judging Players Label ========== judging_players_label = Label(text="How to Judge Players: ", font=std_tf_font_bold, width=std_tf_width, height=std_tf_height, x=settings_indent - std_tf_width, y=judging_teams_label.bottom + title_border, color=title_color, just='right') display_items.append(judging_players_label) judging_players_attributes = Label(font=std_tf_font, width=std_tf_width, height=std_tf_height, x=judging_players_label.right + radio_btn_space, y=judging_players_label.top, color=title_color, just='left') judging_players_attributes_text = '' for attr in settings['player_sort_attributes']: judging_players_attributes_text += format_attr_name(attr) + ', ' # Remove extra comma and space judging_players_attributes_text = judging_players_attributes_text[:-2] # Truncate if too long if len(judging_players_attributes_text) > 26: judging_players_attributes_text = judging_players_attributes_text[:26] + '...' judging_players_attributes.text = judging_players_attributes_text display_items.append(judging_players_attributes) # Judging Teams Edit Button def judging_players_edit_btn_func(): save_settings() attr_dict = {} attr_list = settings['player_sort_attributes'] attr_type = 'player_sort' attribute_settings = {'window': 'ultimate_player_judging', 'file_name': team_list_name_tf.value, 'roster': roster, 'input_formation': input_formation, 'prev_window_value': win_previous} AddAttribute.open_attribute_window(win_ultimate_teams.x, win_ultimate_teams.y, db_dict, attr_dict, attr_list, attr_type, attribute_settings) win_ultimate_teams.hide() judging_edit_btn_width = 40 judging_players_edit_btn = Button("Edit", #x=teams_to_return_tf.right - judging_edit_btn_width, x=judging_players_attributes.right, y=judging_players_label.top, height=small_button_height-7, width=judging_edit_btn_width, font=small_button_font, action=judging_players_edit_btn_func, style = 'default', color=button_color, just='right') display_items.append(judging_players_edit_btn) # ========== New Player Budget ========== budget_tf = TextField(font=std_tf_font, width=tf_width, height=std_tf_height_plus) def budget_btn_func(): if not settings['budget'][0]: settings['budget'][0] = True budget_tf.value = str(settings['budget'][1]) budget_tf.enabled = 1 player_db_button.enabled = 1 else: # Get value from text field and assign to settings if str.isdigit(budget_tf.value): settings['budget'][1] = int(budget_tf.value) settings['budget'][0] = False budget_tf.value = disabled_msg budget_tf.enabled = 0 player_db_button.enabled = 0 win_ultimate_teams.become_target() budget_btn = Button(title="New Player Budget", font=std_tf_font_bold, width=std_tf_width, height=std_tf_height_plus, x=settings_indent - std_tf_width, y=judging_players_label.bottom + title_border*2, action=budget_btn_func, color=title_color, just='right') display_items.append(budget_btn) budget_tf.x = budget_btn.right + radio_btn_space budget_tf.y = budget_btn.top display_items.append(budget_tf) # Disable based on settings if not settings['budget'][0]: budget_tf.value = disabled_msg budget_tf.enabled = 0 player_db_button.enabled = 0 else: budget_tf.value = str(settings['budget'][1]) # ========== Limits Label ========== limits_label = Label(text="Limitations", font=title_font_3, width=std_tf_width, height=title_height-25, x=(win_ultimate_teams.width - std_tf_width)/2, y=budget_tf.bottom + title_border*2, color=title_color, just='center') display_items.append(limits_label) # ========== Players per Position Label ========== players_per_pos_tf = TextField(font=std_tf_font, width=tf_width, height=std_tf_height_plus) def players_per_pos_btn_func(): if not settings['players_per_position'][0]: settings['players_per_position'][0] = True players_per_pos_tf.value = str(settings['players_per_position'][1]) players_per_pos_tf.enabled = 1 else: # Get value from text field and assign to settings if str.isdigit(players_per_pos_tf.value): settings['players_per_position'][1] = int(players_per_pos_tf.value) settings['players_per_position'][0] = False players_per_pos_tf.value = disabled_msg players_per_pos_tf.enabled = 0 win_ultimate_teams.become_target() players_per_pos_btn = Button(title="Players per Position", font=std_tf_font_bold, width=std_tf_width, height=std_tf_height_plus, x=settings_indent - std_tf_width, y=limits_label.bottom + 5, action=players_per_pos_btn_func, color=title_color, just='right') display_items.append(players_per_pos_btn) players_per_pos_tf.x = players_per_pos_btn.right + radio_btn_space players_per_pos_tf.y = players_per_pos_btn.top display_items.append(players_per_pos_tf) # Disable based on settings if not settings['players_per_position'][0]: players_per_pos_tf.value = disabled_msg players_per_pos_tf.enabled = 0 else: players_per_pos_tf.value = str(settings['players_per_position'][1]) # ========== Max Teams per Formation Label ========== teams_per_formation_tf = TextField(font=std_tf_font, width=tf_width, height=std_tf_height_plus) def teams_per_formation_btn_func(): if not settings['teams_per_formation'][0]: settings['teams_per_formation'][0] = True teams_per_formation_tf.value = str(settings['teams_per_formation'][1]) teams_per_formation_tf.enabled = 1 else: # Get value from text field and assign to settings if str.isdigit(teams_per_formation_tf.value): settings['teams_per_formation'][1] = int(teams_per_formation_tf.value) settings['teams_per_formation'][0] = False teams_per_formation_tf.value = disabled_msg teams_per_formation_tf.enabled = 0 win_ultimate_teams.become_target() teams_per_formation_btn = Button(title="Max Teams per Formation", font=std_tf_font_bold, width=std_tf_width, height=std_tf_height_plus, x=settings_indent - std_tf_width, y=players_per_pos_btn.bottom + 5, action=teams_per_formation_btn_func, color=title_color, just='right') display_items.append(teams_per_formation_btn) teams_per_formation_tf.x = teams_per_formation_btn.right + radio_btn_space teams_per_formation_tf.y = teams_per_formation_btn.top display_items.append(teams_per_formation_tf) # Disable based on settings if not settings['teams_per_formation'][0]: teams_per_formation_tf.value = disabled_msg teams_per_formation_tf.enabled = 0 else: teams_per_formation_tf.value = str(settings['teams_per_formation'][1]) # ========== Max Teams to Return Label ========== teams_to_return_tf = TextField(font=std_tf_font, width=tf_width, height=std_tf_height_plus) def teams_to_return_btn_func(): if not settings['num_teams_returned'][0]: settings['num_teams_returned'][0] = True teams_to_return_tf.value = str(settings['num_teams_returned'][1]) teams_to_return_tf.enabled = 1 else: # Get value from text field and assign to settings if str.isdigit(teams_to_return_tf.value): settings['num_teams_returned'][1] = int(teams_to_return_tf.value) settings['num_teams_returned'][0] = False teams_to_return_tf.value = disabled_msg teams_to_return_tf.enabled = 0 win_ultimate_teams.become_target() teams_to_return_btn = Button(title="Max Teams to Return", font=std_tf_font_bold, width=std_tf_width, height=std_tf_height_plus, x=settings_indent - std_tf_width, y=teams_per_formation_btn.bottom + 5, action=teams_to_return_btn_func, color=title_color, just='right') display_items.append(teams_to_return_btn) teams_to_return_tf.x = teams_to_return_btn.right + radio_btn_space teams_to_return_tf.y = teams_to_return_btn.top display_items.append(teams_to_return_tf) # Disable based on settings if not settings['num_teams_returned'][0]: teams_to_return_tf.value = disabled_msg teams_to_return_tf.enabled = 0 else: teams_to_return_tf.value = str(settings['num_teams_returned'][1]) # ========== Time Limit Label ========== time_limit_tf = TextField(font=std_tf_font, width=tf_width, height=std_tf_height_plus) def time_limit_btn_func(): if not settings['time_limit'][0]: settings['time_limit'][0] = True time_limit_val = 0.0 if settings['time_limit'][2] == 'days': time_limit_val = settings['time_limit'][1] / 86400.0 elif settings['time_limit'][2] == 'hours': time_limit_val = settings['time_limit'][1] / 3600.0 if settings['time_limit'][2] == 'minutes': time_limit_val = settings['time_limit'][1] / 60.0 time_limit_tf.value = str(time_limit_val) time_limit_tf.enabled = 1 days_time_limit_radio_btn.enabled = 1 hours_time_limit_radio_btn.enabled = 1 minutes_time_limit_radio_btn.enabled = 1 time_limit_radio_group.enabled = 1 else: # Get value from text field, convert to seconds, and assign to settings try: if settings['time_limit'][2] == 'days': settings['time_limit'][1] = int(float(time_limit_tf.value) * 86400.0) elif settings['time_limit'][2] == 'hours': settings['time_limit'][1] = int(float(time_limit_tf.value) * 3600.0) elif settings['time_limit'][2] == 'minutes': settings['time_limit'][1] = int(float(time_limit_tf.value) * 60.0) except ValueError: print "Invalid time limit." settings['time_limit'][0] = False time_limit_tf.value = disabled_msg time_limit_tf.enabled = 0 days_time_limit_radio_btn.enabled = 0 hours_time_limit_radio_btn.enabled = 0 minutes_time_limit_radio_btn.enabled = 0 time_limit_radio_group.enabled = 0 win_ultimate_teams.become_target() time_limit_btn = Button(title="Time Limit", font=std_tf_font_bold, width=std_tf_width, height=std_tf_height_plus, x=settings_indent - std_tf_width, y=teams_to_return_btn.bottom + 5, action=time_limit_btn_func, color=title_color, just='right') display_items.append(time_limit_btn) def get_time_limit_rg(): # Get value from text field, convert to seconds, and assign to settings if time_limit_tf.value == '': time_limit_tf.value = '0' else: try: if settings['time_limit'][2] == 'days': settings['time_limit'][1] = int(float(time_limit_tf.value) * 86400.0) elif settings['time_limit'][2] == 'hours': settings['time_limit'][1] = int(float(time_limit_tf.value) * 3600.0) elif settings['time_limit'][2] == 'minutes': settings['time_limit'][1] = int(float(time_limit_tf.value) * 60.0) except ValueError: print "Invalid time limit." # Get new time limit units settings['time_limit'][2] = time_limit_radio_group.value time_limit_val = 0.0 if settings['time_limit'][2] == 'days': time_limit_val = settings['time_limit'][1] / 86400.0 elif settings['time_limit'][2] == 'hours': time_limit_val = settings['time_limit'][1] / 3600.0 elif settings['time_limit'][2] == 'minutes': time_limit_val = settings['time_limit'][1] / 60.0 time_limit_tf.value = str(time_limit_val) win_ultimate_teams.become_target() time_limit_radio_group = RadioGroup(action=get_time_limit_rg) # Time Limit Units Radio Buttons days_time_limit_radio_btn = RadioButton('Days', width=radio_btn_width, x=time_limit_btn.right + radio_btn_space, y=time_limit_btn.bottom + 5, group=time_limit_radio_group, value='days') display_items.append(days_time_limit_radio_btn) hours_time_limit_radio_btn = RadioButton('Hours', width=radio_btn_width, x=days_time_limit_radio_btn.right + radio_btn_space, y=days_time_limit_radio_btn.top, group=time_limit_radio_group, value='hours') display_items.append(hours_time_limit_radio_btn) minutes_time_limit_radio_btn = RadioButton('Minutes', width=radio_btn_width, x=hours_time_limit_radio_btn.right + radio_btn_space, y=days_time_limit_radio_btn.top, group=time_limit_radio_group, value='minutes') display_items.append(minutes_time_limit_radio_btn) time_limit_radio_group.value = settings['time_limit'][2] time_limit_tf.x = time_limit_btn.right + radio_btn_space time_limit_tf.y = time_limit_btn.top display_items.append(time_limit_tf) # Disable based on settings if not settings['time_limit'][0]: time_limit_tf.value = disabled_msg time_limit_tf.enabled = 0 days_time_limit_radio_btn.enabled = 0 hours_time_limit_radio_btn.enabled = 0 minutes_time_limit_radio_btn.enabled = 0 time_limit_radio_group.enabled = 0 else: time_limit_value = 0.0 if settings['time_limit'][2] == 'days': time_limit_value = settings['time_limit'][1] / 86400.0 elif settings['time_limit'][2] == 'hours': time_limit_value = settings['time_limit'][1] / 3600.0 elif settings['time_limit'][2] == 'minutes': time_limit_value = settings['time_limit'][1] / 60.0 time_limit_tf.value = str(time_limit_value) # ========== Button Declarations ========== start_btn = Button("Start") menu_btn = Button("Main Menu") back_btn = Button("Back") # ========== Button Functions ========== def save_settings(): """ Save the ultimate team creation configuration settings """ # Get the values from the text fields # New player budget if str.isdigit(budget_tf.value): settings['budget'][1] = int(budget_tf.value) # Players per position if str.isdigit(players_per_pos_tf.value): settings['players_per_position'][1] = int(players_per_pos_tf.value) # Teams per formation if str.isdigit(teams_per_formation_tf.value): settings['teams_per_formation'][1] = int(teams_per_formation_tf.value) # Number of teams returned if str.isdigit(teams_to_return_tf.value): settings['num_teams_returned'][1] = int(teams_to_return_tf.value) # Time limit if time_limit_tf.value != disabled_msg: try: if settings['time_limit'][2] == 'days': settings['time_limit'][1] = int(float(time_limit_tf.value) * 86400.0) elif settings['time_limit'][2] == 'hours': settings['time_limit'][1] = int(float(time_limit_tf.value) * 3600.0) elif settings['time_limit'][2] == 'minutes': settings['time_limit'][1] = int(float(time_limit_tf.value) * 60.0) except ValueError: print "Invalid time limit." # Load configurations from Window.AppConfig import config_filename with open(config_filename, 'r') as config_file: configurations = json.load(config_file) config_file.close() # Edit configurations configurations['ultimate_team_configs'] = settings # Save the settings with open(config_filename, 'w') as config_file: json.dump(configurations, config_file) config_file.close() def start_btn_func(): save_settings() # Assign formation(s) to use if input_formation is None or input_formation['name'] == "Generic": formations = db_dict['formation_list'][1] else: formations = FormationDB.FormationDB(input_formation) # If budget is not used, set player DB to an empty object. if budget_btn.enabled: player_db = db_dict['player_db'][1] else: player_db = PlayerDB.PlayerDB() # Open status page """StatusWindow.open_status_window(win_ultimate_teams.x, win_ultimate_teams.y, db_dict, file_name=team_list_name_tf.value, win_previous=win_ultimate_teams) win_ultimate_teams.hide()""" # Run team creation here team = Team.Team() teams = TeamDB.TeamDB(team.create_team_ultimate(db_dict['player_list'][1], player_db, formations)) if len(teams.db) > 0: teams.save(team_list_name_tf.value) else: print 'Not saved because no teams created.' # Erase file name team_list_name_tf.value = '' win_ultimate_teams.become_target() def menu_btn_func(): save_settings() StartMenu.open_start_menu(win_ultimate_teams.x, win_ultimate_teams.y, db_dict) win_ultimate_teams.hide() def back_btn_func(): save_settings() win_previous.show() win_ultimate_teams.hide() # Save the attribute lists if they were changed if player_judge_list is not None: save_settings() if team_judge_list is not None: save_settings() # ========== Buttons ========== start_btn.x = (win_width - 3*button_width - 2*button_spacing) / 2 start_btn.y = win_ultimate_teams.height - 100 start_btn.height = button_height start_btn.width = button_width start_btn.font = button_font start_btn.action = start_btn_func start_btn.style = 'default' start_btn.color = button_color start_btn.just = 'right' display_items.append(start_btn) menu_btn.x = start_btn.right + button_spacing menu_btn.y = start_btn.top menu_btn.height = button_height menu_btn.width = button_width menu_btn.font = button_font menu_btn.action = menu_btn_func menu_btn.style = 'default' menu_btn.color = button_color menu_btn.just = 'right' display_items.append(menu_btn) back_btn.x = menu_btn.right + button_spacing back_btn.y = start_btn.top back_btn.height = button_height back_btn.width = button_width back_btn.font = button_font back_btn.action = back_btn_func back_btn.style = 'default' back_btn.color = button_color back_btn.just = 'right' display_items.append(back_btn) # ========== Add components to view and add view to window ========== for item in display_items: view.add(item) win_ultimate_teams.add(view) view.become_target() win_ultimate_teams.show()
class Credentials_Dialog(ModalDialog): def __init__(self): """This method is the constructor for a new credentials dialog.""" ModalDialog.__init__(self) #default the credentials information self._user = None self._password = None label = Label("Please enter your credentials.") self._ok_button = Button("OK", action = "ok", style = "default") self._cancel_button = Button("Cancel", style = "cancel", action = "cancel") self._user_box = TextField(width = 150) self._password_box = TextField(width = 150, password = "******", select_action = "password_click") self.place(label, left = 20, top = 20) self.place(self._user_box, top = label + 10, right = label.right) self.place(self._password_box, top = self._user_box.bottom + 10, right = label.right) self.place(self._ok_button, top = self._password_box.bottom + 20, right = label.right) self.place(self._cancel_button, top = self._ok_button.top, right = self._ok_button.left - 20) self.shrink_wrap(padding = (20, 20)) self._message_label = None #the parent class will use this function to set the title self.set_title( "Google Credentials" ) self._password_box.width = 150 self._Set_Text() self._user_canceled = False #end __init__ def password_click(self): print "password click" #end password_click def ok(self): """This method will capture the event of the OK button being clicked.""" self._user = self._user_box.get_text() self._password = self._password_box.get_text() self.dismiss(True) self.exit_modal_event_loop() def cancel(self): """This method will capture the event of the Cancel button being clicked.""" self._user_canceled = True self.dismiss(True) def _Set_Text(self): """This method will set the default text in the text boxes.""" self._user_box.set_text("Username") self._password_box.set_text("Password") def Get_User( self ): """This method will retrieve the user name provided.""" return self._user #end Get_User def Get_Password( self ): """This method will retrieve the password provided.""" return self._password #end Get_Password def Get_User_Canceled( self ): """This method will retrieve if the user asked to cancel the operation.""" return self._user_canceled #end Get_User_Canceled def Set_Message( self, message ): """This method will set the message label to be shown to the user.""" self._message_label.set_text( message )
from GUI import Window, Frame from GUI import Button, Label, ListButton, Slider, TextField, CheckBox from GUI import application from GriddedWindow import GriddedWindow w = GriddedWindow(size=(401, 301), style='modal_dialog', title='DemoGui') theme_list_button = ListButton(width=150, titles=['Standard', 'Dark']) theme_list_button = ListButton(width=150, titles=['Standard', 'Dark']) text_label_slider = Slider(orient='h', width=150) volume_text_field = TextField(text='70', width=150) fps_list_button = ListButton(width=150, titles=['29.97', '60.0']) sound_checkbox = CheckBox(title='Sound') save_button = Button('Save', width=80) cancel_button = Button('Cancel', width=80) w.set_inner_sep(10) w.set_col_seps([80]) w.set_row_seps([10, 10, 10, 10, 30]) w.place_item(Label('Theme:'), 0, 0) w.place_item(Label('TextLabel'), 1, 0) w.place_item(Label('Volume:'), 2, 0) w.place_item(Label('FPS:'), 3, 0) w.place_item(theme_list_button, 0, 1) w.place_item(text_label_slider, 1, 1) w.place_item(volume_text_field, 2, 1) w.place_item(fps_list_button, 3, 1) w.place_item(sound_checkbox, 4, 1) w.place_item(save_button, 5, 0) w.place_item(cancel_button, 5, 1)
def open_attribute_window(window_x, window_y, db_dict, attr_dict, attr_list, attr_type, settings): # ========== Window ========== win_attribute = Window() win_attribute.title = attribute_win_title win_attribute.auto_position = False win_attribute.position = (window_x, window_y) win_attribute.size = (win_width, 500) win_attribute.resizable = 0 win_attribute.name = attribute_title + " Window" win_attribute.show() # ========== Window Image View ========== class StartWindowImageView(View): def draw(self, c, r): c.backcolor = view_backcolor c.erase_rect(r) view = StartWindowImageView(size=win_attribute.size) attribute_display_list = [] # ========== Title ========== title = Label(text=attribute_title) title.font = title_font title.width = title_width title.height = title_height title.x = (win_width - title_width) / 2 title.y = top_border title.color = title_color title.just = 'center' # ========== Button Declarations ========== enter_btn = Button("Enter") erase_btn = Button("Erase List") back_btn = Button("Back") # ========== Radio Button Action ========== def selection_made(): enter_btn.enabled = 1 win_attribute.become_target() def comp_selection_made(): win_attribute.become_target() # ========== Attribute Radio Buttons ========== radio_group = RadioGroup(action=selection_made) radio_button_list = [] with open(config_filename, 'r') as f: attributes_list = json.load(f)['player_attributes']['all'] f.close() for idx, attribute in enumerate(attributes_list): button = RadioButton(attribute) if idx < 10: button.width = 45 button.x = (idx / 10) * (button.width + 5) + 5 elif idx < 30: button.width = 100 button.x = (idx / 10) * (button.width + 5) - 50 elif idx < 40: button.width = 110 button.x = (idx / 10) * (button.width + 5) - 80 else: button.width = 100 button.x = (idx / 10) * (button.width + 5) - 40 button.y = (idx % 10) * 25 + title.bottom + 5 button.group = radio_group button.value = attribute button.title = format_attr_name(attribute) radio_button_list.append(button) # ========== Button Functions ========== def enter_btn_func(): valid = False return_value = None if attr_type == 'sort': # Check for doubles if attr_list.count(radio_group.value) == 0: attr_list.append(radio_group.value) show_attributes(attribute_display_list) erase_btn.enabled = 1 elif attr_type == 'search': # Value checks if radio_group.value in ["PAC", "SHO", "PAS", "DRI", "DEF", "PHY", "DIV", "HAN", "KIC", "REF", "SPD", "POS", "acceleration", "aggression", "agility", "balance", "ballcontrol", "crossing", "curve", "dribbling", "finishing", "freekickaccuracy", "gkdiving", "gkhandling", "gkkicking", "gkpositioning", "gkreflexes", "headingaccuracy", "interceptions", "jumping", "longpassing", "longshots", "marking", "penalties", "positioning", "potential", "rating", "reactions", "shortpassing", "shotpower", "skillMoves", "slidingtackle", "sprintspeed", "stamina", "standingtackle", "strength", "vision", "volleys", "weakFoot"]: # Value should be an integer between 0 and 100 if value_tf.value.isdigit(): return_value = int(value_tf.value) if 0 < return_value < 100: valid = True elif radio_group.value in ["age", "baseId", "clubId", "height", "id", "leagueId", "nationId", "weight"]: # Value should be an integer if value_tf.value.isdigit(): return_value = int(value_tf.value) valid = True elif radio_group.value in ["atkWorkRate", "birthdate", "club", "color", "commonName", "defWorkRate", "firstName", "foot", "itemType", "lastName", "league", "modelName", "name", "name_custom", "nation", "playStyle", "playerType", "position", "positionFull", "quality"]: # Value should be a string if type(value_tf.value) is str: return_value = value_tf.value valid = True elif radio_group.value in ["isGK", "isSpecialType"]: # Value should be a string if value_tf.value.upper() in ['T', 'F', 'TRUE', 'FALSE', 'Y', 'N', 'YES', 'NO']: if value_tf.value.upper()[0] in ['T', 'Y']: return_value = True else: return_value = False valid = True if valid: attr_dict[radio_group.value] = (return_value, compare_group.value) value_tf.value = '' show_attributes(attribute_display_list) erase_btn.enabled = 1 else: print "Invalid attribute value." else: print 'Invalid attr_type for AddAttribute.' def erase_btn_func(): if attr_type == 'sort': del attr_list[:] elif attr_type == 'search': attr_dict.clear() show_attributes(attribute_display_list) erase_btn.enabled = 0 def back_btn_func(): SearchMenu.open_search_menu(win_attribute.x, win_attribute.y, db_dict, attr_dict, attr_list, settings) win_attribute.hide() # ========== Buttons ========== erase_btn.x = (win_width - button_width) / 2 erase_btn.y = win_attribute.height - 70 erase_btn.height = button_height erase_btn.width = button_width erase_btn.font = button_font erase_btn.action = erase_btn_func erase_btn.style = 'default' erase_btn.color = button_color erase_btn.just = 'right' if (attr_type == 'sort' and len(attr_list) == 0) or \ (attr_type == 'search' and len(attr_dict) == 0): erase_btn.enabled = 0 enter_btn.x = erase_btn.left - button_spacing - button_width enter_btn.y = erase_btn.top enter_btn.height = button_height enter_btn.width = button_width enter_btn.font = button_font enter_btn.action = enter_btn_func enter_btn.style = 'default' enter_btn.color = button_color enter_btn.just = 'right' enter_btn.enabled = 0 back_btn.x = erase_btn.right + button_spacing back_btn.y = erase_btn.top back_btn.height = button_height back_btn.width = button_width back_btn.font = button_font back_btn.action = back_btn_func back_btn.style = 'default' back_btn.color = button_color back_btn.just = 'right' # ========== Value Textfield ========== value_tf = TextField() value_tf.width = 200 value_tf.x = (win_width - value_tf.width) / 2 value_tf.y = enter_btn.top - 35 value_tf.height = 25 value_tf.font = std_tf_font # ========== Compare Radio Buttons ========== compare_group = RadioGroup(action=comp_selection_made) comp_button_list = [] comp_button_width = 55 comp_button_x = (win_attribute.width - 4*comp_button_width)/2 for value in ['higher', 'exact', 'lower', 'not']: button = RadioButton(attribute) button.width = comp_button_width button.x = comp_button_x button.y = value_tf.top - value_tf.height - title_border button.group = compare_group button.value = value button.title = value.capitalize() comp_button_x += comp_button_width + 5 comp_button_list.append(button) compare_group.value = 'higher' def show_attributes(display_list): # Remove old attribute labels from screen for message in display_list: view.remove(message) del display_list[:] # Display new search attributes on screen message_x = 10 message_y = win_attribute.height - 150 if attr_type == 'search': display_list.append(Label(text=("Search Attributes:"), font=title_tf_font, width=std_tf_width, height=std_tf_height, x=message_x, y=message_y, color=title_color)) message_y += std_tf_height index = 0 for key, search_value in attr_dict.iteritems(): if index == 6: message_x = back_btn.right + 10 message_y = win_attribute.height - 150 msg_text = format_attr_name(key) + ": " if key in ['id', 'baseId', 'nationId', 'leagueId', 'clubId']: msg_text += str(search_value[0]) elif type(search_value[0]) is int: msg_text += search_value[1].capitalize() + ' ' + str(search_value[0]) elif search_value[1] == 'not': msg_text += search_value[1].capitalize() + ' "' + str(search_value[0]) + '"' else: msg_text += '"' + str(search_value[0]) + '"' attr_label = Label(text=msg_text, font=std_tf_font, width=std_tf_width, height=std_tf_height, x=message_x, y=message_y, color=title_color) message_y += std_tf_height display_list.append(attr_label) index += 1 # Display new sort attributes on screen elif attr_type == 'sort': display_list.append(Label(text=("Sort Attributes:"), font=title_tf_font, width=std_tf_width, height=std_tf_height, x=message_x, y=message_y, color=title_color)) message_y += std_tf_height for index, sort_value in enumerate(attr_list): if index == 6: message_x = back_btn.right + 10 message_y = win_attribute.height - 150 attr_label = Label(text=(format_attr_name(sort_value)), font=std_tf_font, width=std_tf_width, height=std_tf_height, x=message_x, y=message_y, color=title_color) message_y += std_tf_height display_list.append(attr_label) for attribute_label in display_list: view.add(attribute_label) show_attributes(attribute_display_list) # ========== Add buttons to window ========== view.add(title) view.add(enter_btn) view.add(erase_btn) view.add(back_btn) # Shows only for getting attribute for search, not sort if attr_type == 'search': view.add(value_tf) for button in comp_button_list: view.add(button) for button in radio_button_list: view.add(button) win_attribute.add(view) view.become_target() win_attribute.show()
def open_edit_menu(window_x, window_y, db_dict, attr_dict=None, attr_list=None, settings=None): list_players = PlayerDB.PlayerDB() list_formations = FormationDB.FormationDB() list_teams = TeamDB.TeamDB() if settings['edit_subject'] == 'players': list_players.load(settings['file_name'], 'list') elif settings['edit_subject'] == 'formations': list_formations.load(settings['file_name'], 'list') elif settings['edit_subject'] == 'teams': list_teams.load(settings['file_name']) if attr_dict is None: attr_dict = {} if attr_list is None: attr_list = [] if settings is None: settings = { 'window': 'edit', 'edit_type': 'add', 'edit_mode': 'simple', 'edit_subject': 'players', 'sort_order': True, 'messages': { 'search': [], 'sort': [], 'results': [] } } else: if 'window' not in settings: settings['window'] = 'edit' if 'edit_type' not in settings: settings['edit_type'] = 'add' if 'edit_mode' not in settings: settings['edit_mode'] = 'simple' if 'edit_subject' not in settings: settings['edit_subject'] = 'players' if 'sort_order' not in settings: settings['sort_order'] = True if 'messages' not in settings: settings['messages'] = {'search': [], 'sort': [], 'results': []} num_results = 20 general_display = [] simple_display = [] advanced_display = [] # ========== Window ========== win_edit = Window() win_edit.title = edit_win_title win_edit.auto_position = False win_edit.position = (window_x, window_y) win_edit.size = (win_width, win_height) win_edit.resizable = 0 win_edit.name = edit_title + " Window" # ========== Window Image View ========== class FormationsWindowImageView(View): def draw(self, c, r): c.backcolor = view_backcolor c.erase_rect(r) view = FormationsWindowImageView(size=win_edit.size) # ========== Title ========== title = Label(text=edit_title + ' File: ' + settings['file_name']) title.font = title_font title.width = title_width title.height = title_height title.x = (win_width - title_width) / 2 title.y = top_border title.color = title_color title.just = 'center' general_display.append(title) # ========== Action Button Declarations ========== start_btn = Button("Start") back_btn = Button("Back") # ========== Mode Button Declarations ========== simple_btn = Button("Simple") advanced_btn = Button("Advanced") # ========== Tool Button Declarations ========== attribute_btn = Button("Add Search Attribute") sort_btn = Button("Add Sort Attribute") reset_btn = Button("Reset Results") # ========== Simple Field Declarations ========== rating_label = Label("Rating: ") rating_tf = TextField() name_label = Label("Name: ") name_tf = TextField() # ========== Action Button Functions ========== def start_btn_func(): # Search for players based on attributes if settings['edit_subject'] == 'players': # Get the attributes to search with based on what mode is in use if simple_btn.enabled == 0: if len(name_tf.value) > 0: search_dict = {'name_custom': (name_tf.value, 'exact')} else: search_dict = {} if rating_tf.value.isdigit(): search_dict['rating'] = (int(rating_tf.value), 'exact') else: search_dict = attr_dict # Get players from database to add and search if settings['edit_type'] == 'add': db_players = db_dict['player_db'][1] if len(search_dict) == 0: search_results = db_players else: search_results = db_players.search(search_dict) search_results = PlayerDB.PlayerDB(search_results) # Get players from list to edit or delete and search else: if len(search_dict) == 0: search_results = list_players else: search_results = list_players.search(search_dict) search_results = PlayerDB.PlayerDB(search_results) # Sort players - if no attribute selected, use rating if len(attr_list) == 0: search_results.sort(['rating'], sort_order_radio_group.value) else: search_results.sort(attr_list, sort_order_radio_group.value) # Get attributes list and avoid duplicates attributes_list = [] for attr in attr_list: if attributes_list.count(attr) == 0: attributes_list.append(attr) for attr_key in attr_dict.iterkeys(): if attributes_list.count(attr_key) == 0: attributes_list.append(attr_key) display_players(search_results, attributes_list, (0, num_results)) # Start button corresponds to formations elif settings['edit_subject'] == 'formations': # Get the attributes to search with based on what mode is in use if simple_btn.enabled == 0: if len(name_tf.value) > 0: search_dict = {'name': (name_tf.value, 'exact')} else: search_dict = {} else: search_dict = attr_dict # Get formations from database to add and search if settings['edit_type'] == 'add': db_formations = db_dict['formation_db'][1] if len(search_dict) == 0: search_results = db_formations else: search_results = db_formations.search(search_dict) search_results = FormationDB.FormationDB(search_results) # Get formations from list to edit or delete and search else: if len(search_dict) == 0: search_results = list_formations else: search_results = list_formations.search(search_dict) search_results = FormationDB.FormationDB(search_results) # Sort formations - if no attribute selected, use name if len(attr_list) == 0: search_results.sort(['name'], sort_order_radio_group.value) else: search_results.sort(attr_list, sort_order_radio_group.value) # Get attributes list and avoid duplicates attributes_list = [] for attr in attr_list: if attributes_list.count(attr) == 0: attributes_list.append(attr) for attr_key in attr_dict.iterkeys(): if attributes_list.count(attr_key) == 0: attributes_list.append(attr_key) display_formations(search_results, attributes_list, (0, num_results)) # Start button corresponds to teams elif settings['edit_subject'] == 'teams': stuff = 0 win_edit.become_target() def back_btn_func(): # Clean up reset_btn_func() win_edit.hide() PickFile.open_pick_file_window(win_edit.x, win_edit.y, db_dict, settings) # ========== Search Type Button Functions ========== def simple_btn_func(): simple_btn.enabled = 0 advanced_btn.enabled = 1 settings['edit_mode'] = 'simple' for display_item in advanced_display: view.remove(display_item) clean_results() for display_item in simple_display: view.add(display_item) name_tf.become_target() def advanced_btn_func(): advanced_btn.enabled = 0 simple_btn.enabled = 1 settings['edit_mode'] = 'advanced' for display_item in simple_display: view.remove(display_item) clean_results() display_attributes() for display_item in advanced_display: view.add(display_item) win_edit.become_target() # ========== Tool Button Functions ========== def attribute_btn_func(): # Delete results del settings['messages']['results'][:] attr_type = '' if settings['edit_subject'] == 'players': attr_type = 'player_search' elif settings['edit_subject'] == 'formations': attr_type = 'formation_search' elif settings['team_subject'] == 'teams': attr_type = 'player_search' else: print "Invalid edit_subject settings." # Open new window and close current window win_edit.hide() AddAttribute.open_attribute_window(win_edit.x, win_edit.y, db_dict, attr_dict, attr_list, attr_type, settings) def sort_btn_func(): # Delete results del settings['messages']['results'][:] attr_type = '' if settings['edit_subject'] == 'players': attr_type = 'player_sort' elif settings['edit_subject'] == 'formations': attr_type = 'formation_sort' elif settings['team_subject'] == 'teams': attr_type = 'player_sort' else: print "Invalid edit_subject settings." # Open new window and close current window win_edit.hide() AddAttribute.open_attribute_window(win_edit.x, win_edit.y, db_dict, attr_dict, attr_list, attr_type, settings) def display_attributes(): for search_item in settings['messages']['search']: view.add(search_item) for sort_item in settings['messages']['sort']: view.add(sort_item) def clean_results(): # Remove messages off page for message in settings['messages']['search']: view.remove(message) for message in settings['messages']['sort']: view.remove(message) for message in settings['messages']['results']: view.remove(message) del settings['messages']['results'][:] win_edit.become_target() def reset_btn_func(): # Remove messages off page for message in settings['messages']['search']: view.remove(message) for message in settings['messages']['sort']: view.remove(message) for message in settings['messages']['results']: view.remove(message) # Delete the attribute parameters for search and sort attr_dict.clear() del attr_list[:] del settings['messages']['results'][:] win_edit.become_target() def player_bio_btn_func(player): win_edit.become_target() PlayerBio.open_player_bio_window(win_edit.x, win_edit.y, player, win_edit, file_name=settings['file_name'], current_list=list_players) win_edit.hide() def formation_bio_btn_func(formation): win_edit.become_target() FormationBio.open_formation_bio_window( win_edit.x, win_edit.y, formation, win_edit, settings['file_name'], list_formations) win_edit.hide() def add_btn_func(list_item, btn): if settings['edit_subject'] == 'players': # Check if player is already on selected players list # Remove player from list player_data = list_players.search({'id': (list_item['id'], 'exact')}) if len(player_data) > 0: # Remove list_players.db.remove(player_data[0]) # Save list_players.sort(['rating']) list_players.save(settings['file_name'], 'list', True) # Switch button title btn.title = "+" # Add player to the list else: # Add list_players.db.append(list_item) # Save list_players.sort(['rating']) list_players.save(settings['file_name'], 'list', True) # Switch button title btn.title = "-" elif settings['edit_subject'] == 'formations': # Check if formation is already on selected formations list # Remove formation from list if list_item in list_formations.db: # Remove list_formations.db.remove(list_item) # Save list_formations.sort(['name']) list_formations.save(settings['file_name'], 'list', True) # Switch button title btn.title = "+" # Add formation to the list else: # Add list_formations.db.append(list_item) # Save list_formations.sort(['name']) list_formations.save(settings['file_name'], 'list', True) # Switch button title btn.title = "-" win_edit.become_target() def pos_btn_func(player, btn): # Open window to get position win_edit.hide() PickPosition.open_pick_position_window(win_edit.x, win_edit.y, player, list_players, settings, btn, win_edit) win_edit.become_target() # ========== Action Buttons ========== start_btn.x = (win_width - 2*small_button_width - small_button_spacing) / 2 start_btn.y = title.bottom + small_button_top_spacing start_btn.height = small_button_height start_btn.width = small_button_width start_btn.font = small_button_font start_btn.action = start_btn_func start_btn.style = 'default' start_btn.color = small_button_color start_btn.just = 'right' general_display.append(start_btn) back_btn.x = start_btn.right + small_button_spacing back_btn.y = start_btn.top back_btn.height = small_button_height back_btn.width = small_button_width back_btn.font = small_button_font back_btn.action = back_btn_func back_btn.style = 'default' back_btn.color = small_button_color back_btn.just = 'right' general_display.append(back_btn) # ========== Edit Type Radio Buttons ========== def get_edit_type_rg(): settings['edit_type'] = edit_type_radio_group.value win_edit.become_target() edit_type_radio_group = RadioGroup(action=get_edit_type_rg) radio_btn_width = 125 radio_btn_space = 5 # Edit Type type_add_radio_btn = RadioButton() if settings['edit_subject'] == 'players': type_add_radio_btn.title = 'Add Players' elif settings['edit_subject'] == 'formations': type_add_radio_btn.title = 'Add Formations' elif settings['edit_subject'] == 'teams': type_add_radio_btn.title = 'Add Teams' type_add_radio_btn.width = radio_btn_width type_add_radio_btn.x = (win_edit.width - 2*radio_btn_width - radio_btn_space) / 2 type_add_radio_btn.y = start_btn.bottom + small_button_top_spacing type_add_radio_btn.group = edit_type_radio_group type_add_radio_btn.value = 'add' general_display.append(type_add_radio_btn) type_edit_radio_btn = RadioButton() if settings['edit_subject'] == 'players': type_edit_radio_btn.title = 'Edit/Delete Players' elif settings['edit_subject'] == 'formations': type_edit_radio_btn.title = 'Edit/Delete Forms' elif settings['edit_subject'] == 'teams': type_edit_radio_btn.title = 'Edit/Delete Teams' type_edit_radio_btn.width = radio_btn_width type_edit_radio_btn.x = type_add_radio_btn.right + radio_btn_space type_edit_radio_btn.y = type_add_radio_btn.top type_edit_radio_btn.group = edit_type_radio_group type_edit_radio_btn.value = 'edit' general_display.append(type_edit_radio_btn) edit_type_radio_group.value = settings['edit_type'] # ========== Mode Buttons ========== simple_btn.x = (win_width - 2*small_button_width - small_button_spacing) / 2 simple_btn.y = type_add_radio_btn.bottom + small_button_top_spacing simple_btn.height = small_button_height simple_btn.width = small_button_width simple_btn.font = small_button_font simple_btn.action = simple_btn_func simple_btn.style = 'default' simple_btn.color = small_button_color simple_btn.just = 'right' if settings['edit_mode'] == 'simple': simple_btn.enabled = 0 general_display.append(simple_btn) advanced_btn.x = simple_btn.right + small_button_spacing advanced_btn.y = simple_btn.top advanced_btn.height = small_button_height advanced_btn.width = small_button_width advanced_btn.font = small_button_font advanced_btn.action = advanced_btn_func advanced_btn.style = 'default' advanced_btn.color = small_button_color advanced_btn.just = 'right' if settings['edit_mode'] == 'advanced': advanced_btn.enabled = 0 general_display.append(advanced_btn) # ========== Sort Order Radio Buttons ========== def get_attribute_sort_order_rg(): settings['sort_order'] = sort_order_radio_group.value win_edit.become_target() sort_order_radio_group = RadioGroup(action=get_attribute_sort_order_rg) asc_desc_radio_btn_width = 75 asc_msg_width = 80 radio_btn_space = 5 asc_desc_rg_msg = Label(text="Sort Order:", font=std_tf_font, width=asc_msg_width, height=std_tf_height, color=title_color) asc_desc_rg_msg.x = (win_edit.width - 2*asc_desc_radio_btn_width - radio_btn_space - asc_msg_width) / 2 asc_desc_rg_msg.y = simple_btn.bottom + radio_btn_space general_display.append(asc_desc_rg_msg) descend_radio_btn = RadioButton("Descending") descend_radio_btn.width = asc_desc_radio_btn_width descend_radio_btn.x = asc_desc_rg_msg.right descend_radio_btn.y = asc_desc_rg_msg.top descend_radio_btn.group = sort_order_radio_group descend_radio_btn.value = True general_display.append(descend_radio_btn) ascend_radio_btn = RadioButton("Ascending") ascend_radio_btn.width = asc_desc_radio_btn_width ascend_radio_btn.x = descend_radio_btn.right + radio_btn_space ascend_radio_btn.y = descend_radio_btn.top ascend_radio_btn.group = sort_order_radio_group ascend_radio_btn.value = False general_display.append(ascend_radio_btn) sort_order_radio_group.value = settings['sort_order'] # ========== Tool Buttons ========== attribute_btn.x = (win_width - 3*small_button_width - 2*small_button_spacing) / 2 attribute_btn.y = asc_desc_rg_msg.bottom + 5 attribute_btn.height = small_button_height attribute_btn.width = small_button_width attribute_btn.font = small_button_font attribute_btn.action = attribute_btn_func attribute_btn.style = 'default' attribute_btn.color = small_button_color attribute_btn.just = 'right' advanced_display.append(attribute_btn) sort_btn.x = attribute_btn.right + small_button_spacing sort_btn.y = attribute_btn.top sort_btn.height = small_button_height sort_btn.width = small_button_width sort_btn.font = small_button_font sort_btn.action = sort_btn_func sort_btn.style = 'default' sort_btn.color = small_button_color sort_btn.just = 'right' advanced_display.append(sort_btn) reset_btn.x = sort_btn.right + small_button_spacing reset_btn.y = attribute_btn.top reset_btn.height = small_button_height reset_btn.width = small_button_width reset_btn.font = small_button_font reset_btn.action = reset_btn_func reset_btn.style = 'default' reset_btn.color = small_button_color reset_btn.just = 'right' advanced_display.append(reset_btn) # ========== Simple Fields ========== label_width = 50 rating_tf_width = 30 field_spacing = 20 rating_label.font = std_tf_font rating_label.width = label_width rating_label.height = std_tf_height rating_label.x = (win_edit.width - 2*label_width - std_tf_width - rating_tf_width - field_spacing) / 2 rating_label.y = asc_desc_rg_msg.bottom + 5 rating_label.color = title_color if settings['edit_subject'] != 'formations': simple_display.append(rating_label) rating_tf.font = std_tf_font rating_tf.width = rating_tf_width rating_tf.height = 25 rating_tf.x = rating_label.right rating_tf.y = rating_label.top if settings['edit_subject'] != 'formations': simple_display.append(rating_tf) name_label.font = std_tf_font name_label.width = label_width name_label.height = std_tf_height if settings['edit_subject'] != 'formations': name_label.x = rating_tf.right + field_spacing else: name_label.x = (win_edit.width - label_width - std_tf_width) / 2 name_label.y = rating_label.top name_label.color = title_color simple_display.append(name_label) name_tf.font = std_tf_font name_tf.width = std_tf_width name_tf.height = 25 name_tf.x = name_label.right name_tf.y = rating_label.top simple_display.append(name_tf) # ========== Messages ========== lowest_msg_l = start_btn.top lowest_msg_r = start_btn.top attr_msg_offset = 25 # Attribute Messages del settings['messages']['search'][:] del settings['messages']['sort'][:] if len(attr_dict) > 0: settings['messages']['search'].append(Label(text="Search Attributes:", font=title_tf_font, width=std_tf_width, height=std_tf_height, x=attr_msg_offset, y=lowest_msg_l, color=title_color)) lowest_msg_l += std_tf_height for key, value in attr_dict.iteritems(): msg_text = format_attr_name(key) + ": " if key in ['id', 'baseId', 'nationId', 'leagueId', 'clubId']: msg_text += str(value[0]) elif type(value[0]) is int: msg_text += value[1].capitalize() + ' ' + str(value[0]) elif value[1] == 'not': msg_text += value[1].capitalize() + ' "' + str(value[0]) + '"' else: msg_text += '"' + str(value[0]) + '"' attr_label = Label(text=msg_text, font=std_tf_font, width=std_tf_width, height=std_tf_height, x=attr_msg_offset, y=lowest_msg_l, color=title_color) lowest_msg_l += std_tf_height settings['messages']['search'].append(attr_label) if len(attr_list) > 0: settings['messages']['sort'].append(Label(text="Sort Attributes:", font=title_tf_font, width=std_tf_width, height=std_tf_height, x=advanced_btn.right + 3*attr_msg_offset, y=lowest_msg_r, color=title_color)) lowest_msg_r += std_tf_height for value in attr_list: attr_label = Label(text=(format_attr_name(value)), font=std_tf_font, width=std_tf_width, height=std_tf_height, x=advanced_btn.right + 3*attr_msg_offset, y=lowest_msg_r, color=title_color) lowest_msg_r += std_tf_height settings['messages']['sort'].append(attr_label) # ========== Previous, Add to List, Next Buttons ========== previous_btn = Button("<<< Previous %d" % num_results) add_to_list_btn = Button() next_btn = Button("Next %d >>>" % num_results) total_num_results_label = Label() pages_label = Label() def add_to_list_btn_func(input_list, func_type): item_list = copy.deepcopy(input_list) if settings['edit_subject'] == 'players': if func_type == 'add all': added_players = [] # Add current results to player list for player in item_list: if list_players.db.count(player) == 0: list_players.db.append(player) added_players.append(player) # Sort list_players.sort(['rating']) # Save list_players.save(settings['file_name'], 'list', True) # Change button title and action add_to_list_btn.title = "Remove Added Players" add_to_list_btn.action = (add_to_list_btn_func, item_list, 'remove select') # Keep track of just added players settings['messages']['players_changed'] = added_players elif func_type == 'remove all': removed_players = [] # Remove current results from player list for player in item_list: if list_players.db.count(player) > 0: list_players.db.remove(player) removed_players.append(player) # Sort list_players.sort(['rating']) # Save list_players.save(settings['file_name'], 'list', True) # Change button title and action add_to_list_btn.title = "Add Removed Players" add_to_list_btn.action = (add_to_list_btn_func, item_list, 'add select') # Keep track of just removed players settings['messages']['players_changed'] = removed_players elif func_type == 'add select': # Add select players back to player list for player in settings['messages']['players_changed']: if list_players.db.count(player) == 0: list_players.db.append(player) # Sort list_players.sort(['rating']) # Save list_players.save(settings['file_name'], 'list', True) # Change button title and action add_to_list_btn.title = "Remove Added Players" add_to_list_btn.action = (add_to_list_btn_func, item_list, 'remove select') elif func_type == 'remove select': # Remove select players from player list for player in settings['messages']['players_changed']: if list_players.db.count(player) > 0: list_players.db.remove(player) # Sort list_players.sort(['rating']) # Save list_players.save(settings['file_name'], 'list', True) # Change button title and action add_to_list_btn.title = "Add Removed Players" add_to_list_btn.action = (add_to_list_btn_func, item_list, 'add select') elif settings['edit_subject'] == 'formations': if func_type == 'add all': added_formations = [] # Add current results to formation list for formation in item_list: if list_formations.db.count(formation) == 0: list_formations.db.append(formation) added_formations.append(formation) # Sort list_formations.sort(['name']) # Save list_formations.save(settings['file_name'], 'list', True) # Change button title and action add_to_list_btn.title = "Remove Added Forms" add_to_list_btn.action = (add_to_list_btn_func, item_list, 'remove select') # Keep track of just added formations settings['messages']['formations_changed'] = added_formations elif func_type == 'remove all': removed_formations = [] # Remove current results from formation list for formation in item_list: if formation in list_formations.db: list_formations.db.remove(formation) removed_formations.append(formation) # Sort list_formations.sort(['name']) # Save list_formations.save(settings['file_name'], 'list', True) # Change button title and action add_to_list_btn.title = "Add Removed Forms" add_to_list_btn.action = (add_to_list_btn_func, item_list, 'add select') # Keep track of just removed formations settings['messages']['formations_changed'] = removed_formations elif func_type == 'add select': # Add select formations back to formation list for formation in settings['messages']['formations_changed']: if list_formations.db.count(formation) == 0: list_formations.db.append(formation) # Sort list_formations.sort(['name']) # Save list_formations.save(settings['file_name'], 'list', True) # Change button title and action add_to_list_btn.title = "Remove Added Forms" add_to_list_btn.action = (add_to_list_btn_func, item_list, 'remove select') elif func_type == 'remove select': # Remove select formations from formation list for formation in settings['messages']['formations_changed']: if list_formations.db.count(formation) > 0: list_formations.db.remove(formation) # Sort list_formations.sort(['name']) # Save list_formations.save(settings['file_name'], 'list', True) # Change button title and action add_to_list_btn.title = "Add Removed Forms" add_to_list_btn.action = (add_to_list_btn_func, item_list, 'add select') del item_list win_edit.become_target() def previous_btn_func(display_db=None, attributes=None, index_range=None): if display_db is not None: # display previous results if settings['edit_subject'] == 'players': display_players(display_db, attributes, index_range) elif settings['edit_subject'] == 'formations': display_formations(display_db, attributes, index_range) #elif settings['edit_subject'] == 'teams': #display_teams(display_db, attributes, index_range) win_edit.become_target() def next_btn_func(display_db=None, attributes=None, index_range=None): if display_db is not None: # display next results if settings['edit_subject'] == 'players': display_players(display_db, attributes, index_range) elif settings['edit_subject'] == 'formations': display_formations(display_db, attributes, index_range) # elif settings['edit_subject'] == 'teams': # display_teams(display_db, attributes, index_range) win_edit.become_target() add_to_list_btn.x = attribute_btn.right + small_button_spacing add_to_list_btn.y = attribute_btn.bottom + 5 add_to_list_btn.height = tiny_button_height add_to_list_btn.width = small_button_width add_to_list_btn.font = small_button_font add_to_list_btn.style = 'default' add_to_list_btn.color = small_button_color add_to_list_btn.just = 'right' previous_btn.height = tiny_button_height previous_btn.width = small_button_width previous_btn.x = add_to_list_btn.left - previous_btn.width - small_button_spacing previous_btn.y = add_to_list_btn.top previous_btn.font = small_button_font previous_btn.action = previous_btn_func previous_btn.style = 'default' previous_btn.color = small_button_color previous_btn.just = 'right' next_btn.height = tiny_button_height next_btn.width = small_button_width next_btn.x = add_to_list_btn.right + small_button_spacing next_btn.y = add_to_list_btn.top next_btn.font = small_button_font next_btn.action = next_btn_func next_btn.style = 'default' next_btn.color = small_button_color next_btn.just = 'right' total_num_results_label.font = std_tf_font total_num_results_label.width = 100 total_num_results_label.height = std_tf_height total_num_results_label.x = previous_btn.left + - 100 - 10 total_num_results_label.y = add_to_list_btn.top total_num_results_label.color = title_color total_num_results_label.just = 'right' pages_label.font = std_tf_font pages_label.width = 125 pages_label.height = std_tf_height pages_label.x = next_btn.right + 10 pages_label.y = add_to_list_btn.top pages_label.color = title_color pages_label.just = 'left' # ========== Display players from search ========== def display_players(display_db, attributes, index_range): # Remove old messages off page for message in settings['messages']['results']: view.remove(message) del settings['messages']['results'][:] # Add navigation buttons to page if settings['edit_type'] == 'add': add_to_list_btn.title = 'Add All Players' add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'add all') elif settings['edit_type'] == 'edit': add_to_list_btn.title = 'Remove All Players' add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'remove all') else: print "Invalid edit type." previous_range = (index_range[0]-num_results, index_range[0]) previous_btn.action = (previous_btn_func, display_db, attributes, previous_range) next_range = (index_range[1], index_range[1]+num_results) next_btn.action = (next_btn_func, display_db, attributes, next_range) total_num_results_label.text = str(len(display_db.db)) + " Players" pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results), math.ceil(len(display_db.db) / float(num_results))) if index_range[0] > 0: previous_btn.enabled = 1 else: previous_btn.enabled = 0 if index_range[1] <= len(display_db.db) - 1: next_btn.enabled = 1 else: next_btn.enabled = 0 settings['messages']['results'].append(add_to_list_btn) settings['messages']['results'].append(previous_btn) settings['messages']['results'].append(next_btn) settings['messages']['results'].append(total_num_results_label) settings['messages']['results'].append(pages_label) # Print out labels labels = player_info_labels(attributes) stat_index = 1 spacing_list = [25, 125, 40, 40, 65, 115, 115, 115, 40] left_border = (win_width - sum(spacing_list[:-1]) - (len(labels) - len(spacing_list) + 2) * spacing_list[-1])/2 msg_x = left_border + spacing_list[0] msg_y = add_to_list_btn.bottom + 5 for info_label in labels: player_label = Label(text=info_label, font=std_tf_font_bold, width=spacing_list[stat_index]-5, height=std_tf_height, x=msg_x, y=msg_y, color=title_color) settings['messages']['results'].append(player_label) msg_x += spacing_list[stat_index] if stat_index < len(spacing_list)-1: stat_index += 1 msg_y += std_tf_height + 5 # Print out players for idx, player in enumerate(display_db.db[index_range[0]:index_range[1]]): msg_x = left_border player_stats = player_info(player, attributes) stat_index = 0 player_data = list_players.search({'id': (player['id'], 'exact')}) if len(player_data) > 0: add_btn_text = '-' temp_player = player_data[0] else: add_btn_text = '+' temp_player = player add_btn = Button(title=add_btn_text, width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y) add_btn.action = (add_btn_func, temp_player, add_btn) settings['messages']['results'].append(add_btn) msg_x += spacing_list[stat_index] stat_index += 1 # Check for names that are too long name = player_stats[0] if len(name) > 20: name = player['lastName'] bio_btn = Button(title=name, width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y, action=(player_bio_btn_func, temp_player)) settings['messages']['results'].append(bio_btn) msg_x += spacing_list[stat_index] stat_index += 1 for player_stat in player_stats[1:]: player_label = Label(text=player_stat, font=small_button_font, width=spacing_list[stat_index]-5, height=std_tf_height, x=msg_x, y=msg_y, color=title_color) settings['messages']['results'].append(player_label) # Save values for position edit button if stat_index == 3: edit_x = msg_x edit_y = msg_y msg_x += spacing_list[stat_index] if stat_index < len(spacing_list) - 1: stat_index += 1 if settings['edit_type'] == 'edit': pos_btn = Button(title=player_stats[2], width=28, height=15, x=edit_x, y=edit_y) pos_btn.action = (pos_btn_func, player, pos_btn) settings['messages']['results'].append(pos_btn) msg_y += std_tf_height for results_msg in settings['messages']['results']: view.add(results_msg) # ========== Display formations from search ========== def display_formations(display_db, attributes, index_range): # Remove old messages off page for message in settings['messages']['results']: view.remove(message) del settings['messages']['results'][:] # Add navigation buttons to page if settings['edit_type'] == 'add': add_to_list_btn.title = 'Add All Formations' add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'add all') elif settings['edit_type'] == 'edit': add_to_list_btn.title = 'Remove All Formations' add_to_list_btn.action = (add_to_list_btn_func, display_db.db, 'remove all') else: print "Invalid edit type." previous_range = (index_range[0]-num_results, index_range[0]) previous_btn.action = (previous_btn_func, display_db, attributes, previous_range) next_range = (index_range[1], index_range[1]+num_results) next_btn.action = (next_btn_func, display_db, attributes, next_range) total_num_results_label.text = str(len(display_db.db)) + " Formations" pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results), math.ceil(len(display_db.db)/float(num_results))) if index_range[0] > 0: previous_btn.enabled = 1 else: previous_btn.enabled = 0 if index_range[1] <= len(display_db.db) - 1: next_btn.enabled = 1 else: next_btn.enabled = 0 settings['messages']['results'].append(add_to_list_btn) settings['messages']['results'].append(previous_btn) settings['messages']['results'].append(next_btn) settings['messages']['results'].append(total_num_results_label) settings['messages']['results'].append(pages_label) # Print out labels labels = formation_info_labels() stat_index = 1 spacing_list = [25, 100, 100, 55, 55, 55, 55, 140, 160] left_border = (win_edit.width - sum(spacing_list))/2 msg_x = left_border + spacing_list[0] msg_y = add_to_list_btn.bottom + 5 for info_label in labels: formation_label = Label(text=info_label, font=std_tf_font_bold, width=spacing_list[stat_index]-5, height=std_tf_height, x=msg_x, y=msg_y, color=title_color) settings['messages']['results'].append(formation_label) msg_x += spacing_list[stat_index] if stat_index < len(spacing_list)-1: stat_index += 1 msg_y += std_tf_height + 5 # Print out formations for idx, formation in enumerate(display_db.db[index_range[0]:index_range[1]]): msg_x = left_border formation_stats = formation_info(formation) stat_index = 0 if formation in list_formations.db: add_btn_text = '-' else: add_btn_text = '+' add_btn = Button(title=add_btn_text, width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y) add_btn.action = (add_btn_func, formation, add_btn) settings['messages']['results'].append(add_btn) msg_x += spacing_list[stat_index] stat_index += 1 bio_btn = Button(title=formation['name'], width=spacing_list[stat_index]-5, height=15, x=msg_x, y=msg_y, action=(formation_bio_btn_func, formation)) settings['messages']['results'].append(bio_btn) msg_x += spacing_list[stat_index] stat_index += 1 for formation_stat in formation_stats[1:]: formation_label = Label(text=formation_stat, font=small_button_font, width=spacing_list[stat_index]-5, height=std_tf_height, x=msg_x, y=msg_y, color=title_color) settings['messages']['results'].append(formation_label) msg_x += spacing_list[stat_index] if stat_index < len(spacing_list) - 1: stat_index += 1 msg_y += std_tf_height for results_msg in settings['messages']['results']: view.add(results_msg) # ========== Add components to view and add view to window ========== for item in general_display: view.add(item) if settings['edit_mode'] == 'simple': for item in simple_display: view.add(item) elif settings['edit_mode'] == 'advanced': for item in advanced_display: view.add(item) display_attributes() for msg in settings['messages']['results']: view.add(msg) win_edit.add(view) view.become_target() win_edit.show()
def open_create_list_window(window_x, window_y, db_dict, settings): message_text = 'Select list type.' create_list_settings = dict() create_list_settings['results'] = [] create_list_settings['process_step'] = 'list type' num_results = 5 # ========== Window ========== win_create_list = Window() win_create_list.title = create_list_win_title win_create_list.auto_position = False win_create_list.position = (window_x+100, window_y+100) win_create_list.size = (win_width-100, win_height-200) win_create_list.resizable = 0 win_create_list.name = create_list_title + " Window" win_create_list.show() # ========== Window Image View ========== class StartWindowImageView(View): def draw(self, c, r): c.backcolor = view_backcolor c.erase_rect(r) view = StartWindowImageView(size=win_create_list.size) # ========== Title ========== title = Label(text=create_list_title) title.font = title_font title.width = title_width title.height = title_height title.x = (win_create_list.width - title_width) / 2 title.y = top_border title.color = title_color title.just = 'center' # ========== Message Label ========== message = Label(font=title_font_3, width=win_create_list.width - 50, height=title_height, x=25, y=title.bottom + top_border, color=title_color, just='center') message.text = message_text # ========== Button Declarations ========== enter_btn = Button("Enter") undo_btn = Button("Undo Add") back_btn = Button("Back") player_list_btn = Button("Player") formation_list_btn = Button("Formation") team_list_btn = Button("Team") # ========== Results Navigation Item Declarations ========== previous_btn = Button("<<< Previous %d" % num_results) next_btn = Button("Next %d >>>" % num_results) total_num_results_label = Label() pages_label = Label() # ========== Button Functions ========== def enter_btn_func(): # Get file name and save if create_list_settings['process_step'] == 'file name': # Get file name and file prefix file_name = value_tf.value file_prefix = get_file_prefix('current_' + create_list_settings['list_type'] + '_list') if len(file_name) > 0: if not isfile('JSONs/' + file_prefix + file_name + '.json'): # Create list object, set message, and set process step if create_list_settings['list_type'] == 'player': new_list = PlayerDB() message.text = "Enter player rating/name or just name." create_list_settings['process_step'] = 'get player' elif create_list_settings['list_type'] == 'formation': new_list = FormationDB() message.text = "Enter part or full formation name, or nothing for full list." create_list_settings['process_step'] = 'get formation' elif create_list_settings['list_type'] == 'team': new_list = TeamDB() message.text = "Blank team list created. Add teams from Search menu." create_list_settings['process_step'] = 'get team' back_btn.title = "Done" enter_btn.enabled = 0 else: new_list = PlayerDB() print "Invalid list type." # Assign file name and file object create_list_settings['list'] = new_list create_list_settings['file_name'] = file_name # Clear box content value_tf.value = '' else: message.text = "A file with that name already exists." else: message.text = "File name must be at least 1 character." # Get player to add to list elif create_list_settings['process_step'] == 'get player': # Get input player_input = value_tf.value # Remove result messages off page for result_message in create_list_settings['results']: view.remove(result_message) if len(player_input) > 0: search_dict = {} # Check for rating if player_input.split(' ')[0].isdigit(): # Check if there is a name and rating if len(player_input.split(' ')) > 1: search_dict['rating'] = (int(player_input.split(' ')[0]), 'exact') # Get name search_dict['name_custom'] = (player_input.split(' ', 1)[1], 'exact') else: message.text = "Invalid. Ex: '99 Superman' or 'Superman'." # No rating, just name (or invalid) else: search_dict['name_custom'] = (player_input, 'exact') # Valid input if len(search_dict) > 0: # Search for players results = PlayerDB(db_dict['player_db'][1].search(search_dict)) results.sort(['rating']) # No matching players found if len(results.db) == 0: message.text = "Unable to find player. Try again." # If only one player in results, add player. elif len(results.db) == 1: add_player_btn_func(results.db[0]) else: message.text = "Multiple players found. Pick correct one." display_players(results, [], (0, num_results)) else: message.text = "Invalid. Ex: '99 Superman' or 'Superman'." # Get formation to add to list elif create_list_settings['process_step'] == 'get formation': # Get input formation_input = value_tf.value # Remove result messages off page for result_message in create_list_settings['results']: view.remove(result_message) search_dict = {'name': (formation_input, 'exact')} # Search for formations results = FormationDB(db_dict['formation_db'][1].search(search_dict)) # Remove formations already on list for formation in create_list_settings['list'].db: if formation in results.db: results.db.remove(formation) results.sort(['name']) # No matching formations found if len(results.db) == 0: message.text = "Unable to find formation. Try again." # If only one formation in results, add formation. elif len(results.db) == 1: add_formation_btn_func(results.db[0]) else: message.text = "Multiple formations found. Pick correct one." display_formations(results, [], (0, num_results)) # Get team to add to list elif create_list_settings['process_step'] == 'get team': stuff = 0 # Invalid process step else: print "Create file process step is invalid." value_tf.become_target() def undo_btn_func(): # Remove last player added and save if create_list_settings['process_step'] == 'get player': if len(create_list_settings['list'].db) > 0: player = create_list_settings['list'].db.pop(-1) create_list_settings['list'].save(create_list_settings['file_name'], 'list', True) common_name = ascii_text(player['commonName']) player_name = ascii_text(player['firstName']) + ' ' + ascii_text(player['lastName']) if len(common_name) > 0: player_name = common_name + " (" + player_name + ")" message.text = "Removed %s!" % player_name # Remove last formation added and save elif create_list_settings['process_step'] == 'get formation': if len(create_list_settings['list'].db) > 0: formation = create_list_settings['list'].db.pop(-1) create_list_settings['list'].save(create_list_settings['file_name'], 'list', True) message.text = "Removed %s!" % formation['name'] # Disable undo if no items left if len(create_list_settings['list'].db) == 0: undo_btn.enabled = 0 def back_btn_func(): # Sort and save player list before exiting if create_list_settings['process_step'] == 'get player': create_list_settings['list'].sort(['rating']) create_list_settings['list'].save(create_list_settings['file_name'], 'list', True) # Sort and save formation list before exiting elif create_list_settings['process_step'] == 'get formation': create_list_settings['list'].sort(['name']) create_list_settings['list'].save(create_list_settings['file_name'], 'list', True) elif create_list_settings['process_step'] == 'get team': create_list_settings['list'].sort(['rating']) create_list_settings['list'].save(create_list_settings['file_name'], True) FilesMenu.open_files_menu(window_x, window_y, db_dict, settings) win_create_list.hide() def list_type_func(list_type): # Remove list type buttons view.remove(player_list_btn) view.remove(formation_list_btn) view.remove(team_list_btn) # Add textfield, enabled enter button, and change message view.add(value_tf) enter_btn.enabled = 1 message.text = "Enter file name." create_list_settings['list_type'] = list_type # Set list type create_list_settings['process_step'] = 'file name' value_tf.become_target() # ========== Action Buttons ========== enter_btn.x = (win_create_list.width - 3*button_width - 2*button_spacing) / 2 enter_btn.y = win_create_list.height - button_height - 40 enter_btn.height = button_height enter_btn.width = button_width enter_btn.font = button_font enter_btn.action = enter_btn_func enter_btn.style = 'default' enter_btn.color = button_color enter_btn.just = 'right' enter_btn.enabled = 0 undo_btn.x = enter_btn.right + button_spacing undo_btn.y = enter_btn.top undo_btn.height = button_height undo_btn.width = button_width undo_btn.font = button_font undo_btn.action = undo_btn_func undo_btn.style = 'default' undo_btn.color = button_color undo_btn.just = 'right' undo_btn.enabled = 0 back_btn.x = undo_btn.right + button_spacing back_btn.y = enter_btn.top back_btn.height = button_height back_btn.width = button_width back_btn.font = button_font back_btn.action = back_btn_func back_btn.style = 'default' back_btn.color = button_color back_btn.just = 'right' # ========== List Type Buttons ========== player_list_btn.x = (win_create_list.width - 3*button_width - 2*button_spacing) / 2 player_list_btn.y = message.bottom + top_border player_list_btn.height = button_height player_list_btn.width = button_width player_list_btn.font = button_font player_list_btn.action = (list_type_func, 'player') player_list_btn.style = 'default' player_list_btn.color = button_color player_list_btn.just = 'right' formation_list_btn.x = player_list_btn.right + button_spacing formation_list_btn.y = player_list_btn.top formation_list_btn.height = button_height formation_list_btn.width = button_width formation_list_btn.font = button_font formation_list_btn.action = (list_type_func, 'formation') formation_list_btn.style = 'default' formation_list_btn.color = button_color formation_list_btn.just = 'right' team_list_btn.x = formation_list_btn.right + button_spacing team_list_btn.y = player_list_btn.top team_list_btn.height = button_height team_list_btn.width = button_width team_list_btn.font = button_font team_list_btn.action = (list_type_func, 'team') team_list_btn.style = 'default' team_list_btn.color = button_color team_list_btn.just = 'right' # ========== Value Textfield ========== value_tf = TextField() value_tf.width = 200 value_tf.x = (win_create_list.width - value_tf.width) / 2 value_tf.y = message.bottom + top_border value_tf.height = 25 value_tf.font = std_tf_font # ========== Players navigation functions ========== def previous_btn_func(display_db=None, attributes=None, index_range=None): if display_db is not None: # display previous results if create_list_settings['process_step'] == 'get player': display_players(display_db, attributes, index_range) elif create_list_settings['process_step'] == 'get formation': display_formations(display_db, attributes, index_range) win_create_list.become_target() def next_btn_func(display_db=None, attributes=None, index_range=None): if display_db is not None: # display next results if create_list_settings['process_step'] == 'get player': display_players(display_db, attributes, index_range) elif create_list_settings['process_step'] == 'get formation': display_formations(display_db, attributes, index_range) win_create_list.become_target() def add_player_btn_func(player): # Check for duplicates if create_list_settings['list'].db.count(player) == 0: # Add player and save create_list_settings['list'].db.append(player) create_list_settings['list'].save(create_list_settings['file_name'], 'list', True) # Remove result messages off page for result_message in create_list_settings['results']: view.remove(result_message) common_name = ascii_text(player['commonName']) player_name = ascii_text(player['firstName']) + ' ' + ascii_text(player['lastName']) if len(common_name) > 0: player_name = common_name + " (" + player_name + ")" # Reset page value_tf.value = '' message.text = "Added %s!" % player_name back_btn.title = "Done" undo_btn.enabled = 1 value_tf.become_target() # Duplicate player, don't add else: message.text = "Player already on list." win_create_list.become_target() def add_formation_btn_func(formation): # Check for duplicates if create_list_settings['list'].db.count(formation) == 0: # Add formation and save create_list_settings['list'].db.append(formation) create_list_settings['list'].save(create_list_settings['file_name'], 'list', True) # Remove result messages off page for result_message in create_list_settings['results']: view.remove(result_message) # Reset page value_tf.value = '' message.text = "Added %s!" % formation['name'] back_btn.title = "Done" undo_btn.enabled = 1 value_tf.become_target() # Duplicate formation, don't add else: message.text = "Formation already on list." win_create_list.become_target() # ========== Display Players Buttons ========== previous_btn.height = tiny_button_height previous_btn.width = small_button_width previous_btn.x = (win_create_list.width - 2*small_button_width - small_button_spacing) / 2 previous_btn.y = value_tf.bottom + top_border previous_btn.font = small_button_font previous_btn.action = previous_btn_func previous_btn.style = 'default' previous_btn.color = small_button_color previous_btn.just = 'right' next_btn.height = tiny_button_height next_btn.width = small_button_width next_btn.x = previous_btn.right + small_button_spacing next_btn.y = previous_btn.top next_btn.font = small_button_font next_btn.action = next_btn_func next_btn.style = 'default' next_btn.color = small_button_color next_btn.just = 'right' total_num_results_label.font = std_tf_font total_num_results_label.width = 100 total_num_results_label.height = std_tf_height total_num_results_label.x = previous_btn.left + - 100 - 10 total_num_results_label.y = previous_btn.top total_num_results_label.color = title_color total_num_results_label.just = 'right' pages_label.font = std_tf_font pages_label.width = 125 pages_label.height = std_tf_height pages_label.x = next_btn.right + 10 pages_label.y = previous_btn.top pages_label.color = title_color pages_label.just = 'left' # ========== Display info from search ========== def display_players(results_list, attributes, index_range): # Remove old messages off page for result_message in create_list_settings['results']: view.remove(result_message) del create_list_settings['results'][:] # Add navigation buttons to page previous_range = (index_range[0]-num_results, index_range[0]) previous_btn.action = (previous_btn_func, results_list, attributes, previous_range) next_range = (index_range[1], index_range[1]+num_results) next_btn.action = (next_btn_func, results_list, attributes, next_range) total_num_results_label.text = str(len(results_list.db)) + " Players" pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results), math.ceil(len(results_list.db)/float(num_results))) if index_range[0] > 0: previous_btn.enabled = 1 else: previous_btn.enabled = 0 if index_range[1] <= len(results_list.db) - 1: next_btn.enabled = 1 else: next_btn.enabled = 0 create_list_settings['results'].append(previous_btn) create_list_settings['results'].append(next_btn) create_list_settings['results'].append(total_num_results_label) create_list_settings['results'].append(pages_label) # Print out labels labels = [''] + player_info_labels(attributes) stat_index = 0 add_btn_width = 30 add_btn_space = add_btn_width + 10 spacing_list = [add_btn_space, 125, 40, 40, 65, 115, 115, 115] left_border = (win_create_list.width - sum(spacing_list)) / 2 msg_x = left_border msg_y = previous_btn.bottom + 5 for info_label in labels: player_label = Label(text=info_label, font=std_tf_font_bold, width=spacing_list[stat_index]-5, height=std_tf_height, x=msg_x, y=msg_y, color=title_color) create_list_settings['results'].append(player_label) msg_x += spacing_list[stat_index] stat_index += 1 msg_y += std_tf_height + 5 # Print out players for idx, player in enumerate(results_list.db[index_range[0]:index_range[1]]): msg_x = left_border player_stats = player_info(player, attributes) stat_index = 0 add_btn = Button("Add", width=add_btn_width, height=15, x=msg_x, y=msg_y, action=(add_player_btn_func, player)) create_list_settings['results'].append(add_btn) msg_x += spacing_list[stat_index] stat_index += 1 for player_stat in player_stats: player_label = Label(text=player_stat, font=small_button_font, width=win_width-(2*left_border), height=std_tf_height, x=msg_x, y=msg_y, color=title_color) create_list_settings['results'].append(player_label) msg_x += spacing_list[stat_index] stat_index += 1 msg_y += std_tf_height for results_msg in create_list_settings['results']: view.add(results_msg) def display_formations(results_list, attributes, index_range): # Remove old messages off page for result_message in create_list_settings['results']: view.remove(result_message) del create_list_settings['results'][:] # Add navigation buttons to page previous_range = (index_range[0]-num_results, index_range[0]) previous_btn.action = (previous_btn_func, results_list, attributes, previous_range) next_range = (index_range[1], index_range[1]+num_results) next_btn.action = (next_btn_func, results_list, attributes, next_range) total_num_results_label.text = str(len(results_list.db)) + " Formations" pages_label.text = "Page %d of %d" % (int(index_range[1]/num_results), math.ceil(len(results_list.db)/float(num_results))) if index_range[0] > 0: previous_btn.enabled = 1 else: previous_btn.enabled = 0 if index_range[1] <= len(results_list.db) - 1: next_btn.enabled = 1 else: next_btn.enabled = 0 create_list_settings['results'].append(previous_btn) create_list_settings['results'].append(next_btn) create_list_settings['results'].append(total_num_results_label) create_list_settings['results'].append(pages_label) # Print out labels labels = [''] + formation_info_labels()[:-2] stat_index = 0 add_btn_width = 30 add_btn_space = add_btn_width + 10 spacing_list = [add_btn_space, 100, 100, 55, 55, 55, 55] left_border = (win_create_list.width - sum(spacing_list)) / 2 msg_x = left_border msg_y = previous_btn.bottom + 5 for info_label in labels: player_label = Label(text=info_label, font=std_tf_font_bold, width=win_width-(2*left_border), height=std_tf_height, x=msg_x, y=msg_y, color=title_color) create_list_settings['results'].append(player_label) msg_x += spacing_list[stat_index] stat_index += 1 msg_y += std_tf_height + 5 # Print out formations for idx, formation in enumerate(results_list.db[index_range[0]:index_range[1]]): msg_x = left_border formation_stats = formation_info(formation)[:-2] stat_index = 0 add_btn = Button("Add", width=add_btn_width, height=15, x=msg_x, y=msg_y, action=(add_formation_btn_func, formation)) create_list_settings['results'].append(add_btn) msg_x += spacing_list[stat_index] stat_index += 1 for formation_stat in formation_stats: formation_label = Label(text=formation_stat, font=small_button_font, width=win_width-(2*left_border), height=std_tf_height, x=msg_x, y=msg_y, color=title_color) create_list_settings['results'].append(formation_label) msg_x += spacing_list[stat_index] stat_index += 1 msg_y += std_tf_height for results_msg in create_list_settings['results']: view.add(results_msg) # ========== Add items to window ========== view.add(title) view.add(message) view.add(enter_btn) view.add(undo_btn) view.add(back_btn) view.add(player_list_btn) view.add(formation_list_btn) view.add(team_list_btn) win_create_list.add(view) view.become_target() win_create_list.show()
def _get_default_editor(self): editor = self._default_editor if not editor: editor = TextField() self._default_editor = editor return editor
def __init__(self, number, *args, **kwds): TextField.__init__(self, *args, **kwds) self.number = number
class Obscure_Reference_Main( main_application.Main_Application ): def __init__( self ): #call the parent constructor main_application.Main_Application.__init__( self ) self._close = False #default our database parser self._parser = None #default the list of players self._player_list = {} #default the manager self._current_manager = None self._manager_list = {} self._overall_team_frame = None self._dropdown_string_table = [] #end __init__ def _Determine_Team_Information( self ): """This method will retrieve the information from the database that's pertinent to the individual team that's running.""" #retrieve the manager table self._manager_table = \ self._parser.Get_Table(string_definitions.managers_table_name) #retrieve the teams feed self._manager_feed = \ self._parser.Get_Feed(self._manager_table) #because we could log in with any variation of periods in the #username field, we need to strip them out to make sure we get a #good comparison filtered_user_name = self._username.replace( ".", "" ) #create manager objects based on the information in the table for raw_manager in self._manager_feed.entry: #create the object current_manager = manager.Manager( raw_manager ) #save the manager in the manager list based on the username self._manager_list[current_manager.Get_Username( )] = current_manager current_manager_name = \ current_manager.Get_Username( ).replace( ".", "" ) #check for a match with the provided username if filtered_user_name == current_manager_name: self._current_manager = current_manager #end if we have a match with the login username #end loop through manager #end _Determine_Team_Information def _Determine_Session_Information( self ): """This method will retrieve the information from the database that's pertinent to the session that is currently running.""" #Get the table the contains the information self._session_table = \ self._parser.Get_Table( string_definitions.session_table_name ) #pull out the year field self._current_year = \ self._parser.Get_Current_Year( self._session_table ) #end _Determine_Session_Information def Get_Current_Year( self ): """This method will return the current season year.""" return self._current_year #end Get_Current_Year def Get_Current_Team( self ): """This method will retrieve the team associated with the currently- logged in manager.""" return self._current_team #end Get_Current_Team def Get_Current_Manager( self ): """This method will retrieve the manager associated with the currently- logged-in user.""" return self._current_manager #end Get_Current_Manager def _Perform_Login( self ): """This method will attempt to log in to Google database.""" _credentials = credentials_dialog.Credentials_Dialog( ) #show the dialog _credentials.present( ) #loop until we get a successful login or the user has canceled while self._parser is None and not _credentials.Get_User_Canceled(): try: #try to log in to the parser using the received credentials self._parser = database_parser.Database_Parser( \ _credentials.Get_User( ), _credentials.Get_Password( ), string_definitions.default_database_name ) #end try to log in except (gdata.service.BadAuthentication, gdata.service.CaptchaRequired): #let the user know that there was a problem _credentials.Set_Message( "Login failed. Try again" ) #end BadAuthentication #end loop until successful login/user canceled if self._parser <> None: #save the username self._username = _credentials.Get_User( ) if self._username.count("@") > 0: char_index = self._username.index( "@" ) #the user name needs to be everything before the at self._username = self._username[0:char_index] #end if we have the at symbol #end if valid login #end _Perform_Login def Load_Player_Data( self ): """This method will load the latest player data to be used.""" #check to make sure that we have a valid parser if self._parser <> None: #call in to the database to reload the players self._parser.Reload_Players( ) #retrieve the list of players raw_player_list = self._parser.Get_Player_List( ) #if we had a previous list if 0 <> len( self._player_list ): #delete the previous list del( self._player_list ) #end if we have a previous player list self._player_list = {} #get the list of keys available for the player table self._player_keys = raw_player_list[0].custom.keys() #the statically-defined self._player_header_keys = ["Action", "Name", "Manager", "Cap Hit" ] year_list = [] #loop through the keys looking for salary information for key in self._player_keys: #if we've found a salary if key.count( string_definitions.salary_field_prefix ): #add this year to the year list year_list.append( \ key.replace( string_definitions.salary_field_prefix, "" ) ) #end if we've found a salary #end loop through keys #put the year list in inverse order year_list.sort( reverse=True ) #add the year list to the header keys self._player_header_keys += year_list #loop through the player list creating the objects for current_player in raw_player_list: #pull out the player name to make this code not quite as ugly player_name = \ current_player.custom[string_definitions.player_name_field].text this_player = \ player.Player( raw_data = current_player, receiver = self, add_player_function = "Add_Player", drop_player_function = "Drop_Player", trade_player_function = "Trade_Player" ) #add the new player to our list self._player_list[player_name] = this_player #retrieve the manager name manager_name = this_player.Get_Manager_Name() #determine if this player is on a team if manager_name <> None and manager_name <> "": #get the manager current_manager = self._manager_list[manager_name] #add this player to the manager's team current_manager.Add_Player( this_player ) #end if player is on a team #end loop through players #end if valid parser #end Load_Player_Data #this method doesn't conform to naming standard because it is #automatically called by the GUI framework def open_app(self): #perform the login self._Perform_Login( ) #if we have a successful login, create the main GUI if self._parser <> None: #determine the team information self._Determine_Team_Information( ) #figure out the important bits about our current session self._Determine_Session_Information( ) #end if valid parser else: #note to self: we're closing self._close = True #exit out of the application self.Exit( ) #couldn't log in #make sure that we didn't cancel out if self._close <> True: #create the main GUI self._main_gui = \ obscure_main_gui.Obscure_Main_Gui( controller = self, logo_file = _logo_file ) #display the main GUI self._main_gui.show( ) #while we're here, let's grab the player data self.Load_Player_Data( ) #end if user didn't cancel out #end open_app def _Create_Overall_Player_Frame( self ): """This method is used to create the overall player frame used when displaying the players.""" #retrieve the main frame from the GUI main_frame = self._main_gui.Get_Main_Frame() #create the overall player frame self._overall_player_frame = \ Frame( container = main_frame, anchor = "ltrb", size = ( main_frame.width, main_frame.height ) ) #create the search button self._player_search_button = Button( "Player Search", action = "Player_Search", style = "default" ) #put the button in the frame self._overall_player_frame.place( self._player_search_button, left = 0, top = 0 ) #create the text box self._player_search_field = \ TextField( width = number_constants.text_box_width ) #put the field on the frame self._overall_player_frame.place( \ self._player_search_field, left = self._player_search_button.right ) #end _Create_Overall_Player_Frame def Players_Matching_String( self, search_string ): """This method will look through the player list for any matching the provided search string.""" #shift the search string to lower case search_string = search_string.lower() player_list = {} #loop through the player list for current_player in self._player_list: #shift the player name to lower case lower_current_player = current_player.lower( ) #if we have a match with the player if 0 < lower_current_player.count( search_string ): #add this player to the list player_list[current_player] = self._player_list[current_player] #end if we have a match #end loop through player list return player_list #end Players_Matching_String def Player_Search( self ): """This method will be invoked when the user clicks the player search button.""" #retrieve the search string search_string = self._player_search_field.get_text( ) #get the players matching the search string player_list = self.Players_Matching_String( search_string ) #clear the existing player frame self._overall_player_frame.remove( self._player_frame ) main_frame = self._main_gui.Get_Main_Frame( ) #create a new player frame with the new list self._player_frame = \ player_frame.Player_Frame( player_list = player_list, player_keys = self._player_header_keys, container = self._overall_player_frame, anchor = "ltrb", scrolling = "", size = (main_frame.width - 40, #TODO: Magic numbers need tweaked and defined (self._overall_player_frame.height - self._player_search_button.height - number_constants.basic_pad - number_constants.half_pad))) #put the overall player frame on the GUI self._overall_player_frame.place( \ self._player_frame, sticky = "nsew", top = (self._player_search_button.bottom + \ number_constants.half_pad)) self._main_gui.Receive_New_Frame(self._overall_player_frame) #end Player_Search def Show_Players( self ): """This method will cause the list of players to be displayed.""" self._Create_Overall_Player_Frame( ) #retrieve the main frame from the GUI main_frame = self._main_gui.Get_Main_Frame() #create the player frame self._player_frame = \ player_frame.Player_Frame( player_list = self._player_list, player_keys = self._player_header_keys, container = self._overall_player_frame, anchor = "ltrb", scrolling = "", size = (main_frame.width - 40, #TODO: Magic numbers need tweaked and defined (self._overall_player_frame.height - self._player_search_button.height - number_constants.basic_pad - number_constants.half_pad))) #put the overall player frame on the GUI self._overall_player_frame.place( \ self._player_frame, sticky = "nsew", top = (self._player_search_button.bottom + \ number_constants.half_pad)) #give the new frame to the main GUI self._main_gui.Receive_New_Frame( self._overall_player_frame ) #end Show_Players def Show_Transactions( self ): """This method will cause the list of pending transactions to be displayed.""" None #end Show_Transactions def _Ask_User( self, question ): """This method will ask the user if they're sure that they want to do what they've said they do. Basically, we're protecting them from themselves.""" #create the confirm dialog confirm_dialog = ModalDialog( title = "Please Confirm" ) confirm_dialog.place( Label(text = question ), left = 20, top = 20 ) #create the buttons for OK/Cancel confirm_dialog.default_button = DefaultButton() confirm_dialog.cancel_button = CancelButton() #put the buttons on the GUI confirm_dialog.place( confirm_dialog.default_button, right = -20, bottom = -20 ) confirm_dialog.place( confirm_dialog.cancel_button, left = 20, bottom = -20 ) #center the dialog confirm_dialog.center( ) #ask for confirmation to make sure that the user really wants to do #this confirm = confirm_dialog.present( ) return confirm #end _Ask_User def Add_Player( self, player_to_add ): """This function will add the player to the current team.""" if self._current_manager <> None: if self._Ask_User( "Are you sure that you want to\n add " + \ player_to_add.Get_Name( ) + \ "?" ): # Change the local data self._current_manager.Add_Player( player_to_add ) #tell the player their new manager player_to_add.Set_Manager_Name( \ self._current_manager.Get_Email( ) ) try: #update the database self._parser.Set_Player_Line(player_to_add.Get_Raw_Data()) #change the player information with the username #string instead of the whole email address player_to_add.Set_Manager_Name( \ string_definitions.Extract_Username( \ self._current_manager.Get_Email( ) ) ) #update the GUI self.Show_Team( self._current_manager.Get_Username( ) ) #end try except gdata.service.RequestError: #create a modal dialog to show error_dialog = ModalDialog(title = "Couldn't Add Player", size = (400, 70)) #create an information label error_dialog.place(Label(text = "Player has already " + \ "been added by someone else"), left = 20, top = 20) #create the button error_dialog.default_button = DefaultButton() error_dialog.place(error_dialog.default_button, right = -20, bottom = -20) #start the reload of the players self.Load_Player_Data( ) #show the dialog error_dialog.present() #re-show the player data self.Show_Players() #end except #end if user confirmed #end if #end Add_Player def Drop_Player( self, player ): """This function will add the player to the current team.""" confirm = self._Ask_User( "Are you sure that you want to \ndrop " + \ player.Get_Name( ) + \ "?" ) #if the user was sure if confirm: # Change the local data self._current_manager.Drop_Player( player ) #tell the player they no longer have a mananger player.Set_Manager_Name( "" ) try: #update the database self._parser.Set_Player_Line(player.Get_Raw_Data()) #update the GUI self.Show_Team( self._current_manager.Get_Username( ) ) #end try except gdata.service.RequestError: #create a modal dialog to show error_dialog = ModalDialog(title = "Couldn't Drop Player", size = (400, 70)) #create an information label error_dialog.place(Label(text = "Error when trying to drop " + \ "player." ), left = 20, top = 20) #create the button error_dialog.default_button = DefaultButton() error_dialog.place(error_dialog.default_button, right = -20, bottom = -20) #start the reload of the players self.Load_Player_Data( ) #show the dialog error_dialog.present() #re-show the player data self.Show_Players() #end except #end if user wants to continue #end Drop_Player def Trade_Player( self, player ): """This function will add the player to the current team.""" None #end Trade_Player def Get_Current_Manager_Name( self ): """This method will retrieve the name of this instance's manager.""" return self._current_manager.Get_Username( ) #end Get_Current_Manager_Name def _Create_Overall_Team_Frame( self ): """This method will create the frame that contains the team frame.""" #create the frame self._overall_team_frame = \ Frame( container = self._main_gui.Get_Main_Frame( ), anchor = "ltrb", size = ((self._main_gui.Get_Main_Frame_Width() - \ number_constants.basic_pad), (self._main_gui.Get_Main_Frame_Height() - \ number_constants.basic_pad))) #create the drop-down self._team_dropdown = \ team_dropdown.Team_Dropdown( manager_list = self._manager_list, receiver = self, receiver_function = "Show_Team", position = ( 0, 0 ), width = self._overall_team_frame.width ) #add the drop down to the overall frame self._overall_team_frame.add( self._team_dropdown ) #end _Create_Overall_Team_Frame def Show_Team( self, manager_name, internal_switch = False ): """This method will show the team based on the name of the team's manager.""" if None == self._overall_team_frame: self._Create_Overall_Team_Frame( ) #end if team frame didn't exist before else: #remove the existing team frame from the overall team frame self._overall_team_frame.remove( self._team_frame ) #end if the team frame did exist before display_manager = self._manager_list[manager_name] #if this is a switch triggered by the program #if internal_switch: # self._team_dropdown.Set_Value( ) #end if internal switch #create this team's frame self._team_frame = \ team_frame.Team_Frame( display_team = display_manager.Get_Team(), player_keys = self._player_header_keys, container = self._overall_team_frame, anchor = "ltrb", size = (self._overall_team_frame.width, (self._overall_team_frame.height - \ self._team_dropdown.height - \ number_constants.basic_pad) ) ) #add the team frame to the overall team frame self._overall_team_frame.place( self._team_frame, sticky = "nsew", left = 0, top = (self._team_dropdown.height + \ number_constants.basic_pad) ) #give the new frame to the main GUI self._main_gui.Receive_New_Frame(self._overall_team_frame)
def open_attribute_window(window_x, window_y, db_dict, attr_dict, attr_list, attr_type, settings): # ========== Window ========== win_attribute = Window() win_attribute.title = attribute_win_title win_attribute.auto_position = False win_attribute.position = (window_x, window_y) win_attribute.size = (win_width, 500) win_attribute.resizable = 0 win_attribute.name = attribute_title + " Window" win_attribute.show() # ========== Window Image View ========== class AddAttributeWindowImageView(View): def draw(self, c, r): c.backcolor = view_backcolor c.erase_rect(r) view = AddAttributeWindowImageView(size=win_attribute.size) attribute_display_list = [] # ========== Title ========== title = Label(text=attribute_title) title.font = title_font title.width = title_width title.height = title_height title.x = (win_width - title_width) / 2 title.y = top_border title.color = title_color title.just = 'center' view.add(title) # ========== Button Declarations ========== enter_btn = Button("Enter") erase_btn = Button("Erase List") back_btn = Button("Back") # ========== Radio Button Action ========== def selection_made(): enter_btn.enabled = 1 win_attribute.become_target() def comp_selection_made(): win_attribute.become_target() def attribute_button_func(attr_value): # Check for doubles if attr_list.count(attr_value) == 0: attr_list.append(attr_value) show_attributes(attribute_display_list) erase_btn.enabled = 1 win_attribute.become_target() # ========== Attribute Radio Buttons ========== radio_group = RadioGroup(action=selection_made) radio_button_list = [] buttons_per_column = 11 config_file = '_attributes' if attr_type[:4] == 'play': config_file = 'player' + config_file elif attr_type[:4] == 'form': config_file = 'formation' + config_file elif attr_type[:4] == 'team': config_file = 'team' + config_file else: print "Invalid attribute type." with open(config_filename, 'r') as f: attributes_list = json.load(f)[config_file]['all'] f.close() for idx, attribute in enumerate(attributes_list): if attr_type[-6:] == 'search': button = RadioButton(attribute) button.group = radio_group button.value = attribute button.title = format_attr_name(attribute) elif attr_type[-4:] == 'sort': button = Button() button.action = (attribute_button_func, attribute) button.title = format_attr_name(attribute) else: print "Invalid attribute type." if attr_type[:4] == 'play': if idx < buttons_per_column: button.width = 45 button.x = (idx / buttons_per_column) * (button.width + 5) + 5 elif idx < 3*buttons_per_column: button.width = 100 button.x = (idx / buttons_per_column) * (button.width + 5) - 50 elif idx < 4*buttons_per_column: button.width = 110 button.x = (idx / buttons_per_column) * (button.width + 5) - 80 else: button.width = 100 button.x = (idx / buttons_per_column) * (button.width + 5) - 40 button.y = (idx % buttons_per_column) * 25 + title.bottom - 5 # Added for 81st item """if idx == 80: button.x = 7 * (button.width + 5) - 40 button.y = 10 * 25 + title.bottom + 5""" elif attr_type[:4] == 'form': button.width = 150 button.x = (win_attribute.width - button.width) / 2 button.y = idx * 25 + title.bottom + 5 elif attr_type[:4] == 'team': if idx < buttons_per_column: button.width = 150 button.x = win_attribute.width / 2 - (button.width + 5) else: button.width = 150 button.x = win_attribute.width / 2 + 5 button.y = (idx % buttons_per_column) * 25 + title.bottom - 5 else: print "Invalid attribute type." radio_button_list.append(button) # ========== Button Functions ========== def enter_btn_func(): valid = False return_value = None # Player if attr_type == 'player_search': # Value checks if radio_group.value in ["PAC", "SHO", "PAS", "DRI", "DEF", "PHY", "DIV", "HAN", "KIC", "REF", "SPD", "POS", "acceleration", "aggression", "agility", "balance", "ballcontrol", "crossing", "curve", "dribbling", "finishing", "freekickaccuracy", "gkdiving", "gkhandling", "gkkicking", "gkpositioning", "gkreflexes", "headingaccuracy", "interceptions", "jumping", "longpassing", "longshots", "marking", "penalties", "positioning", "potential", "rating", "reactions", "shortpassing", "shotpower", "skillMoves", "slidingtackle", "sprintspeed", "stamina", "standingtackle", "strength", "vision", "volleys", "weakFoot"]: # Value should be an integer between 0 and 100 if value_tf.value.isdigit(): return_value = int(value_tf.value) if 0 < return_value < 100: valid = True elif radio_group.value in ["age", "baseId", "clubId", "id", "leagueId", "nationId", "price"]: # Value should be an integer if value_tf.value.isdigit(): return_value = int(value_tf.value) valid = True elif radio_group.value in ["height"]: # Check if value is a decimal decimal_value = 0.0 if '.' in value_tf.value: try: decimal_value = float(value_tf.value) # If value is less than 10, assume unit is feet. Else, assume unit is centimeters. if decimal_value < 10: return_value = int(decimal_value * 30.48) else: return_value = decimal_value valid = True except Exception: print "Invalid attribute value." value_tf.value = "Invalid attribute value." elif value_tf.value.isdigit(): # If value is less than 10, assume unit is feet. Else, assume unit is centimeters. if int(value_tf.value) < 10: return_value = int(int(value_tf.value) * 30.48) else: return_value = int(value_tf.value) valid = True elif radio_group.value in ["weight"]: # Value should be an integer if value_tf.value.isdigit(): # If value is greater than 110, assume unit is pounds. Else, assume unit is kilograms. if int(value_tf.value) > 110: return_value = int(int(value_tf.value) * 0.453592) else: return_value = int(value_tf.value) valid = True elif radio_group.value in ["atkWorkRate", "birthdate", "club", "color", "commonName", "defWorkRate", "firstName", "foot", "itemType", "lastName", "league", "modelName", "name", "name_custom", "nation", "playStyle", "playerType", "position", "positionFull", "quality", "specialities", "traits"]: # Value should be a string if type(value_tf.value) is str: return_value = value_tf.value valid = True elif radio_group.value in ["isGK", "isSpecialType"]: # Value should be a string if value_tf.value.upper() in ['T', 'F', 'TRUE', 'FALSE', 'Y', 'N', 'YES', 'NO']: if value_tf.value.upper()[0] in ['T', 'Y']: return_value = True else: return_value = False valid = True if valid: attr_dict[radio_group.value] = (return_value, compare_group.value) value_tf.value = '' show_attributes(attribute_display_list) erase_btn.enabled = 1 else: print "Invalid attribute value." value_tf.value = "Invalid attribute value." # Formation elif attr_type == 'formation_search': # Value checks if radio_group.value in ["num_attackers", "num_midfielders", "num_defenders"]: # Value should be an integer between 0 and 10 if value_tf.value.isdigit(): return_value = int(value_tf.value) if 0 < return_value < 10: valid = True elif radio_group.value in ["num_links"]: # Value should be an integer if value_tf.value.isdigit(): return_value = int(value_tf.value) valid = True elif radio_group.value in ["name", "style", "description", "position_all"]: # Value should be a string if type(value_tf.value) is str: return_value = value_tf.value valid = True if valid: attr_dict[radio_group.value] = (return_value, compare_group.value) value_tf.value = '' show_attributes(attribute_display_list) erase_btn.enabled = 1 else: print "Invalid attribute value." value_tf.value = "Invalid attribute value." # Team elif attr_type == 'team_search': # Value checks if radio_group.value in ["rating", "chemistry", "total_ic"]: # Value should be an integer between -1 and 111 if value_tf.value.isdigit(): return_value = int(value_tf.value) if -1 < return_value < 111: valid = True elif radio_group.value in ["total_skillMoves"]: # Value should be an integer between 10 and 56 if value_tf.value.isdigit(): return_value = int(value_tf.value) if 10 < return_value < 56: valid = True elif radio_group.value in ["strength", "total_price", "total_PAC", "total_SHO", "total_PAS", "total_DRI", "total_DEF", "total_PHY"]: # Value should be an integer if value_tf.value.isdigit(): return_value = int(value_tf.value) valid = True elif radio_group.value in ["player", "formation", "manager_league", "manager_nation", "style"]: # Value should be a string if type(value_tf.value) is str: return_value = value_tf.value valid = True if valid: attr_dict[radio_group.value] = (return_value, compare_group.value) value_tf.value = '' show_attributes(attribute_display_list) erase_btn.enabled = 1 else: print "Invalid attribute value." value_tf.value = "Invalid attribute value." else: print 'Invalid attr_type for AddAttribute.' win_attribute.become_target() def erase_btn_func(): if attr_type[-4:] == 'sort': del attr_list[:] elif attr_type[-6:] == 'search': attr_dict.clear() show_attributes(attribute_display_list) win_attribute.become_target() erase_btn.enabled = 0 def back_btn_func(): if settings['window'] == 'search': SearchMenu.open_search_menu(win_attribute.x, win_attribute.y, db_dict, attr_dict, attr_list, settings) elif settings['window'] == 'edit': EditMenu.open_edit_menu(win_attribute.x, win_attribute.y, db_dict, attr_dict, attr_list, settings) elif settings['window'] == 'ultimate_player_judging': CreateUltimateTeams.open_create_ultimate_teams_window( win_attribute.x, win_attribute.y, db_dict, settings['prev_window_value'], player_judge_list=attr_list, file_name=settings['file_name'], roster=settings['roster'], input_formation=settings['input_formation']) elif settings['window'] == 'ultimate_team_judging': CreateUltimateTeams.open_create_ultimate_teams_window( win_attribute.x, win_attribute.y, db_dict, settings['prev_window_value'], team_judge_list=attr_list, file_name=settings['file_name'], roster=settings['roster'], input_formation=settings['input_formation']) elif settings['window'] == 'pick_player': PickPlayer.open_pick_player_window(win_attribute.x, win_attribute.y, db_dict, settings['input_formation'], settings['win_previous'], settings['roster'], settings['pos_symbol'], settings['pick_formations_page'], attr_dict, attr_list, settings) else: print "Invalid window setting." win_attribute.become_target() win_attribute.hide() def attr_btn_func(attr_to_remove): # Remove from attribute dict if attr_type[-6:] == 'search': attr_dict.pop(attr_to_remove, None) show_attributes(attribute_display_list) if len(attr_dict) < 1: erase_btn.enabled = 0 # Remove from attribute list elif attr_type[-4:] == 'sort': if attr_to_remove in attr_list: attr_list.remove(attr_to_remove) show_attributes(attribute_display_list) if len(attr_list) < 1: erase_btn.enabled = 0 win_attribute.become_target() # ========== Buttons ========== custom_button_width = 100 erase_btn.x = (win_width - custom_button_width) / 2 erase_btn.y = win_attribute.height - 70 erase_btn.height = button_height erase_btn.width = custom_button_width erase_btn.font = button_font erase_btn.action = erase_btn_func erase_btn.style = 'default' erase_btn.color = button_color erase_btn.just = 'right' if (attr_type[-4:] == 'sort' and len(attr_list) == 0) or \ (attr_type[-6:] == 'search' and len(attr_dict) == 0): erase_btn.enabled = 0 if attr_type[-4:] == 'sort': erase_btn.x = (win_width - 2*custom_button_width - button_spacing) / 2 view.add(erase_btn) enter_btn.x = erase_btn.left - button_spacing - custom_button_width enter_btn.y = erase_btn.top enter_btn.height = button_height enter_btn.width = custom_button_width enter_btn.font = button_font enter_btn.action = enter_btn_func enter_btn.style = 'default' enter_btn.color = button_color enter_btn.just = 'right' enter_btn.enabled = 0 if attr_type[-6:] == 'search': view.add(enter_btn) back_btn.x = erase_btn.right + button_spacing back_btn.y = erase_btn.top back_btn.height = button_height back_btn.width = custom_button_width back_btn.font = button_font back_btn.action = back_btn_func back_btn.style = 'default' back_btn.color = button_color back_btn.just = 'right' view.add(back_btn) # ========== Value Textfield ========== value_tf = TextField() value_tf.width = 200 value_tf.x = (win_width - value_tf.width) / 2 value_tf.y = erase_btn.top - 35 value_tf.height = 25 value_tf.font = std_tf_font # ========== Compare Radio Buttons ========== compare_group = RadioGroup(action=comp_selection_made) comp_button_list = [] comp_button_width = 55 comp_button_x = (win_attribute.width - 4*comp_button_width)/2 for value in ['higher', 'exact', 'lower', 'not']: button = RadioButton() button.width = comp_button_width button.x = comp_button_x button.y = value_tf.top - value_tf.height - title_border button.group = compare_group button.value = value button.title = value.capitalize() comp_button_x += comp_button_width + 5 comp_button_list.append(button) compare_group.value = 'higher' def show_attributes(display_list): # Remove old attribute buttons from screen for message in display_list: view.remove(message) del display_list[:] # Display new search attributes on screen message_x = 10 message_y = win_attribute.height - 150 if attr_type[-6:] == 'search': display_list.append(Label(text="Search Attributes:", font=title_tf_font, width=std_tf_width, height=std_tf_height, x=message_x, y=message_y, color=title_color)) message_y += std_tf_height index = 0 for key, search_value in attr_dict.iteritems(): if index == 6: message_x = win_attribute.width - std_tf_width - 10 message_y = win_attribute.height - 150 + std_tf_height msg_text = format_attr_name(key) + ": " if key in ['id', 'baseId', 'nationId', 'leagueId', 'clubId']: msg_text += str(search_value[0]) elif type(search_value[0]) is int: msg_text += search_value[1].capitalize() + ' ' + str(search_value[0]) elif search_value[1] == 'not': msg_text += search_value[1].capitalize() + ' "' + str(search_value[0]) + '"' else: msg_text += '"' + str(search_value[0]) + '"' attr_btn = Button(title=msg_text, font=std_tf_font, width=std_tf_width, height=std_tf_height, x=message_x, y=message_y, color=title_color, action=(attr_btn_func, key)) message_y += std_tf_height + 1 display_list.append(attr_btn) index += 1 # Display new sort attributes on screen elif attr_type[-4:] == 'sort': display_list.append(Label(text="Sort Attributes:", font=title_tf_font, width=std_tf_width, height=std_tf_height, x=message_x, y=message_y, color=title_color)) message_y += std_tf_height for index, sort_value in enumerate(attr_list): if index == 6: message_x = win_attribute.width - std_tf_width - 10 message_y = win_attribute.height - 150 + std_tf_height attr_btn = Button(title=(format_attr_name(sort_value)), font=std_tf_font, width=std_tf_width, height=std_tf_height, x=message_x, y=message_y, color=title_color, action=(attr_btn_func, sort_value)) message_y += std_tf_height + 1 display_list.append(attr_btn) for attribute_label in display_list: view.add(attribute_label) show_attributes(attribute_display_list) # ========== Add buttons to window ========== # Shows only for getting attribute for search, not sort if attr_type[-6:] == 'search': view.add(value_tf) for button in comp_button_list: view.add(button) for button in radio_button_list: view.add(button) win_attribute.add(view) view.become_target() win_attribute.show()
from GUI import Window, CheckBox, Label, TextField, Grid, application from testing import say items = [ [Label("Name"), TextField(width=100)], [Label("Age"), TextField(width=50)], [Label("Language"), CheckBox("Python")], ] grid = Grid(items) win = Window(title="Grid") grid.position = (10, 10) win.add(grid) win.shrink_wrap() win.show() instructions = """ There should be six components laid out in a grid of three rows and two columns. Each component should be centre-left aligned within its cell. """ say(instructions) application().run()
def open_enter_text_window(window_x, window_y, db_dict, settings, box_type, fill_text='', file_prefix=''): general_display = [] if box_type == 'rename': title = 'Rename File' old_file_name = fill_text message_text = 'Enter new file name.' elif box_type == 'duplicate': title = 'Duplicate File' old_file_name = fill_text message_text = 'Enter new file name.' elif box_type == 'download': title = 'Download Player Database' message_text = 'Enter player database name.' download_settings = {'overwrite_counter': 0, 'last_entered_text': ''} else: title = 'Enter Text' message_text = 'Enter text.' # ========== Window ========== win_enter_text = Window() win_enter_text.title = title win_enter_text.auto_position = False win_enter_text.position = (window_x+100, window_y+100) win_enter_text.size = (win_width-200, win_height-400) win_enter_text.resizable = 0 win_enter_text.name = enter_text_title + " Window" win_enter_text.show() # ========== Window Image View ========== class StartWindowImageView(View): def draw(self, c, r): c.backcolor = view_backcolor c.erase_rect(r) view = StartWindowImageView(size=win_enter_text.size) # ========== Title ========== title = Label(text=title) title.font = title_font title.width = title_width title.height = title_height title.x = (win_enter_text.width - title_width) / 2 title.y = top_border title.color = title_color title.just = 'center' general_display.append(title) # ========== Message Label ========== message = Label(font=title_font_2, width=win_enter_text.width - 50, height=title_height, x=25, y=title.bottom + top_border, color=title_color, just='center') message.text = message_text general_display.append(message) # ========== Button Declarations ========== enter_btn = Button("Enter") back_btn = Button("Back") # ========== Button Functions ========== def enter_btn_func(): # Rename file if box_type == 'rename': # Get new name new_file_name = value_tf.value if len(new_file_name) > 0: if not isfile('JSONs/' + file_prefix + new_file_name + '.json'): # Rename file rename('JSONs/' + file_prefix + old_file_name + '.json', 'JSONs/' + file_prefix + new_file_name + '.json') # Disable pick file back button in case the selected file has changed settings['file_changes'] = True PickFile.open_pick_file_window(window_x, window_y, db_dict, settings) win_enter_text.hide() else: message.text = "A file with that name already exists." else: message.text = "File name must be at least 1 character." # Duplicate file elif box_type == 'duplicate': # Get new name duplicate_file_name = value_tf.value if len(duplicate_file_name) > 0: if not isfile('JSONs/' + file_prefix + duplicate_file_name + '.json'): # Create duplicate file copyfile('JSONs/' + file_prefix + old_file_name + '.json', 'JSONs/' + file_prefix + duplicate_file_name + '.json') PickFile.open_pick_file_window(window_x, window_y, db_dict, settings) win_enter_text.hide() else: message.text = "A file with that name already exists." else: message.text = "File name must be at least 1 character." elif box_type == 'download': valid_name = False # Get new player database name new_player_db_name = value_tf.value if new_player_db_name != download_settings['last_entered_text']: download_settings['overwrite_counter'] = 0 message.text = message_text if len(new_player_db_name) > 0: if not isfile('JSONs/play_db_' + new_player_db_name + '.json'): valid_name = True else: download_settings['last_entered_text'] = new_player_db_name if download_settings['overwrite_counter'] == 0: download_settings['overwrite_counter'] += 1 message.text = "File already exists. Overwrite?" elif download_settings['overwrite_counter'] == 1: download_settings['overwrite_counter'] += 1 message.text = "Are you sure you want to overwrite?" elif download_settings['overwrite_counter'] == 2: download_settings['overwrite_counter'] += 1 message.text = "Really, really, really sure?" elif download_settings['overwrite_counter'] >= 3: valid_name = True if valid_name: # Open status window to start download of players StatusWindow.open_status_window(win_enter_text.x, win_enter_text.y, db_dict, get_prices=sort_order_radio_group.value, file_name=new_player_db_name, settings=settings, win_previous=win_enter_text, win_next='FilesMenu') win_enter_text.hide() else: message.text = "File name must be at least 1 character." def back_btn_func(): if box_type == 'download': FilesMenu.open_files_menu(window_x, window_y, db_dict, settings) else: PickFile.open_pick_file_window(window_x, window_y, db_dict, settings) win_enter_text.hide() # ========== Buttons ========== enter_btn.x = (win_enter_text.width - 2*button_width - button_spacing) / 2 enter_btn.y = win_enter_text.height - 70 enter_btn.height = button_height enter_btn.width = button_width enter_btn.font = button_font enter_btn.action = enter_btn_func enter_btn.style = 'default' enter_btn.color = button_color enter_btn.just = 'right' general_display.append(enter_btn) back_btn.x = enter_btn.right + button_spacing back_btn.y = enter_btn.top back_btn.height = button_height back_btn.width = button_width back_btn.font = button_font back_btn.action = back_btn_func back_btn.style = 'default' back_btn.color = button_color back_btn.just = 'right' general_display.append(back_btn) # ========== Value Textfield ========== value_tf = TextField() value_tf.width = 200 value_tf.x = (win_enter_text.width - value_tf.width) / 2 value_tf.y = enter_btn.top - 65 value_tf.height = 25 value_tf.font = std_tf_font value_tf.value = fill_text general_display.append(value_tf) def get_attribute_sort_order_rg(): settings['order_rg'] = sort_order_radio_group.value win_enter_text.become_target() sort_order_radio_group = RadioGroup(action=get_attribute_sort_order_rg) prices_label_width = 85 prices_button_width = 50 prices_label = Label(text="Get Prices?:", font=std_tf_font, width=prices_label_width, height=std_tf_height, color=title_color) prices_label.x = (win_enter_text.width - 2*prices_button_width - 10 - prices_label_width) / 2 prices_label.y = enter_btn.top - 38 prices_label.just = 'center' prices_yes = RadioButton("Yes") prices_yes.width = prices_button_width prices_yes.x = prices_label.right + 5 prices_yes.y = prices_label.top prices_yes.group = sort_order_radio_group prices_yes.value = True prices_no = RadioButton("No") prices_no.width = prices_button_width prices_no.x = prices_yes.right + 5 prices_no.y = prices_label.top prices_no.group = sort_order_radio_group prices_no.value = False sort_order_radio_group.value = True if box_type == 'download': value_tf.y = enter_btn.top - 75 general_display.append(prices_label) general_display.append(prices_yes) general_display.append(prices_no) # ========== Add buttons to window ========== for item in general_display: view.add(item) win_enter_text.add(view) view.become_target() win_enter_text.show()
def __init__(self, session, transport, **kwargs): title = 'Login' self._session = session self._transport = transport if 'title' in kwargs: title = kwargs['title'] ModalDialog.__init__(self, title=title) label = Label('Key File:') btn_rsa = RadioButton(title='RSA', value='RSA') btn_dss = RadioButton(title='DSS', value='DSS') self.key_file_group = key_file_group = RadioGroup( items=[btn_rsa, btn_dss]) key_file_group.value = 'RSA' self.txt_key_file = txt_key_file = TextField(multiline=False, password=False) btn_browse_file = Button('Browse', action='choose_key_file', enabled=True) lbl_login = Label('Login') self.txt_login = TextField(multiline=False, password=False) if 'username' in kwargs: self.txt_login.text = kwargs['username'] lbl_passwd = Label('Password') self.txt_passwd = TextField(multiline=False, password=True) self.ok_button = Button("Connect", action="ok", enabled=True, style='default') self.cancel_button = Button("Cancel", enabled=True, style='cancel', action='cancel') self.place(label, left=padding, top=padding) self.place(btn_rsa, left=label + padding, top=padding) self.place(btn_dss, left=btn_rsa + padding, top=padding) self.place(txt_key_file, left=padding, top=btn_rsa + padding, right=240) self.place(btn_browse_file, left=txt_key_file, top=txt_key_file.top) self.place(lbl_login, left=padding, top=txt_key_file + padding) self.place(self.txt_login, left=padding, top=lbl_login + padding, right=btn_browse_file.right) self.place(lbl_passwd, left=padding, top=self.txt_login + padding) self.place(self.txt_passwd, left=padding, top=lbl_passwd + padding, right=btn_browse_file.right) self.place(self.cancel_button, top=self.txt_passwd + padding, right=btn_browse_file.right) self.place(self.ok_button, top=self.txt_passwd + padding, right=self.cancel_button - padding) self.shrink_wrap(padding=(padding, padding))