def createListFrame(self): # TODO rename self.list_frame = Frame(master=self) self.list_frame.pack(side='left', padx=0, pady=0, fill="both", expand=True) canvas = Canvas(self.list_frame, bg="gray") scroll_y = Scrollbar(self.list_frame, orient="vertical", command=canvas.yview) scroll_frame = Frame(canvas, bg="gray") void_label = Label(master=scroll_frame, text=" " * 255, bg="gray") void_label.pack(padx=2, pady=2, side="bottom") for e in self.windowList: self.createWindowFrame(scroll_frame, windowObject=e) canvas.create_window(0, 0, anchor='nw', window=scroll_frame) canvas.update_idletasks() scroll_frame.update() canvas.configure( scrollregion=canvas.bbox( 'all' ), # scrollregion=canvas.bbox('all') #TODO: #20 scrollregion yscrollcommand=scroll_y.set) canvas.pack(fill='both', expand=True, side='left') scroll_y.pack(fill='y', side='right')
class Window: """ Abstract Window class """ def __init__(self, root): self.root = root self.frame = Frame(master=self.root, bd=0, height=670, width=1280, bg=BACKGROUND) def show(self): self.frame.pack(side=TOP) self.frame.pack_propagate(0) def hide(self): self.frame.pack_forget() def update(self): self.frame.update()
class Component(Extendable, ABC): """ A blank base component which extends lifecycle methods to be overriden as necessary """ def __init__(self, container: Widget, get_data: Optional[Callable[["Component"], Any]] = None, on_change: Callable = lambda: None, update_interval: Optional[int] = None, styles: Optional[dict] = None): super().__init__() self._container = container self._outer_frame = Frame(self._container) self._frame = None # Add child elements to this frame in _render() # Allow the outer frame to expand to fill the container self._outer_frame.rowconfigure(0, weight=1) self._outer_frame.columnconfigure(0, weight=1) # All element styles should be stored here, as their own dicts self.styles = {} styles = {} if not styles else styles self.styles["frame"] = styles.get("frame", {}) # Use this space to keep hold of any elements that might need configuring in _update or _get_data self.children = {} self._update_interval = update_interval # Milliseconds """ This function should receive this component instance as a parameter and return any data from the application state that is needed by this component. If it is set to None rather than a function, this indicates that there is no outside data source. Other aspects of this component (styles, etc.) can be edited during the execution of this function. """ self._get_data = get_data """ When the state of this component changes, this function should be called and passed this component instance and any event data as parameters. The function should perform any additional external work needed. """ self._on_change = on_change @property def exists(self) -> bool: """ Should be used to check that the component has not been destroyed, before its state is altered in any way """ return self._outer_frame.winfo_exists() @property def is_rendered(self) -> bool: """ Used internally to check that a component has rendered its contained widgets, before checking their details """ if self._frame is None: return False self._frame.update() return self._frame.winfo_exists() @property def height(self) -> int: self._outer_frame.update() return self._outer_frame.winfo_height() @property def width(self) -> int: self._outer_frame.update() return self._outer_frame.winfo_width() @property def height_clearance(self) -> Optional[int]: """ Represents the amount of vertical space in the widget (values such as padding and border are removed) """ if not self.is_rendered: return None frame_padding = self.styles["frame"].get("pady", 0) frame_borderwidth = self.styles["frame"].get("borderwidth", 0) total_buffer = (2 * frame_padding) + (2 * frame_borderwidth) return self._frame.winfo_height() - total_buffer @property def width_clearance(self) -> Optional[int]: """ Represents the amount of horizontal space in the widget (values such as padding and border are removed) """ if not self.is_rendered: return None frame_padding = self.styles["frame"].get("padx", 0) frame_borderwidth = self.styles["frame"].get("borderwidth", 0) total_buffer = (2 * frame_padding) + (2 * frame_borderwidth) return self._frame.winfo_width() - total_buffer def render(self) -> Frame: """ This method should be invoked externally, and the returned frame have pack() or grid() called on it """ for child_element in self._outer_frame.winfo_children(): child_element.destroy() self._refresh_frame() self._render() if self._update_interval: self._frame.after(self._update_interval, self._update_loop) return self._outer_frame def _update_loop(self) -> None: """ Used internally to handle updating the component once per update interval (if update interval was provided) """ self._frame.after_cancel(self._update_loop) if not self.exists: return if self._update_interval: self._frame.after(self._update_interval, self._update_loop) self._update() if self._needs_render: self.render() # Overridable Methods @property def _needs_render(self) -> bool: """ Overridable method. Should return a True value only once per time a re-render is required. If the component will never need to poll for a re-render, this method need not be overridden """ return False def _refresh_frame(self) -> None: """ Overridable method. Handles creating a new blank frame to store in self._frame at the top of each render() call. Only needs overriding if this blank frame needs extra base functionality before any child components are rendered to it """ self._frame = Frame(self._outer_frame, **self.styles["frame"]) self._frame.grid(row=0, column=0, sticky="nswe") def _update(self) -> None: """ Overridable method. Handles updating the component state once per update interval (if update interval was provided). If the component will not need to directly update its state outside of a new render, this method need not be overridden """ pass def _render(self) -> None: """ Overridable method. Any child components should be rendered to self._frame in this method """ raise NotImplementedError
class BattleshipsDemoClient(Frame): def __init__(self, tk, args): Frame.__init__(self, tk) # empty string for platform's default settings locale.setlocale(locale.LC_ALL, '') self.master = tk tk.title(APP_TITLE) tk.resizable(False, False) try: if WINDOWS: tk.iconbitmap("200x200/icon.ico") else: tk.iconbitmap("@200x200/icon.xbm") except Exception as e: print(e) atexit.register(self.cancel_game) # Init class data fields that we use for storing info that we need for using the API self.bot_id = None self.bot_password = None self.logged_in = False self.game_style_ids = [] self.gameChips = 0 self.gameDeals = 0 self.gameStake = 0 self.gamePrize = 0 self.player_key = None self.play_again = BooleanVar() self.do_not_play_same_user = BooleanVar() self.close_after_game = False self.game_cancelled = False self.in_game = False self.topFrame = Frame(tk, padx=12, pady=12) self.middleFrame = Frame(tk, padx=12) self.middleFrameLeft = Frame(self.middleFrame) self.middleFrameRight = Frame(self.middleFrame) self.middleFrameRighter = Frame(self.middleFrame) self.topFrame.grid(row=0, sticky=W + E) self.middleFrame.grid(row=1, sticky=W) self.middleFrameLeft.grid(row=1, column=0) self.middleFrameRight.grid(row=1, column=1) self.middleFrameRighter.grid(row=1, column=2) # =================================== # Create form elements # Top Frame Elements self.botNameLabel = Label(self.topFrame, text="Bot Name:") self.bot_id_entry = Entry(self.topFrame) self.bot_id_entry.bind('<Return>', self.log_in_if_not) self.bot_id_entry.focus() self.passwordLabel = Label(self.topFrame, text="Password:"******"Login", command=self.log_in_out_clicked) self.balanceLabel = Label(self.topFrame, text="Bot Balance:") self.balance = Label(self.topFrame, text="0") self.close_button = Button(self.topFrame, text="Close", padx=2, command=tk.destroy) # Middle Frame Elements # Middle Frame LEFT Elements self.gameStyleLabel = Label(self.middleFrameLeft, font=(None, 18), pady=0, text="Game Style Selection") self.opponentLabel = Label(self.middleFrameLeft, text="Specify Opponent (optional):") self.specify_opponent_entry = Entry(self.middleFrameLeft) self.do_not_play_same_user_check = Checkbutton( self.middleFrameLeft, text='Don\'t play another bot in same user account as me', var=self.do_not_play_same_user) self.game_styles_listbox = Listbox(self.middleFrameLeft, background='#FFFFFF', height=8) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind( '<Return>', self.find_game_double_clicked ) # Not a double click but we want it to do the same thing self.refresh_game_styles_button = Button( self.middleFrameLeft, text="Refresh Game Styles", command=self.refresh_game_styles_clicked) self.thinkingTimeLabel = Label(self.middleFrameLeft, text="Add \"Thinking Time\" (ms):") self.thinking_time_entry = Entry(self.middleFrameLeft) self.auto_play_next_game_check = Checkbutton( self.middleFrameLeft, text='Play another game when complete', var=self.play_again) self.cancel_stop_game_button = Button( self.middleFrameLeft, text=CANCEL_GAME_TEXT, command=self.cancel_stop_game_clicked) self.find_game_button = Button(self.middleFrameLeft, text="Find Game", command=self.find_game_clicked) self.resultText = Message( self.middleFrameLeft, width=300, text="This is where the informational messages will appear") self.spacerLabel = Label(self.middleFrameLeft, text=" ") # Middle Frame RIGHT Elements self.gameTitleLabel = Label(self.middleFrameRight, text="Game Title") self.gameTitleText = Text(self.middleFrameRight, height=3, background='white', spacing1=3, pady=0) self.player = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.opponent = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.gameActionLabel = Label(self.middleFrameRight, text="") # =================================== # Set initial element states self.set_gamestyle_controls_states(DISABLED) self.cancel_stop_game_button.config(state=DISABLED) self.game_styles_listbox.config(background='white') self.thinking_time_entry.insert(0, 100) self.gameTitleText.config(state=DISABLED) self.set_balance(0) self.gameTitleText.tag_configure("center", justify='center') self.gameTitleText.tag_configure("bold", font='-weight bold') # =================================== # Form Layout # Top Frame Form Layout self.topFrame.grid_rowconfigure(0, weight=1) self.botNameLabel.grid(row=0, column=0, sticky=E) self.bot_id_entry.grid(row=0, column=1, sticky=W) self.passwordLabel.grid(row=0, column=2, sticky=E) self.bot_password_entry.grid(row=0, column=3, sticky=W) self.log_in_out_button.grid(row=0, column=4, sticky=E) self.topFrame.grid_columnconfigure(5, weight=1) self.balanceLabel.grid(row=0, column=5, sticky=E) self.balance.grid(row=0, column=6, sticky=W) self.close_button.grid(row=0, column=7, sticky=E, padx=(50, 0)) # Middle Frame Form Layout self.middleFrame.grid_rowconfigure(0, weight=1) self.gameStyleLabel.grid(row=0, column=0, columnspan=1, sticky=W + E) self.spacerLabel.grid(row=0, column=2, sticky=E) self.opponentLabel.grid(row=2, column=0, sticky=W, pady=4) self.specify_opponent_entry.grid(row=2, column=0, sticky=E, pady=4) self.do_not_play_same_user_check.grid(row=3, column=0, columnspan=1, sticky='we', pady=4) self.game_styles_listbox.grid(row=4, column=0, columnspan=1, sticky='we', pady=4) self.find_game_button.grid(row=5, column=0, pady=4, sticky=W) self.refresh_game_styles_button.grid(row=5, column=0, columnspan=1, sticky='', pady=4) self.cancel_stop_game_button.grid(row=5, column=0, sticky=E) self.thinkingTimeLabel.grid(row=6, column=0, sticky=W, pady=4) self.thinking_time_entry.grid(row=6, column=0, sticky=E, pady=4) self.auto_play_next_game_check.grid(row=7, column=0, columnspan=1, sticky=W, pady=4) self.resultText.grid(row=9, column=0, columnspan=2, sticky=W, pady=4) self.middleFrame.grid_columnconfigure(9, weight=1) self.gameTitleLabel.grid(row=0, column=3) self.gameTitleText.grid(row=0, column=3, columnspan=2) self.player.grid(row=1, column=3) self.opponent.grid(row=1, column=4) self.gameActionLabel.grid(row=11, column=3, sticky='w') if args.botid is not None: self.auto_play(args) def auto_play(self, args): self.bot_id_entry.insert(0, args.botid) self.bot_password_entry.insert(0, args.password) self.log_in_out_clicked() self.thinking_time_entry.insert(0, args.timeout) if args.playanothergame: self.auto_play_next_game_check.select() if args.dontplaysameuserbot: self.do_not_play_same_user_check.select() if args.closeaftergame: self.close_after_game = True i = 0 for i in range(self.game_styles_listbox.size()): if args.gamestyle in str(self.game_styles_listbox.get(i)): break self.game_styles_listbox.select_set(i, i) self.find_game_clicked() def log_in_out_clicked(self): """Click handler for the 'Login'/'Logout' button.""" # This means we're logging out if self.logged_in: self.resultText.config(text='Logged Out') self.master.title(APP_TITLE + " (Not Logged In)") self.cancel_game() self.bot_id = 'housebot-competition' self.bot_password = None self.clear_game_title_text() self.gameActionLabel.config(text="") self.reset_game_styles_listbox() self.clear_all_boards() self.opponent.delete("all") self.log_in_out_button.config(text='Login') self.set_login_controls_states(ENABLED) self.set_gamestyle_controls_states(DISABLED) self.logged_in = False self.bot_password_entry.delete(0, 'end') self.set_balance(0) # This means we're logging in else: self.bot_id = self.bot_id_entry.get() self.bot_password = '******' res = self.get_list_of_game_styles() if res['Result'] == 'SUCCESS': self.resultText.config(text='Logged In') game_styles = res['GameStyles'] self.master.title(self.bot_id + " - " + APP_TITLE) self.set_login_controls_states(DISABLED) self.set_gamestyle_controls_states(ENABLED) self.set_game_styles_listbox(game_styles) self.set_balance(res['Balance']) self.log_in_out_button.config(text='Logout') self.logged_in = True else: messagebox.showerror( 'Error', 'Invalid login attempt. Please check the username and password entered.' ) def log_in_if_not(self, _): if not self.logged_in: self.log_in_out_clicked() def clear_all_boards(self): self.player.delete("all") self.opponent.delete("all") self.player.myBoard = None self.opponent.oppBoard = None def set_in_game(self, value): self.in_game = value def set_game_title_text(self, text, tag): self.gameTitleText.config(state=ENABLED) self.gameTitleText.insert("end", text, ("center", tag)) self.gameTitleText.config(state=DISABLED) def clear_game_title_text(self): self.gameTitleText.config(state=ENABLED) self.gameTitleText.delete("1.0", "end") self.gameTitleText.config(state=DISABLED) def set_login_controls_states(self, state): self.bot_id_entry.config(state=state) self.bot_password_entry.config(state=state) def set_gamestyle_controls_states(self, state): self.specify_opponent_entry.config(state=state) self.do_not_play_same_user_check.config(state=state) self.game_styles_listbox.config(state=state) self.find_game_button.config(state=state) self.refresh_game_styles_button.config(state=state) self.auto_play_next_game_check.config(state=state) self.thinking_time_entry.config(state=state) self.opponentLabel.config(state=state) self.thinkingTimeLabel.config(state=state) self.balanceLabel.config(state=state) self.balance.config(state=state) self.gameStyleLabel.config(state=state) self.game_styles_listbox.config(state=state) self.player.config(state=state) self.opponent.config(state=state) def set_balance(self, balance): """Set the balance field""" self.balance['text'] = int_with_commas(balance) self.balance['text'] += ' sat' def get_list_of_game_styles(self): """Get list of game styles from the server.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'GameTypeId': BATTLESHIPS_GAME_TYPE_ID } url = BASE_URL + GET_LIST_OF_GAME_STYLES_EXTENSION return BattleshipsDemoClient.make_api_call(url, req) def set_game_styles_listbox(self, game_styles): """Set the content of the game styles listbox with a list of GameStyle dictionaries. Keyword Arguments: game_styles -- The list of GameStyle dictionaries, this should be obtained through get_list_of_game_styles(). """ self.reset_game_styles_listbox() for index, game_style in enumerate(game_styles): self.game_styles_listbox.insert( index, GAME_STYLE_LISTBOX_TEXT.format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Ships'], game_style['GameTypeSpecificInfo']['Board Size'], game_style['GameTypeSpecificInfo']['Timeout ms'], game_style['GameTypeSpecificInfo']['DealsTotal'], game_style['GameTypeSpecificInfo']['PercentageLand'], game_style['GameTypeSpecificInfo']['RandomLand'])) self.game_style_ids.append(game_style['GameStyleId']) # self.game_styles_listbox.select_set(GAME_STYLE_LISTBOX_DEFAULT_SELECTION) def reset_game_styles_listbox(self): """Clear the content of the game styles listbox.""" if self.game_styles_listbox.size() != 0: self.game_styles_listbox.delete(0, 'end') self.game_style_ids = [] def refresh_game_styles_clicked(self): """Click handler for the 'Refresh Game Styles' button.""" res = self.get_list_of_game_styles() game_styles = res['GameStyles'] self.set_game_styles_listbox(game_styles) def find_game_clicked(self): """Click handler for the 'Find Game' button""" self.find_game_button.config(state=DISABLED) self.cancel_stop_game_button.config(state=ENABLED) self.clear_all_boards() # Here we dispatch the work to a separate thread, to keep the GUI responsive. if not MAC: threading.Thread(target=self.game_loop, daemon=True).start() else: self.game_loop() # Doesn't work on MACs def find_game_double_clicked(self, _): self.find_game_clicked() def game_loop(self): """Loop through finding and playing games.""" while True: self.clear_all_boards() self.find_game() if self.game_cancelled: break self.play_game() if self.close_after_game: self.close_button.invoke() if self.game_cancelled: break if not self.play_again.get(): break self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_cancelled = False def find_game(self): """Find a game.""" offer_game_res = self.offer_game() if offer_game_res['Result'] == 'INVALID_LOGIN_OR_PASSWORD': self.cancel_stop_game_clicked() if 'ErrorMessage' in offer_game_res and offer_game_res[ 'ErrorMessage'] == 'Check of OpponentId failed': self.resultText.config(text='Invalid Opponent ID') else: self.resultText.config(text='Invalid login or password') elif offer_game_res['Result'] == 'INSUFFICIENT_BALANCE': self.cancel_stop_game_clicked() self.resultText.config(text='Insufficient balance') elif offer_game_res['Result'] == 'BOT_IS_INACTIVE': self.cancel_stop_game_clicked() self.resultText.config(text='Bot is inactive') else: self.player_key = offer_game_res['PlayerKey'] if offer_game_res['Result'] == 'WAITING_FOR_GAME': self.wait_for_game() def offer_game(self): """Offer a game.""" opponent_id = self.specify_opponent_entry.get() if len(opponent_id) == 0: opponent_id = None try: game_style_id = self.game_style_ids[int( self.game_styles_listbox.curselection()[0])] except IndexError: self.game_styles_listbox.select_set( GAME_STYLE_LISTBOX_DEFAULT_SELECTION) game_style_id = self.game_style_ids[0] req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'GameStyleId': game_style_id, 'DontPlayAgainstSameUser': self.do_not_play_same_user.get(), 'DontPlayAgainstSameBot': False, 'OpponentId': opponent_id } url = BASE_URL + OFFER_GAME_EXTENSION return BattleshipsDemoClient.make_api_call(url, req) def wait_for_game(self): """Wait for game to start.""" self.resultText.config(text='Waiting for game') while True: if self.game_cancelled: self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) break poll_results = self.poll_for_game_state() if poll_results['Result'] == 'SUCCESS': break if poll_results['Result'] == 'INVALID_PLAYER_KEY' or poll_results[ 'Result'] == 'GAME_HAS_ENDED' or poll_results[ 'Result'] == 'GAME_WAS_STOPPED': self.game_cancelled = True time.sleep(2) def play_game(self): """Play a game.""" self.resultText.config(text='Playing game') self.in_game = True poll_results = self.poll_for_game_state() if poll_results["Result"] != "SUCCESS": return game_state = poll_results['GameState'] title = format('Game ID: ' + str(game_state['GameId'])) game_style_details = self.game_styles_listbox.get('active').split( " | ") title += format(' / Style: ' + str(self.game_style_ids[int( self.game_styles_listbox.curselection()[0])])) title += format(' / Land: ' + game_style_details[6].split(" ")[2] + '%') title += format(' / Deals: ' + game_style_details[5].split(" ")[1]) title += format(' / ' + game_style_details[7]) title += "\n" versus = format(self.bot_id + ' vs ' + game_state['OpponentId']) self.clear_game_title_text() self.set_game_title_text(title, "") self.set_game_title_text(versus, "bold") self.middleFrame.update() while True: if self.game_cancelled: break if game_state['IsMover']: self.resultText.config(text='Playing Game - Your Turn') move = battleships_move.calculateMove(game_state) move_results = self.make_move(move) if move_results['Result'] == 'INVALID_MOVE': self.resultText.config(text="Invalid Move") elif move_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + move_results['Result']) print("Game ended") break else: game_state = move_results['GameState'] else: self.resultText.config(text="Playing Game - Opponent's Turn") # ---- Code here will be called on your opponent's turn ---- # ---------------------------------------------------------- poll_results = self.poll_for_game_state() if poll_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + poll_results['Result']) break game_state = poll_results['GameState'] if game_state['GameStatus'] != 'RUNNING': break self.middleFrameRight.update() try: if int(self.thinking_time_entry.get()) > 0: time.sleep((int(self.thinking_time_entry.get()) / 1000)) else: time.sleep(0.1) except ValueError: time.sleep(0.1) self.set_in_game(False) def make_move(self, move): """Make a move.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key, 'Move': move } url = BASE_URL + MAKE_MOVE_EXTENSION result = BattleshipsDemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: print(result) try: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) except Exception as e: print("Gamestate error: " + str(e)) return result def poll_for_game_state(self): """Poll the server for the latest GameState.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'PlayerKey': self.player_key } url = BASE_URL + POLL_FOR_GAME_STATE_EXTENSION result = BattleshipsDemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) return result def cancel_stop_game_clicked(self): self.game_cancelled = True self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) def cancel_game(self): if self.player_key is None: return req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key } url = BASE_URL + CANCEL_GAME_OFFER_EXTENSION BattleshipsDemoClient.make_api_call(url, req) try: self.resultText.config(text='Cancelled game') except Exception as e: print(str(e) + " -- resultText Message object no longer exists") @staticmethod def make_api_call(url, req): """Make an API call.""" while True: try: res = requests.post(url, json=req, headers=API_CALL_HEADERS, timeout=60.0) try: jres = res.json() if 'Result' in jres: return jres time.sleep(0.1) except ValueError: time.sleep(0.1) except requests.ConnectionError: time.sleep(0.1) except requests.Timeout: time.sleep(0.1) except requests.HTTPError: time.sleep(0.1) except BaseException as e: # Bad code but needed for testing purposes print(e) time.sleep(0.1)
class App(Frame): def __init__(self, parent, *args, **kwargs): Frame.__init__(self, parent, *args, **kwargs) self.winfo_toplevel().title("CS430 Final Project: Samuel Golden") self.parent = parent # init fonts FONT = 'Din' TEXT_FONT = 'Courier' self.titleFont = (FONT, 16) self.headerFont = (FONT, 14, 'bold') self.textFont = (TEXT_FONT, 12) self.statusFont = (FONT, 12, 'italic') # init widgets self.outputLabel = Label(self, text='Algorithmic output:', font=self.titleFont) self.outputNb = Notebook(self) self.mstTab = Frame(self.outputNb) self.inputLabel = Label(self, text='Matrix input (-1 = no link, separate weight with single space, no trailing newline):', font=self.titleFont) self.matrixLabel = Label(self, text='Given Matrix', font=self.titleFont) self.matrixText = Text(self, font=self.textFont, height=8, width=30) self.matrixFrame = Frame(self) self.runButton = Button(self, text='Run', font=self.headerFont, relief='raised', borderwidth=5, command=self.run) self.statusStr = StringVar() self.statusStr.set('IDLE: not running.') self.statusBar = Label(self, textvariable=self.statusStr, font=self.statusFont) self.grid_all() self.config_text() self.config_nb() def run(self): self.write_status("RUNNING: parsing input matrix...") matrixInput = self.matrixText.get("1.0", END) # 1.0 means line 1, char 0 matrix = matrixInput.split('\n') matrix = [row.split(' ') for row in matrix] if len(matrix[-1]) == 1: del matrix[-1] for r in range(len(matrix)): for v in range(len(matrix[r])): try: matrix[r][v] = int(matrix[r][v]) except ValueError: self.write_status(f"STOPPED: invalid entry in matrix '{matrix[r][v]}'.") return self.write_status("RUNNING: validating input matrix...") matrixSize = len(matrix) for row in matrix: if len(row) != matrixSize: self.write_status("STOPPED: matrix size invalid (must be square).") return for i in range(0, matrixSize): if matrix[i][i] != 0: self.write_status("STOPPED: matrix diagonal should all be zeros (node cannot have link to itself)") return self.write_status("RUNNING: drawing table for parsed matrix...") matrixTable = MatrixTable(self.matrixFrame, matrix) matrixTable.grid(row=0, column=0, sticky='nsew') self.matrixFrame.update() self.write_status("RUNNING: running MST algorithm...") unsortedEdges, sortedEdges, mstEdges = mst(matrix) self.write_status("RUNNING: drawing MST visualization...") mstView = MSTView(self.mstTab) mstView.populate(unsortedEdges, sortedEdges, mstEdges) mstView.grid(row=0, column=0, sticky='nsew') self.write_status("IDLE: Done. Last successful run: " + datetime.now().strftime("%H:%M:%S")) def write_status(self, string): self.statusStr.set(string) self.parent.update() def config_text(self): start_matrix = "0 200 500 10 -1\n200 0 80 70 90\n50 80 0 -1 40\n10 70 -1 0 20\n-1 90 40 20 0" self.matrixText.insert(END, start_matrix) def config_nb(self): self.outputNb.add(self.mstTab, text='Minimum Spanning Tree') self.outputNb.select(self.mstTab) self.outputNb.enable_traversal() def grid_all(self): to_grid = [ # r c rs cs stick widget (1, 0, 1, 2, 'nsw', self.outputLabel), (2, 0, 1, 2, 'nsew', self.outputNb), (3, 0, 1, 2, 'nsw', self.inputLabel), (4, 0, 1, 1, 'nsew', self.matrixText), (4, 1, 1, 1, 'nsew', self.matrixFrame), (5, 0, 1, 2, 'ns', self.runButton), (6, 0, 1, 2, 'nsew', self.statusBar) ] for w in to_grid: w[5].grid(row=w[0], column=w[1], sticky=w[4], columnspan=w[3], rowspan=w[2], padx=10, pady=10) self.columnconfigure(0, weight=1)
from tkinter import Tk,Frame,Grid, Label, Button, Canvas from rgbSensor import getRGB app = Tk() app.title("RGB GUI") # * Name of the window # * Main frame on which everything is added f = Frame(app,width=800,height=500) f.grid(row=1,column=0,sticky="NW") f.grid_propagate(0) f.update() # * Title Label title = Label(f,text="RGB Viewer") title.config(font=("Roboto Slab", 20)) title.place(x=400, y=50, anchor="center") colors=getRGB() red=Label(f,text="RED: "+str(colors[0])) red.config(font=("Roboto Slab", 15)) red.place(x=400, y=100, anchor="center") green=Label(f,text="GREEN: "+str(colors[1])) green.config(font=("Roboto Slab", 15)) green.place(x=400, y=150, anchor="center") blue=Label(f,text="BLUE: "+str(colors[2])) blue.config(font=("Roboto Slab", 15)) blue.place(x=400, y=200, anchor="center")
class WiFiCrack(object): def __init__(self, password_filepath): self.password_filepath = password_filepath self.win = Tk() self.win.title(soft_tk_title) soft_tk_x = int((self.win.winfo_screenwidth() - soft_tkwidth) / 2) soft_tk_y = int((self.win.winfo_screenheight() - soft_tkheight) / 2) soft_tk_size = '{}x{}+{}+{}'.format(soft_tkwidth, soft_tkheight, soft_tk_x, soft_tk_y) self.win.geometry(soft_tk_size) self.e1_str = StringVar() self.l1_str = StringVar() self.cancel_flag = False self.canvas_posx = (5, 5) self.canvas_posy = (5, 24) self.ftop = Frame(self.win) self.ftop.pack(side='top') self.fcen = Frame(self.win) self.fcen.pack() self.fbot = Frame(self.win) self.fbot.pack(side='bottom') self.cv1 = Canvas(self.ftop, width=150, height=24, bg='white') self.cv1.pack(side='left') self.lb1 = Label(self.ftop, textvariable=self.l1_str, width=5, height=1, bg='white') self.lb1.pack(side='right') self.lb2 = Label(self.fcen, text='密码:') self.lb2.pack(side='left') self.ent1 = Entry(self.fcen, textvariable=self.e1_str, width=30) self.ent1.pack(side='right') self.but0 = Button(self.fbot, text='检查无线网卡', command=self.check_wifi_module) self.but1 = Button(self.fbot, text='点击获取', command=self.get_password) self.but2 = Button(self.fbot, text='取消获取', command=self.cancel_get_password) self.but3 = Button(self.fbot, text='退出', command=self.win.quit) self.but0.pack(side='left') self.but1.pack(side='left', anchor='w') self.but2.pack(side='left') self.but3.pack(side='right', anchor='e') def get_password_lists(self): with open(self.password_filepath, 'r') as fr: password_lists = fr.readlines() return password_lists def get_password(self): wifi_obj = pywifi.PyWiFi() wireless_lists = wifi_obj.interfaces() if wireless_lists != []: wireless_obj = wireless_lists[0] profile_obj = pywifi.Profile() self.password_lists = self.get_password_lists() wifi_crack = MyWifiCrack(wireless_obj, profile_obj) # 填充进度条 self.out_rec = self.cv1.create_rectangle(self.canvas_posx[0], self.canvas_posx[1], self.canvas_posy[0] + 100, self.canvas_posy[1], outline="green", width=1) self.fill_rec = self.cv1.create_rectangle(self.canvas_posx[0], self.canvas_posx[1], self.canvas_posy[0], self.canvas_posy[1], outline="", width=0, fill="green") for i in range(len(self.password_lists)): time.sleep(0.1) wifi_crack.run_password_str(self.password_lists[i]) self.change_schedule(i, len(self.password_lists) - 1) if self.cancel_flag: self.l1_str.set('') break #更新进度条函数 def change_schedule(self, now_schedule, all_schedule): self.cv1.coords( self.fill_rec, (self.canvas_posx[0], self.canvas_posx[1], self.canvas_posy[0] + 1 + (now_schedule / all_schedule) * 100, self.canvas_posy[1])) self.ftop.update() self.l1_str.set(str(round(now_schedule / all_schedule * 100, 2)) + '%') if round(now_schedule / all_schedule * 100, 2) == 100.00: self.l1_str.set("完成") def cancel_get_password(self): self.cv1.delete(self.out_rec) self.cv1.delete(self.fill_rec) self.l1_str.set('') self.cancel_flag = True def check_wifi_module(self): wifi_obj = pywifi.PyWiFi() wireless_lists = wifi_obj.interfaces() warn_title = '警告' warn_no_wifi_module_msg = '该电脑没有无线网卡模块!' warn_has_wifi_module_msg = '该电脑存在无线网卡模块,可以吃尝试获取密码!' if wireless_lists == []: messagebox.showwarning(warn_title, warn_no_wifi_module_msg) else: messagebox.showwarning(warn_title, warn_has_wifi_module_msg) def show(self): self.win.mainloop()
class DemoClient(Frame): def __init__(self, tk, args): Frame.__init__(self, tk) locale.setlocale(locale.LC_ALL, '') # empty string for platform's default settings self.master = tk self.config = json.load(open('config.json', 'r')) self.config['COMBOBOX_INDEX'] = sorted(self.config['COMBOBOX_INDEX'], key=lambda x: x[0]) self.game_type = int( args.gametype ) if args.gametype else self.config["DEFAULT_GAME_TYPE_ID"] tk.title(self.config["APP_TITLE"]) tk.resizable(False, False) self.get_icon() atexit.register(self.cancel_game) # Init class data fields that we use for storing info that we need for using the API self.bot_id = None self.bot_password = None self.logged_in = False self.game_style_ids = [] self.gameChips = 0 self.gameDeals = 0 self.gameStake = 0 self.gamePrize = 0 self.player_key = None self.play_again = BooleanVar() self.do_not_play_same_user = BooleanVar() self.close_after_game = False self.game_cancelled = False self.in_game = False self.topFrame = Frame(tk, padx=12, pady=12) self.middleFrame = Frame(tk, padx=12) self.middleFrameLeft = Frame(self.middleFrame) self.middleFrameRight = Frame(self.middleFrame) self.middleFrameRighter = Frame(self.middleFrame) self.topFrame.grid(row=0, sticky=W + E) self.middleFrame.grid(row=1, sticky=W) self.middleFrameLeft.grid(row=1, column=0) self.middleFrameRight.grid(row=1, column=1) self.middleFrameRighter.grid(row=1, column=2) # =================================== # Create form elements # Top Frame Elements self.botNameLabel = Label(self.topFrame, text="Bot Name:") self.bot_id_entry = Entry(self.topFrame) self.bot_id_entry.bind('<Return>', self.log_in_if_not) self.bot_id_entry.focus() self.passwordLabel = Label(self.topFrame, text="Password:"******"Login", command=self.log_in_out_clicked) self.balanceLabel = Label(self.topFrame, text="Bot Balance:") self.balance = Label(self.topFrame, text="0") self.close_button = Button(self.topFrame, text="Close", padx=2, command=tk.destroy) # Middle Frame Elements # Middle Frame LEFT Elements self.gameTypeCmb = ttk.Combobox( self.middleFrameLeft, state="disabled", values=tuple((game[0]) for game in self.config['COMBOBOX_INDEX'])) if self.game_type != self.config['NULL_GAME_TYPE_ID']: index = [ i for i in range(len(self.config['COMBOBOX_INDEX'])) if self.config['COMBOBOX_INDEX'][i][1] == self.game_type ][0] self.gameTypeCmb.current( index) # Default selection matches default game type id self.gameTypeCmb.bind("<<ComboboxSelected>>", self.game_type_selected) self.gameStyleLabel = Label(self.middleFrameLeft, font=(None, 18), pady=0, text="Game Style Selection") self.opponentLabel = Label(self.middleFrameLeft, text="Specify Opponent (optional):") self.specify_opponent_cmb = ttk.Combobox( self.middleFrameLeft, values=self.config['AVAILABLE_OPPONENTS']) self.do_not_play_same_user_check = Checkbutton( self.middleFrameLeft, text='Don\'t play another bot in same user account as me', var=self.do_not_play_same_user) self.game_styles_listbox = Listbox(self.middleFrameLeft, background='#FFFFFF', height=8) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind( '<Return>', self.find_game_double_clicked ) # Not a double click but we want it to do the same thing self.refresh_game_styles_button = Button( self.middleFrameLeft, text="Refresh Game Styles", command=self.refresh_game_styles_clicked) self.thinkingTimeLabel = Label(self.middleFrameLeft, text="Add \"Thinking Time\" (ms):") self.thinking_time_entry = Entry(self.middleFrameLeft) self.auto_play_next_game_check = Checkbutton( self.middleFrameLeft, text='Play another game when complete', var=self.play_again) self.cancel_stop_game_button = Button( self.middleFrameLeft, text=CANCEL_GAME_TEXT, command=self.cancel_stop_game_clicked) self.find_game_button = Button(self.middleFrameLeft, text="Find Game", command=self.find_game_clicked) self.resultText = Message( self.middleFrameLeft, width=300, text="This is where the informational messages will appear") self.spacerLabel = Label(self.middleFrameLeft, text=" ") # Middle Frame RIGHT Elements self.gameTitleLabel = Label(self.middleFrameRight, text="Game Title") self.gameTitleText = Text(self.middleFrameRight, height=3, background='white', spacing1=3, pady=0) self.player = None # Initialise as none before updating in create_visuals() self.opponent = None # Initialise as none before updating in create_visuals() self.create_visuals() self.gameActionLabel = Label(self.middleFrameRight, text="") # =================================== # Set initial element states self.set_gamestyle_controls_states(DISABLED) self.cancel_stop_game_button.config(state=DISABLED) self.game_styles_listbox.config(background='white') self.thinking_time_entry.insert(0, 100) self.gameTitleText.config(state=DISABLED) self.set_balance(0) self.gameTitleText.tag_configure("center", justify='center') self.gameTitleText.tag_configure("bold", font='-weight bold') # =================================== # Form Layout # Top Frame Form Layout self.topFrame.grid_rowconfigure(0, weight=1) self.botNameLabel.grid(row=0, column=0, sticky=E) self.bot_id_entry.grid(row=0, column=1, sticky=W) self.passwordLabel.grid(row=0, column=2, sticky=E) self.bot_password_entry.grid(row=0, column=3, sticky=W) self.log_in_out_button.grid(row=0, column=4, sticky=E) self.topFrame.grid_columnconfigure(5, weight=1) self.balanceLabel.grid(row=0, column=5, sticky=E) self.balance.grid(row=0, column=6, sticky=W) self.close_button.grid(row=0, column=7, sticky=E, padx=(50, 0)) # Middle Frame Form Layout self.middleFrame.grid_rowconfigure(0, weight=1) self.gameTypeCmb.grid(row=0, column=0, columnspan=1, sticky=W + E) self.gameStyleLabel.grid(row=1, column=0, columnspan=1, sticky=W + E) self.spacerLabel.grid(row=1, column=2, sticky=E) self.opponentLabel.grid(row=2, column=0, sticky=W, pady=4) self.specify_opponent_cmb.grid(row=2, column=0, sticky=E, pady=4) self.do_not_play_same_user_check.grid(row=3, column=0, columnspan=1, sticky='we', pady=4) self.game_styles_listbox.grid(row=4, column=0, columnspan=1, sticky='we', pady=4) self.find_game_button.grid(row=5, column=0, pady=4, sticky=W) self.refresh_game_styles_button.grid(row=5, column=0, columnspan=1, sticky='', pady=4) self.cancel_stop_game_button.grid(row=5, column=0, sticky=E) self.thinkingTimeLabel.grid(row=6, column=0, sticky=W, pady=4) self.thinking_time_entry.grid(row=6, column=0, sticky=E, pady=4) self.auto_play_next_game_check.grid(row=7, column=0, columnspan=1, sticky=W, pady=4) self.resultText.grid(row=9, column=0, columnspan=2, sticky=W, pady=4) self.middleFrame.grid_columnconfigure(9, weight=1) self.gameTitleLabel.grid(row=0, column=3) self.gameTitleText.grid(row=0, column=3, columnspan=2) self.gameActionLabel.grid(row=11, column=3, sticky='w') if args.botid is not None and args.password is not None: self.auto_play(args) def auto_play(self, args): self.bot_id_entry.insert(0, args.botid) self.bot_password_entry.insert(0, args.password) self.log_in_out_clicked() self.thinking_time_entry.insert(0, args.timeout) if args.playanothergame: self.auto_play_next_game_check.select() if args.dontplaysameuserbot: self.do_not_play_same_user_check.select() if args.closeaftergame: self.close_after_game = True if args.gamestyle is not None: i = 0 for i in range(self.game_styles_listbox.size()): if args.gamestyle in str(self.game_styles_listbox.get(i)): break self.game_styles_listbox.select_set(i, i) self.find_game_clicked() def log_in_out_clicked(self): """Click handler for the 'Login'/'Logout' button.""" # This means we're logging out if self.logged_in: self.resultText.config(text='Logged Out') self.master.title(self.config["APP_TITLE"] + " (Not Logged In)") self.cancel_game() self.bot_id = None self.bot_password = None self.clear_game_title_text() self.gameActionLabel.config(text="") self.reset_game_styles_listbox() self.clear_all_boards() self.opponent.delete("all") self.log_in_out_button.config(text='Login') self.set_login_controls_states(ENABLED) self.set_gamestyle_controls_states(DISABLED) self.gameTypeCmb.config(state="disabled") self.logged_in = False self.bot_password_entry.delete(0, 'end') self.set_balance(0) # This means we're logging in else: self.bot_id = self.bot_id_entry.get() self.bot_password = self.bot_password_entry.get() res = self.get_list_of_game_styles() if res['Result'] == 'SUCCESS': self.resultText.config(text='Logged In') game_styles = res['GameStyles'] self.master.title(self.bot_id + " - " + self.config["APP_TITLE"]) self.set_login_controls_states(DISABLED) self.set_gamestyle_controls_states(ENABLED) self.gameTypeCmb.config(state="readonly") self.set_game_styles_listbox(game_styles) self.set_balance(res['Balance']) self.log_in_out_button.config(text='Logout') self.logged_in = True else: messagebox.showerror( 'Error', 'Invalid login attempt. Please check the username and password entered.' ) def log_in_if_not(self, _): if not self.logged_in: self.log_in_out_clicked() def clear_all_boards(self): self.player.clear_board() self.opponent.clear_board() self.player.delete("all") self.opponent.delete("all") self.player.myBoard = None self.opponent.oppBoard = None def set_in_game(self, value): self.in_game = value def set_game_title_text(self, text, tag): self.gameTitleText.config(state=ENABLED) self.gameTitleText.insert("end", text, ("center", tag)) self.gameTitleText.config(state=DISABLED) def clear_game_title_text(self): self.gameTitleText.config(state=ENABLED) self.gameTitleText.delete("1.0", "end") self.gameTitleText.config(state=DISABLED) def set_login_controls_states(self, state): self.bot_id_entry.config(state=state) self.bot_password_entry.config(state=state) def set_gamestyle_controls_states(self, state): self.specify_opponent_cmb.config(state=state) self.do_not_play_same_user_check.config(state=state) self.game_styles_listbox.config(state=state) self.find_game_button.config(state=state) self.refresh_game_styles_button.config(state=state) self.auto_play_next_game_check.config(state=state) self.thinking_time_entry.config(state=state) self.opponentLabel.config(state=state) self.thinkingTimeLabel.config(state=state) self.balanceLabel.config(state=state) self.balance.config(state=state) self.gameStyleLabel.config(state=state) self.game_styles_listbox.config(state=state) self.player.config(state=state) self.opponent.config(state=state) def set_balance(self, balance): """Set the balance field""" self.balance['text'] = int_with_commas(balance) def get_list_of_game_styles(self): """Get list of game styles from the server.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'GameTypeId': self.game_type } url = self.config["BASE_URL"] + self.config[ "GET_LIST_OF_GAME_STYLES_EXTENSION"] return DemoClient.make_api_call(url, req) def set_game_styles_listbox(self, game_styles): """Set the content of the game styles listbox with a list of GameStyle dictionaries. Keyword Arguments: game_styles -- The list of GameStyle dictionaries, this should be obtained through get_list_of_game_styles(). """ self.reset_game_styles_listbox() for index, game_style in enumerate(game_styles): if self.game_type == self.config["BATTLESHIPS_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["BATTLESHIPS_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Ships'], game_style['GameTypeSpecificInfo']['Board Size'], game_style['GameTypeSpecificInfo']['Timeout ms'], game_style['GameTypeSpecificInfo']['DealsTotal'], game_style['GameTypeSpecificInfo']['PercentageLand'], game_style['GameTypeSpecificInfo']['RandomLand'])) elif self.game_type == self.config[ "NOUGHTS_AND_CROSSES_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["NOUGHTS_AND_CROSSES_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['DealsTotal'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config[ "TRAVELLING_SALESDRONE_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self. config["TRAVELLING_SALESDRONE_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['TotalCities'], game_style['GameTypeSpecificInfo']['DealLength'])) elif self.game_type == self.config["PREDICTIVE_TEXT_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self. config["PREDICTIVE_TEXT_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo'] ['Number of Sentences'], game_style['GameTypeSpecificInfo'] ['Switched Words Game'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["TWIST_CUBE_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["TWIST_CUBE_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['cubeSize'], game_style['GameTypeSpecificInfo']['GameLength'])) elif self.game_type == self.config["SLIDING_PUZZLE_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["SLIDING_PUZZLE_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['RowSize'], game_style['GameTypeSpecificInfo']['ColumnSize'], game_style['GameTypeSpecificInfo']['TimeLimit'])) elif self.game_type == self.config["BLURRY_WORD_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["BLURRY_WORD_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['NumImages'], game_style['GameTypeSpecificInfo']['GameLength'])) elif self.game_type == self.config["MASTERMIND_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["MASTERMIND_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['NumPegs'], game_style['GameTypeSpecificInfo']['NumColours'], game_style['GameTypeSpecificInfo'] ['DuplicatesAllowed'])) elif self.game_type == self.config[ "WAREHOUSE_LOGISTICS_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["WAREHOUSE_LOGISTICS_GAME_STYLE_LISTBOX_TEXT"]. format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo'] ['WarehouseDimensions'][0], game_style['GameTypeSpecificInfo'] ['WarehouseDimensions'][1])) elif self.game_type == self.config["FOUR_IN_A_ROW_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["FOUR_IN_A_ROW_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['Connections'])) elif self.game_type == self.config["WHO_IS_WHO_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["WHO_IS_WHO_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['NumCharacters'], game_style['GameTypeSpecificInfo']['ComparisonRound'])) elif self.game_type == self.config[ "REVERSING_STONES_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["REVERSING_STONES_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['Holes'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["CHECKERS_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["CHECKERS_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["GO_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["GO_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], "CAPTURE" if game_style['GameTypeSpecificInfo']['IsCaptureGo'] else game_style['GameTypeSpecificInfo']['ScoringMethod'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["LEXICO_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["LEXICO_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['TileMultipliers'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["DOMINOES_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["DOMINOES_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['SpotNo'], game_style['GameTypeSpecificInfo']['Timeout ms'])) else: raise ValueError('INVALID GAME TYPE PARAMETER') self.game_style_ids.append(game_style['GameStyleId']) # self.game_styles_listbox.select_set(GAME_STYLE_LISTBOX_DEFAULT_SELECTION) def reset_game_styles_listbox(self): """Clear the content of the game styles listbox.""" if self.game_styles_listbox.size() != 0: self.game_styles_listbox.delete(0, 'end') self.game_style_ids = [] def refresh_game_styles_clicked(self): """Click handler for the 'Refresh Game Styles' button.""" res = self.get_list_of_game_styles() game_styles = res['GameStyles'] self.set_game_styles_listbox(game_styles) def find_game_clicked(self): """Click handler for the 'Find Game' button""" self.find_game_button.config(state=DISABLED) self.cancel_stop_game_button.config(state=ENABLED) self.game_styles_listbox.unbind('<Double-1>') self.game_styles_listbox.unbind('<Return>') self.game_styles_listbox.config(state=DISABLED) self.clear_all_boards() # Here we dispatch the work to a separate thread, to keep the GUI responsive. if not MAC: threading.Thread(target=self.game_loop, daemon=True).start() else: self.game_loop() # Doesn't work on MACs def find_game_double_clicked(self, _): self.find_game_clicked() def game_type_selected(self, _): self.game_type = self.config["COMBOBOX_INDEX"][ self.gameTypeCmb.current()][1] res = self.get_list_of_game_styles() if res['Result'] == 'SUCCESS': game_styles = res['GameStyles'] self.set_game_styles_listbox(game_styles) self.get_icon() self.player.destroy() self.opponent.destroy() self.create_visuals() def get_icon(self): try: if WINDOWS: self.master.iconbitmap("assets/{0}/icon.ico".format( self.game_type)) else: self.master.iconbitmap("./assets/{0}/icon.xbm".format( self.game_type)) except Exception as e: print(e) def create_visuals(self): if self.game_type == self.config["NULL_GAME_TYPE_ID"]: self.player = null_visuals.NullVisuals( self.middleFrameRight) # Game Display Table self.opponent = null_visuals.NullVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["BATTLESHIPS_GAME_TYPE_ID"]: self.player = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.opponent = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["NOUGHTS_AND_CROSSES_GAME_TYPE_ID"]: self.player = noughts_and_crosses_visuals.NoughtsAndCrossesVisuals( self.middleFrameRight) # Game Display Table self.opponent = noughts_and_crosses_visuals.NoughtsAndCrossesVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config[ "TRAVELLING_SALESDRONE_GAME_TYPE_ID"]: self.player = travelling_salesdrone_visuals.TravellingSalesdroneVisuals( self.middleFrameRight) # Game Display Table self.opponent = travelling_salesdrone_visuals.TravellingSalesdroneVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["PREDICTIVE_TEXT_GAME_TYPE_ID"]: self.player = predictive_text_visuals.PredictiveTextVisuals( self.middleFrameRight) # Game Display Table self.opponent = predictive_text_visuals.PredictiveTextVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["TWIST_CUBE_GAME_TYPE_ID"]: self.player = twist_cube_visuals.TwistCubeVisuals( self.middleFrameRight) # Game Display Table self.opponent = twist_cube_visuals.TwistCubeVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["SLIDING_PUZZLE_GAME_TYPE_ID"]: self.player = sliding_puzzle_visuals.SlidingPuzzleVisuals( self.middleFrameRight) # Game Display Table self.opponent = sliding_puzzle_visuals.SlidingPuzzleVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["BLURRY_WORD_GAME_TYPE_ID"]: self.player = blurry_word_visuals.MicrosoftCognitiveChallengeVisuals( self.middleFrameRight) # Game Display Table self.opponent = blurry_word_visuals.MicrosoftCognitiveChallengeVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["MASTERMIND_GAME_TYPE_ID"]: self.player = mastermind_visuals.MastermindVisuals( self.middleFrameRight) # Game Display Table self.opponent = mastermind_visuals.MastermindVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["WAREHOUSE_LOGISTICS_GAME_TYPE_ID"]: self.player = warehouse_logistics_visuals.WarehouseLogisticsVisuals( self.middleFrameRight) # Game Display Table self.opponent = warehouse_logistics_visuals.WarehouseLogisticsVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["FOUR_IN_A_ROW_GAME_TYPE_ID"]: self.player = four_in_a_row_visuals.FourInARowVisuals( self.middleFrameRight) # Game Display Table self.opponent = four_in_a_row_visuals.FourInARowVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["WHO_IS_WHO_GAME_TYPE_ID"]: self.player = who_is_who_visuals.WhoIsWhoVisuals( self.middleFrameRight) # Game Display Table self.opponent = who_is_who_visuals.WhoIsWhoVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["REVERSING_STONES_GAME_TYPE_ID"]: self.player = reversing_stones_visuals.ReversingStonesVisuals( self.middleFrameRight) # Game Display Table self.opponent = reversing_stones_visuals.ReversingStonesVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["CHECKERS_GAME_TYPE_ID"]: self.player = checkers_visuals.CheckersVisuals( self.middleFrameRight) # Game Display Table self.opponent = checkers_visuals.CheckersVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["GO_GAME_TYPE_ID"]: self.player = go_visuals.GoVisuals( self.middleFrameRight) # Game Display Table self.opponent = go_visuals.GoVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["LEXICO_GAME_TYPE_ID"]: self.player = lexico_visuals.LexicoVisuals( self.middleFrameRight) # Game Display Table self.opponent = lexico_visuals.LexicoVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["DOMINOES_GAME_TYPE_ID"]: self.player = dominoes_visuals.DominoesVisuals( self.middleFrameRight) # Game Display Table self.opponent = dominoes_visuals.DominoesVisuals( self.middleFrameRight) # Game Display Table else: raise ValueError('INVALID GAME TYPE PARAMETER') self.player.grid(row=1, column=3) self.opponent.grid(row=1, column=4) def game_loop(self): """Loop through finding and playing games.""" while True: self.clear_all_boards() mover.persistentData = {} self.find_game() self.update_balance() if self.game_cancelled: break self.play_game() self.update_balance() if self.close_after_game: self.close_button.invoke() if self.game_cancelled: break if not self.play_again.get(): break self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind('<Return>', self.find_game_double_clicked) self.game_styles_listbox.config(state=ENABLED) self.game_cancelled = False def find_game(self): """Find a game.""" offer_game_res = self.offer_game() if offer_game_res['Result'] == 'INVALID_LOGIN_OR_PASSWORD': self.cancel_stop_game_clicked() if 'ErrorMessage' in offer_game_res and offer_game_res[ 'ErrorMessage'] == 'Check of OpponentId failed': self.resultText.config(text='Invalid Opponent ID') else: self.resultText.config(text='Invalid login or password') elif offer_game_res['Result'] == 'INSUFFICIENT_BALANCE': self.cancel_stop_game_clicked() self.resultText.config(text='Insufficient balance') elif offer_game_res['Result'] == 'BOT_IS_INACTIVE': self.cancel_stop_game_clicked() self.resultText.config(text='Bot is inactive') else: self.player_key = offer_game_res['PlayerKey'] if offer_game_res['Result'] == 'WAITING_FOR_GAME': self.wait_for_game() def offer_game(self): """Offer a game.""" self.cancel_game( ) # Cancel the last outstanding game offer that was made opponent_id = self.specify_opponent_cmb.get() if len(opponent_id) == 0: opponent_id = None try: game_style_id = self.game_style_ids[int( self.game_styles_listbox.curselection()[0])] except IndexError: self.game_styles_listbox.select_set( GAME_STYLE_LISTBOX_DEFAULT_SELECTION) game_style_id = self.game_style_ids[0] req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'GameStyleId': game_style_id, 'DontPlayAgainstSameUser': self.do_not_play_same_user.get(), 'DontPlayAgainstSameBot': False, 'OpponentId': opponent_id } url = self.config["BASE_URL"] + self.config["OFFER_GAME_EXTENSION"] return DemoClient.make_api_call(url, req) def wait_for_game(self): """Wait for game to start.""" self.resultText.config(text='Waiting for game') while True: if self.game_cancelled: self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind('<Return>', self.find_game_double_clicked) self.game_styles_listbox.config(state=ENABLED) break poll_results = self.poll_for_game_state() if poll_results['Result'] == 'SUCCESS': break if poll_results['Result'] == 'INVALID_PLAYER_KEY' or poll_results[ 'Result'] == 'GAME_HAS_ENDED' or poll_results[ 'Result'] == 'GAME_WAS_STOPPED': self.game_cancelled = True time.sleep(2) def play_game(self): """Play a game.""" self.resultText.config(text='Playing game') self.in_game = True poll_results = self.poll_for_game_state() if poll_results["Result"] != "SUCCESS": return game_state = poll_results['GameState'] title = format('Game ID: ' + str(game_state['GameId'])) title += format(' / Style: ' + str(self.game_style_ids[int( self.game_styles_listbox.curselection()[0])])) title += "\n" versus = format(self.bot_id + ' vs ' + game_state['OpponentId']) self.clear_game_title_text() self.set_game_title_text(title, "") self.set_game_title_text(versus, "bold") self.middleFrame.update() while True: if self.game_cancelled: break if game_state['IsMover']: self.resultText.config(text='Playing Game - Your Turn') move = mover.calculate_move(self.game_type, game_state) move_results = self.make_move(move) if move_results['Result'] == 'INVALID_MOVE': self.resultText.config(text="Invalid Move") elif move_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + move_results['Result']) print(str(move_results)) print("Game ended") break else: game_state = move_results['GameState'] else: self.resultText.config(text="Playing Game - Opponent's Turn") # ---- Code here will be called on your opponent's turn ---- # ---------------------------------------------------------- poll_results = self.poll_for_game_state() if poll_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + poll_results['Result']) break game_state = poll_results['GameState'] if game_state['GameStatus'] != 'RUNNING': break self.middleFrameRight.update() try: if int(self.thinking_time_entry.get()) > 0: time.sleep((int(self.thinking_time_entry.get()) / 1000)) else: time.sleep(0.1) except ValueError: time.sleep(0.1) self.set_in_game(False) def make_move(self, move): """Make a move.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key, 'Move': move } url = self.config["BASE_URL"] + self.config["MAKE_MOVE_EXTENSION"] result = DemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: print(result) try: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) except Exception as e: print("Gamestate error: " + str(e)) return result def poll_for_game_state(self): """Poll the server for the latest GameState.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'PlayerKey': self.player_key } url = self.config["BASE_URL"] + self.config[ "POLL_FOR_GAME_STATE_EXTENSION"] result = DemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) return result def cancel_stop_game_clicked(self): self.game_cancelled = True self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind('<Return>', self.find_game_double_clicked) self.game_styles_listbox.config(state=ENABLED) def cancel_game(self): print("Cancelling last game offer") if self.player_key is None: return req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key } url = self.config["BASE_URL"] + self.config[ "CANCEL_GAME_OFFER_EXTENSION"] DemoClient.make_api_call(url, req) try: self.resultText.config(text='Cancelled game') except Exception as e: print(str(e) + " -- Demo client has been closed") def update_balance(self): res = self.get_list_of_game_styles() self.set_balance(res['Balance']) @staticmethod def make_api_call(url, req): """Make an API call.""" while True: try: res = requests.post(url, json=req, headers=API_CALL_HEADERS, timeout=60.0) try: jres = res.json() if 'Result' in jres: return jres time.sleep(0.1) except ValueError: time.sleep(0.1) except requests.ConnectionError: time.sleep(0.1) except requests.Timeout: time.sleep(0.1) except requests.HTTPError: time.sleep(0.1) except BaseException as e: # Bad code but needed for testing purposes print(e) time.sleep(0.1)
class MultiChoicePrompt(Toplevel): """Class that creates a multiple choice prompt window for selecting leaves.""" def __init__(self, main_window, title, prompt, options, customise_option=False, text_placeholder="", **kwargs): """ Parameters ---------- main_window : Program Program object which is the main window title : str Title of prompt window prompt : str Prompt text in dialog window options : list[str] List of options that will be displayed in multiple choice prompt customise_option : bool Logic to add option that includes text widget where user can type (default is False) text_placeholder : str Grey placeholder text in text widget (default = "") """ super().__init__(**kwargs) self.title(title) self.customise_value = len(options) self.main = main_window self.text_placeholder = text_placeholder self.protocol("WM_DELETE_WINDOW", self._exit) prompt_frame = Frame(self) prompt_frame.pack(side="top") prompt_frame.bind("<ButtonRelease-1>", self._text_focus_off) prompt_message = Label(prompt_frame, text=prompt) prompt_message.pack(pady=(20, 10), padx=20) self.radio_frame = Frame(self) self.radio_frame.pack(anchor="c", fill="x", padx=50) self.radio_frame.bind("<ButtonRelease-1>", self._text_focus_off) self.v = IntVar() for i, option in enumerate(options): radio_button = Radiobutton(self.radio_frame, text=option, variable=self.v, value=i) radio_button.bind("<ButtonRelease-1>", self._text_focus_off) radio_button.pack(anchor="w", padx=20, pady=10) if customise_option: radio_button = Radiobutton(self.radio_frame, text="Customise", variable=self.v, value=self.customise_value) radio_button.pack(anchor="w", padx=20, pady=10) self.customise_text = TextWithPlaceholder(self.radio_frame, self.text_placeholder, height=2, width=40) self.customise_text.bind("<ButtonRelease-1>", self._text_on_click) self.customise_text.pack(anchor="w", padx=(40, 40), pady=(0, 20)) self.v.set(0) #Set default selected radio button self.error_message_frame = Frame(self) self.error_message_frame.pack(anchor="c", fill="x") ok_button = Button(self, text="OK", width=20, command=self._get_input_leaves) ok_button.pack(pady=(20, 20)) def _text_focus_off(self, *_): """Removes focus from the TextWithPlaceholder object.""" self.focus_set() def _text_on_click(self, *_): """Automatically selects the "Customise" radio button when user clicks on text field""" self.v.set(1) def _get_input_leaves(self): """Get the input leaves from the text field.""" self._clear_error_messages() if self.v.get() == 0: input_leaves = self.main.network.labelled_leaves else: input_leaves = self.customise_text.get("1.0", "end") try: if input_leaves == self.text_placeholder: raise InvalidLeaves self.main.network.set_current_selected_leaves(input_leaves) self.main.generate_trees_graph() self._exit() except InvalidLeaves as e: #Display error message error_message = Label(self.error_message_frame, text=e, fg="red") error_message.pack(pady=(10, 10), padx=20) def _clear_error_messages(self): """Clear any error messages in dialog""" for widget in self.error_message_frame.winfo_children(): widget.destroy() empty_frame = Frame(self.error_message_frame) empty_frame.pack() self.error_message_frame.update() def _exit(self): """Hide window""" self._clear_error_messages() self.withdraw()
class App(Frame): def __init__(self,parent): super().__init__(parent) self.parent = parent self.squares = [] self.initUI() def initUI(self): # Tạo tiêu đề cho cửa sổ self.parent.title("Sudoku problem") # Cấu hình layout cho cửa sổ này. Trong đó tham số: # side = left : cho biết layout sẽ căn chỉnh cố định với cạnh trái # fill = both : kích thước của layout sẽ đổ đầy 2 bên # expand = True : cho phép cửa sổ mở rộng self.pack(side = "left", fill ="both", expand = True) # Tạo menu cho cửa sổ menuBar = Menu(self) self.parent.config(menu = menuBar) fileMenu = Menu(menuBar) fileMenu.add_command(label = "Import Sudoku", command = self.importSudoku) menuBar.add_cascade(label = "File",menu = fileMenu) # Tạo một frame, frame này sẽ chứa 81 ô. Trong đó: # self: cho biết widget sẽ chứa nó # width: cho biết chiều rộng của frame # height: cho biết chiều cao của frame self.map = Frame(self,width = 600, height = 600) self.map.pack(side = "left", fill="both",expand = True) # Lấy ra thông tin chiều dài và rộng tính theo pixel của map self.map.update() self.x = int(self.map.winfo_width() - 10) self.y = int(self.map.winfo_height() - 10) # Tạo frame thứ 2, frame này chứa button sử dụng để tìm lời giải và chứa label # hiển thị thời gian tìm lời giải self.frameWidget = Frame(self, width = 200) self.frameWidget.pack(side = "left", fill = "both",expand = True) # Tạo button để chạy tìm lời giải # Tham số command = self.resolvingUsingAc3 để tạo sự kiện khi nhấn button self.btnAc3 = Button(self.frameWidget, text = "AC3 algorithm", command = self.resolvingUsingAc3) # Tham số pady = 50 để label cách trục y 25px self.btnAc3.pack(pady = 50) self.btnBks = Button(self.frameWidget, text = "Backtrack algorithm", command = self.resolvingUsingBacktrack) self.btnBks.pack(pady = 50) # Tạo label hiển thị thời gian tìm lời giải self.lbTime = Label(self.frameWidget,text = "0.0s") self.lbTime.pack(pady = 25) '''Hàm lấy dữ liệu từ file txt''' def importSudoku(self): # List lưu các định dạng file khác nhau để đọc ftypes = [('All files','*')] # Hiển thị hộp thoại chọn đường dẫn file dialog = Open(self,filetypes = ftypes) path = dialog.show() # Đọc file intput_ = "" with open(path,"r") as ins: for line in ins: intput_ += line self.input = intput_ self.createSquares(9) self.setNumbers(9,intput_) ''' Hàm gọi thuật toán AC3 algorithm để tìm lời giải, sau đó nó sẽ đặt các con số lên map ''' def resolvingUsingAc3(self): # Khi thuật toán bắt đầu chạy, ta sẽ khóa button này lại tránh trường hợp click nhiều # lần từ người dùng self.btnAc3['state'] = 'disabled' self.btnBks['state'] = 'disabled' solution, ti = ac3.getResults(self.input) self.createSquares(9) self.setNumbers(9,solution) self.lbTime.config(text = str(ti)+"s") # Thuật toán chạy xong, các số đã được đặt ta mở khóa lại button self.btnAc3['state'] = 'active' self.btnBks['state'] = 'active' ''' Hàm gọi thuật toán Backtrack algorithm để tìm lời giải, sau đó nó sẽ đặt các con số lên map ''' def resolvingUsingBacktrack(self): # Khi thuật toán bắt đầu chạy, ta sẽ khóa button này lại tránh trường hợp click nhiều # lần từ người dùng self.btnAc3['state'] = 'disabled' self.btnBks['state'] = 'disabled' solution, ti = bks.getResults(self.input) self.createSquares(9) self.setNumbers(9,solution) self.lbTime.config(text = str(ti)+"s") # Thuật toán chạy xong, các số đã được đặt ta mở khóa lại button self.btnAc3['state'] = 'active' self.btnBks['state'] = 'active' '''Hàm tạo 81 ô trên map''' def createSquares(self, numOfSquares): for widget in self.map.winfo_children(): widget.destroy() self.map.update() self.squares.clear() # Lấy chiều rộng và chiều dài của 1 ô theo pixel w = int(self.x/numOfSquares) h = int(self.y/numOfSquares) # Cấu hình cột, hàng cho map for k in range(numOfSquares): self.map.columnconfigure(k,pad = 1) self.map.rowconfigure(k,pad = 1) # Tạo các label, mỗi ô trên map sẽ chứa một label, dùng để hiển thị số for i in range(numOfSquares): self.squares.append([]) for j in range(numOfSquares): # Tạo một ảnh pixel, để khi ta set width và height cho label thì nó sẽ lấy # kích thước theo pixel chứ không phải mm pixelVirtual = PhotoImage(width = 1, height = 1) lb = Label(self.map, text = 0, image = pixelVirtual, compound = 'center', borderwidth = 1, relief = "groove",width = w, height = h, bg = "white") lb.config(font =("Courier", 35)) lb.grid(row = i, column = j) self.squares[i].append(lb) '''Hàm đặt các con số lên map dựa vào solution tìm được''' def setNumbers(self,numOfSquares,solution): for i in range(numOfSquares): for j in range(numOfSquares): lb = self.squares[i][j] pixelVirtual = PhotoImage(width = 1, height = 1) lb.config(image = pixelVirtual, text = str(solution[i*numOfSquares+j]))
def main(): root = Tk() root.columnconfigure(0, weight=1) root.rowconfigure(0, weight=1) root.geometry('900x600+50+50') root.title('Imagepreview Test') window = Frame(root) window.grid(column=0, row=0, sticky='news') window.columnconfigure(0, weight=1) window.rowconfigure(0, weight=0) window.rowconfigure(1, weight=1) topWidget = Label(window, text='Image Preview', font=('Arial', '32')) topWidget.grid(column=0, row=0, sticky='we') topWidget.columnconfigure(0, weight=1) topWidget.rowconfigure(0, weight=1) '''************ImagePreview************''' previewFrame = Frame(window) previewFrame.grid(column=0, row=1, sticky='news') previewFrame.columnconfigure(0, weight=1) previewFrame.rowconfigure(0, weight=1) try: testImage = Image.open('test.jpg') except: testImage = Image.new('RGB', (100, 100), color='#999999') preview = Imagepreview.Imagepreview(previewFrame, testImage, zoomscale=1.2, minzoomlevel=0.1, maxzoomlevel=20.0, quality=0, backgroundcolor='#999999') preview.grid(column=0, row=0, sticky='news') '''************************************''' buttonColor = 'gray80' controlFrame = Frame(window) controlFrame.grid(column=1, row=0, rowspan=3, padx=3) previewFrame.rowconfigure(2, weight=0) def update_label(event=None): infoLabel.config( anchor='w', text= 'Scale:\t\tx{}\n\nWidth:\t\t{}\nHeight:\t\t{}\n\nScale width:\t{}\nScale height:\t{}' .format(round(preview.canvasScale, 2), testImage.width, testImage.height, preview.resizedImage.width, preview.resizedImage.height)) def reset_button(event=None): preview.reset_preview() update_label() def original_button(event=None): preview.original_zoom() update_label() resetButton = Button(controlFrame, text='Reset Preview (Ctrl+R)', command=reset_button, bg=buttonColor) resetButton.grid(column=0, row=0, sticky='we') originalButton = Button(controlFrame, text='x1.0 zoom (Num 1)', command=original_button, bg=buttonColor) originalButton.grid(column=0, row=1, sticky='we') seperatorOne = Separator(controlFrame) seperatorOne.grid(column=0, row=2, sticky='we', pady=10) infoLabel = Label(controlFrame, anchor='w') infoLabel.grid(column=0, row=3, sticky='s') infoLabel.config( text= 'Scale:\t\tx{}\n\nWidth:\t\t{}\nHeight:\t\t{}\n\nScale width:\t{}\nScale height:\t{}' .format(round(preview.canvasScale, 2), testImage.width, testImage.height, preview.resizedImage.width, preview.resizedImage.height)) if os.name == 'nt': root.bind('<MouseWheel>', update_label) elif os.name == 'posix': root.bind('<Button-4>', update_label) root.bind('<Button-5>', update_label) # root.bind('<MouseWheel>', update_label) root.bind('1', original_button) root.bind('<Control-r>', reset_button) def update_quality(x): for child in qualityFrame.winfo_children(): try: child.configure(bg='white', fg='black') except: pass if x == 0: qualityZero.configure(bg='gray10', fg='white') elif x == 1: qualityOne.configure(bg='gray10', fg='white') elif x == 2: qualityTwo.configure(bg='gray10', fg='white') elif x == 3: qualityThree.configure(bg='gray10', fg='white') elif x == 4: qualityFour.configure(bg='gray10', fg='white') preview.resizeQuality = x preview.scaleChanged = True preview.display_image(image=preview.previewImage, quality=x) seperatorTwo = Separator(controlFrame) seperatorTwo.grid(column=0, row=4, sticky='we', pady=10) qualityFrame = Frame(controlFrame) qualityFrame.grid(column=0, row=5, sticky='we', padx=30) qualityFrame.columnconfigure(0, weight=1) qualityLabel = Label(qualityFrame, text='Resize Filter', font=('Arial', '10', 'bold')) qualityLabel.grid(column=0, row=0, sticky='we', pady=5) qualityZero = Button(qualityFrame, text='0 (NEAREST)', anchor='w', command=lambda: update_quality(0)) qualityZero.grid(column=0, row=1, sticky='we') qualityOne = Button(qualityFrame, text='1 (BILINEAR)', anchor='w', command=lambda: update_quality(1)) qualityOne.grid(column=0, row=2, sticky='we') qualityTwo = Button(qualityFrame, text='2 (HAMMING)', anchor='w', command=lambda: update_quality(2)) qualityTwo.grid(column=0, row=3, sticky='we') qualityThree = Button(qualityFrame, text='3 (BICUBIC)', anchor='w', command=lambda: update_quality(3)) qualityThree.grid(column=0, row=4, sticky='we') qualityFour = Button(qualityFrame, text='4 (LANCZOS)', anchor='w', command=lambda: update_quality(4)) qualityFour.grid(column=0, row=5, sticky='we') update_quality(0) seperatorThree = Separator(controlFrame) seperatorThree.grid(column=0, row=6, sticky='we', pady=10) def load_image(): try: filetypes = [('JPEG', '*.jpg *.jpeg'), ('PNG', '*.png'), ("all files", "*.*")] testImage = Image.open( askopenfilename(title='Load Image...', defaultextension='.', filetypes=filetypes)) preview.update_image(image=testImage) except AttributeError: pass loadButton = Button(controlFrame, text='Load Image', font=('Arial', '18'), command=load_image, bg=buttonColor) loadButton.grid(column=0, row=7, sticky='we') window.update() root.minsize(root.winfo_width(), root.winfo_height()) preview.reset_preview() window.mainloop()
class GameGrid(Frame): def __init__(self): # Frame.__init__(self) self.score = 0 self.game = Frame() self.game.grid() self.game.master.title('2048') # self.master.bind("<Key>", self.key_down) # self.gamelogic = gamelogic self.game.commands = { c.KEY_UP: logic.up, c.KEY_DOWN: logic.down, c.KEY_LEFT: logic.left, c.KEY_RIGHT: logic.right, c.KEY_UP_ALT: logic.up, c.KEY_DOWN_ALT: logic.down, c.KEY_LEFT_ALT: logic.left, c.KEY_RIGHT_ALT: logic.right, c.KEY_H: logic.left, c.KEY_L: logic.right, c.KEY_K: logic.up, c.KEY_J: logic.down } self.game.grid_cells = [] self.init_grid(self.game) self.init_matrix() self.update_grid_cells(self.game) def render(self): self.game.update_idletasks() self.game.update() time.sleep(0.01) time.sleep(0.01) def init_grid(self, game): background = Frame(game, bg=c.BACKGROUND_COLOR_GAME, width=c.SIZE, height=c.SIZE) background.grid() for i in range(c.GRID_LEN): grid_row = [] for j in range(c.GRID_LEN): cell = Frame(background, bg=c.BACKGROUND_COLOR_CELL_EMPTY, width=c.SIZE / c.GRID_LEN, height=c.SIZE / c.GRID_LEN) cell.grid(row=i, column=j, padx=c.GRID_PADDING, pady=c.GRID_PADDING) t = Label(master=cell, text="", bg=c.BACKGROUND_COLOR_CELL_EMPTY, justify=CENTER, font=c.FONT, width=5, height=2) t.grid() grid_row.append(t) game.grid_cells.append(grid_row) def gen(self): return random.randint(0, c.GRID_LEN - 1) def init_matrix(self): self.matrix = logic.new_game(c.GRID_LEN) self.history_matrixs = list() self.matrix = logic.add_two(self.matrix) self.matrix = logic.add_two(self.matrix) def update_grid_cells(self, game): for i in range(c.GRID_LEN): for j in range(c.GRID_LEN): new_number = self.matrix[i][j] if new_number == 0: game.grid_cells[i][j].configure( text="", bg=c.BACKGROUND_COLOR_CELL_EMPTY) else: game.grid_cells[i][j].configure( text=str(new_number), bg=c.BACKGROUND_COLOR_DICT[new_number], fg=c.CELL_COLOR_DICT[new_number]) game.update_idletasks() def num_actions_available(self): return 4 def get_state(self): flat = np.array(self.matrix).flatten().astype(np.float32()) return torch.from_numpy(flat) def key_down(self, event): key = event game_done = False game_result = False temp = 0 current_state = self.matrix if key == c.KEY_BACK and len(self.history_matrixs) > 1: self.matrix = self.history_matrixs.pop() self.update_grid_cells() print('back on step total step:', len(self.history_matrixs)) elif key in self.game.commands: self.matrix, done = self.game.commands[key](self.matrix) if done: self.matrix = logic.add_two(self.matrix) # record last move self.history_matrixs.append(self.matrix) self.update_grid_cells(self.game) done = False if logic.game_state(self.matrix) == 'win': game_done = True game_result = True self.game.grid_cells[1][1].configure( text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY) self.game.grid_cells[1][2].configure( text="Win!", bg=c.BACKGROUND_COLOR_CELL_EMPTY) if logic.game_state(self.matrix) == 'lose': game_done = True game_result = False self.game.grid_cells[1][1].configure( text="You", bg=c.BACKGROUND_COLOR_CELL_EMPTY) self.game.grid_cells[1][2].configure( text="Lose!", bg=c.BACKGROUND_COLOR_CELL_EMPTY) if (game_done and game_result): self.score = sum(np.array(self.matrix).flatten()) elif (game_done and not (game_result)): self.score = -1 * sum(np.array(self.matrix).flatten()) else: if (self.score != sum(np.array(self.matrix).flatten())): for i in range(4): for j in range(4): if (self.matrix[i][j] == 2 * current_state[i][j]): temp += self.matrix[i][j] self.score = sum(np.array(self.matrix).flatten()) return self.matrix, game_done, temp else: # print(0) return self.matrix, game_done, -100 return self.matrix, game_done, self.score def generate_next(self): index = (self.gen(), self.gen()) while self.matrix[index[0]][index[1]] != 0: index = (self.gen(), self.gen()) self.matrix[index[0]][index[1]] = 2
def layout(self): self.background_label = Label(self.login_window, image=self.photos_img) self.background_label.place(x=0, y=0, relwidth=1, relheight=1) f = Frame(self.login_window, width=100, height=100) main_row = 0 configLabel = Label(f, text="Välj rally").grid(row=main_row, column=0) current_index = 0 titles = [] for config in self.config_finder.rally_configs: if config == self.current_login_configuration: current_index = len(titles) titles.append(config.title) self.configuration_combobox = Combobox(f, values=self.config_finder.get_all_titles()) self.configuration_combobox.current(current_index) self.configuration_combobox.bind("<<ComboboxSelected>>", self.on_rally_cb_changed) self.configuration_combobox.grid(row=main_row, column=1) main_row += 1 difficultyLabel = Label(f, text="Välj svårighetsgrad").grid(row=main_row, column=0) self.difficulty_combobox = Combobox(f, values=self.current_login_configuration.get_difficulties()) self.difficulty_combobox.current(0) #self.configuration_combobox.bind("<<ComboboxSelected>>", self.on_rally_cb_changed) self.difficulty_combobox.grid(row=main_row, column=1) main_row += 1 serverLabel = Label(f, text="Server address").grid(row=main_row, column=0) self.server_sv = StringVar() self.server_sv.set("") self.serverEntry = Entry(f, textvariable=self.server_sv) self.serverEntry.grid(row=main_row, column=1) main_row += 1 teamnameLabel = Label(f, text="Team Login Name").grid(row=main_row, column=0) self.teamname_sv = StringVar() self.teamname_sv.set("") self.teamnameEntry = Entry(f, textvariable=self.teamname_sv) self.teamnameEntry.grid(row=main_row, column=1) main_row += 1 passwordLabel = Label(f, text="Password").grid(row=main_row, column=0) self.password_sv = StringVar() self.password_sv.set("") self.passwordEntry = Entry(f, textvariable=self.password_sv) self.passwordEntry.grid(row=main_row, column=1) main_row += 1 usernameLabel = Label(f, text="User Name").grid(row=main_row, column=0) self.username_sv = StringVar() self.username_sv.set("") self.usernameEntry = Entry(f, textvariable=self.username_sv) self.usernameEntry.grid(row=main_row, column=1) main_row += 1 self.loginButton = Button(f, text="Login", command=self.validateLoginFunction) self.loginButton.grid(row=main_row, column=1) self.entries = [self.configuration_combobox, self.serverEntry, self.teamnameEntry, self.passwordEntry, self.usernameEntry, self.loginButton, self.difficulty_combobox] f.pack() f.update() self.login_frame = f self.update_layout() self.update_login_information()
class Window: def __init__(self) -> None: self.root = Tk() self.root.geometry("300x370+0+0") # self.root.resizable(True, True) self.root.eval("tk::PlaceWindow . center") self.root.title("Чеботарёв Степан ПКС-405") self.root.iconphoto(False, PhotoImage(file=config_get("icon_path"))) self.Frame = None self.database_manager = DatabaseManager() # ? Fonts self.font_color = "#37474F" self.font_color_complementary = "#78909C" self.font_color_accent = "#FF9C1A" self.font_captcha = ("Curlz MT", 24) self.font_20 = ( "Arial", 20, ) self.font_24 = ( "Arial", 24, ) self.font_28 = ( "Arial", 28, ) def MainPage(self): self.root.geometry("1600x600+0+0") self.root.title("My Best Program") self.root.eval("tk::PlaceWindow . center") self.Frame = Frame(self.root, bg="white") self.Frame.place(x=0, y=0) self.Treeview = Table( self.Frame, headings=( "Артикул", "Наименование", "Единица изменения", "Количество", "Поставщик", "Тип", "Цена", "Вес", ), rows=(self.database_manager.get_all_fittings()), ) self.Treeview.pack(expand=tk.YES, fill=tk.BOTH) def LoginPage(self) -> None: if type(self.Frame) is Frame: self.Frame.destroy() self.Frame = Frame(self.root, width=300, height=400) self.Frame.grid(row=0, column=0, sticky="NW") self.Frame.grid_propagate(0) self.Frame.update() self.root.title("Авторизация") label = Label(self.Frame, text="Login here", font=self.font_24, fg=self.font_color) label.place( x=self.Frame.winfo_width() / 2, y=self.Frame.winfo_height() / 2 - 150, anchor="center", ) username_label = Label(self.Frame, text="Username", font=self.font_24, fg=self.font_color) username_label.place( x=self.Frame.winfo_width() / 2 - 70, y=self.Frame.winfo_height() / 2 - 100, anchor="center", ) password_label = Label(self.Frame, text="Password", font=self.font_24, fg=self.font_color) password_label.place( x=self.Frame.winfo_width() / 2 - 70, y=self.Frame.winfo_height() / 2 - 30, anchor="center", ) self.captcha_answer = get_captcha() self.captcha_label = Label( self.Frame, text=self.captcha_answer, font=self.font_captcha, fg=self.font_color_complementary, ) self.captcha_label.place( x=self.Frame.winfo_width() / 2 - 80, y=self.Frame.winfo_height() / 2 + 40, anchor="center", ) self.username = Entry(self.Frame, font=self.font_20, fg=self.font_color, width=20) self.password = Entry(self.Frame, font=self.font_20, fg=self.font_color, show="*", width=20) self.username.place( x=self.Frame.winfo_width() / 2, y=self.Frame.winfo_height() / 2 - 70, anchor="center", ) self.password.place( x=self.Frame.winfo_width() / 2, y=self.Frame.winfo_height() / 2, anchor="center", ) self.captcha = Entry(self.Frame, font=self.font_20, fg=self.font_color, width=20) self.captcha.place( x=self.Frame.winfo_width() / 2, y=self.Frame.winfo_height() / 2 + 70, anchor="center", ) sign_in_button = Button( self.Frame, text="Sign In", font=self.font_20, width=9, fg="green", command=self.sign_in, ) sign_up_button = Button( self.Frame, text="Sign Up", font=self.font_20, width=9, fg="blue", command=self.sign_up, ) sign_in_button.place( x=self.Frame.winfo_width() / 2 - 70, y=self.Frame.winfo_height() / 2 + 120, anchor="center", ) sign_up_button.place( x=self.Frame.winfo_width() / 2 + 69, y=self.Frame.winfo_height() / 2 + 120, anchor="center", ) return def update_captcha(self) -> None: self.captcha_answer = get_captcha() self.captcha_label.destroy() self.captcha_label = Label( self.Frame, text=self.captcha_answer, font=self.font_captcha, fg=self.font_color_complementary, ) self.captcha_label.place( x=self.Frame.winfo_width() / 2 - 80, y=self.Frame.winfo_height() / 2 + 40, anchor="center", ) def sign_in(self) -> None: captcha = self.captcha.get() if not captcha or captcha.strip() != self.captcha_answer: self.update_captcha() messagebox.showerror("Регистрация", "Ошибка в капче!", icon="warning") return login, password = self.username.get(), self.password.get() is_sign_in = self.database_manager.sign_in(login, md5(password)) if is_sign_in: # * Очистка фрейма, мусорных атрибутов self.Frame.destroy() del self.Frame del self.username del self.password del self.captcha # * Инициализация основной страницы self.MainPage() return True self.update_captcha() messagebox.showerror("Авторизация", "Логин и/или пароль неверны!", icon="warning") return False def sign_up(self) -> None: from re import compile captcha = self.captcha.get() if not captcha or captcha.strip() != self.captcha_answer: self.update_captcha() messagebox.showerror("Регистрация", "Ошибка в капче!", icon="warning") return login, password = self.username.get(), self.password.get() password_len = len(password) if password_len < 6: messagebox.showerror( "Регистрация", "В пароле должно быть не менее 6 символов!", icon="warning", ) return elif password_len > 18: messagebox.showerror( "Регистрация", "В пароле должно быть не более 18 символов!", icon="warning", ) return symbol_in = False number_in = False low_in = False up_in = False stack = [] not3_in = True numbers = list(map(str, (range(10)))) for symbol in password: if symbol in ["*", "&", "{", "}", "|", ".", "+"]: symbol_in = True if symbol in numbers: number_in = True if symbol in ascii_lowercase: low_in = True if symbol in ascii_uppercase: low_in = True if not3_in: if not stack: stack = [symbol] elif symbol == stack[0]: if len(stack) == 2: not3_in = False symbol.append(symbol) else: stack = [symbol] if not low_in: self.update_captcha() messagebox.showerror( "Регистрация", "Вы забыли указать буквы нижнего регистра!", icon="warning", ) return if not up_in: self.update_captcha() messagebox.showerror("Регистрация", "Вы забыли указать заглавные буквы!", icon="warning") return if not symbol_in: self.update_captcha() messagebox.showerror("Регистрация", "Вы забыли указать символ!", icon="warning") return if not number_in: self.update_captcha() messagebox.showerror("Регистрация", "Вы забыли указать число!", icon="warning") return result = self.database_manager.sign_up(login, md5(password)) if not result: self.update_captcha() messagebox.showerror("Регистрация", "Ошибка регистрации!", icon="warning") return messagebox.showinfo("Регистрация", "Пользователь успешно зарегистрирован!") def Run(self) -> None: self.LoginPage() return self.root.mainloop()
def main(token): ''' Main event loop, draw the image and text to tkinter window ''' root = Tk() root.configure(bg="black", cursor="none") root.attributes('-fullscreen', True) f = Frame(root, bg="black", width=MONITOR_WIDTH, height=MONITOR_HEIGHT) f.grid(row=0, column=0, sticky="NW") f.grid_propagate(0) f.update() most_recent_song = "" while True: redraw = True time.sleep(5) current_song = get_current_playing(token) if current_song["album"] != most_recent_song: redraw = True else: redraw = False if redraw: artist = current_song["artist"] name = current_song["name"] album = current_song["album"] most_recent_song = album hd_img = itunes_search(current_song["album"], current_song["artist"]) if hd_img != None: pi = convert_image(hd_img) itunes_cover = "iTunes Cover" else: pi = convert_image(current_song["img_src"]) itunes_cover = "" img_x = MONITOR_WIDTH / 2 img_y = MONITOR_HEIGHT / 2 label = Label(f, image=pi, highlightthickness=0, bd=0) label.place(x=img_x, y=img_y, anchor="center") artist_label = Label(f, text=artist, bg="black", fg="white", font=("Courier New", 10)) artist_x = MONITOR_WIDTH - (MONITOR_WIDTH / 5) artist_y = (MONITOR_HEIGHT / 2) - 50 artist_label.place(x=artist_x, y=artist_y, anchor="center") song_label = Label( f, text=name + "\n \n " + album + "\n \n " + itunes_cover, bg="black", fg="white", font=("Courier New", 10), ) song_x = MONITOR_WIDTH - (MONITOR_WIDTH / 5) song_y = (MONITOR_HEIGHT / 2) + 50 song_label.place(x=song_x, y=song_y, anchor="center") root.update() label.destroy() artist_label.destroy() song_label.destroy()
class StringInputPrompt(Toplevel): """Class for prompt dialog that asks for string input""" def __init__(self, main_window, title, prompt, placeholder="", operation="Network", **kwargs): """ Parameters ---------- main_window : Program Program object which is the main window title : str Title of prompt window prompt : str Prompt text in dialog window placeholder : str Grey placeholder text in text widget (default = "") network : bool True if input prompt is for processing network manually entered by user, else for processing multiple trees manually entered by user (default is True) """ super().__init__(**kwargs) self.main = main_window self.title(title) self.placeholder = placeholder self.protocol("WM_DELETE_WINDOW", self._exit) #self.is_network = network self.operation = operation prompt_frame = Frame(self) prompt_frame.pack(side="top") self.prompt_message = Label(prompt_frame, text=prompt) self.prompt_message.pack(pady=(20, 10), padx=20) self.text_entry_frame = Frame(self) self.text_entry = TextWithPlaceholder(self.text_entry_frame, self.placeholder, height=6, width=40) self.text_entry.pack(anchor="c", expand=True, fill="both") self.text_entry_frame.pack(padx=(20), pady=(0, 20), expand=True, fill="both") self.error_message_frame = Frame(self) self.error_message_frame.pack(anchor="c", pady=(0, 20)) self.buttons_frame = Frame(self) self.buttons_frame.pack(side="bottom", anchor="c", pady=(10, 20)) ok_button = Button(self.buttons_frame, text="OK", width=20, command=self._get_input) cancel_button = Button(self.buttons_frame, text="Cancel", width=20, command=self._exit) ok_button.pack(side="left", padx=(20, 10)) cancel_button.pack(side="right", padx=(10, 20)) def change_contents(self, title, prompt, placeholder=""): """ Change title, prompt and placeholder text of this dialog Parameters ---------- title : str Title of prompt window prompt : str Prompt text in dialog window placeholder : str Grey placeholder text in text widget (default = "") """ self.title(title) self.prompt_message.configure(text=prompt) self.text_entry.put_placeholder(placeholder) self.placeholder = placeholder def _get_input(self): """Get network/trees entered""" self._clear_error_messages() input_text = self.text_entry.get("1.0", "end").strip() try: if input_text == self.placeholder: raise MalformedNewickException if self.operation == "Network": self.main.generate_network(input_text) elif self.operation == "Calculate drSPR": self.main.get_drspr(input_text) else: self.main.get_rspr_graph(input_text) self._exit() except MalformedNewickException: if not input_text or input_text == self.placeholder: if self.operation == "Network": error_text = "Please enter network" else: error_text = "Please enter at least 2 trees" Label(self.error_message_frame, text=error_text, fg="red").pack(anchor="c") return #Check the input if input_text[-1] != ";": Label(self.error_message_frame, text="String not terminated by semicolon", fg="red").pack(anchor="c") #Count brackets opening_brackets = 0 closing_brackets = 0 for character in input_text: if character == "(": opening_brackets += 1 elif character == ")": closing_brackets += 1 if opening_brackets > closing_brackets: Label( self.error_message_frame, text= f"Missing {opening_brackets - closing_brackets} closing bracket(s)", fg="red").pack(anchor="c") elif closing_brackets > opening_brackets: Label( self.error_message_frame, text= f"Missing {closing_brackets - opening_brackets} closing bracket(s)", fg="red").pack(anchor="c") elif opening_brackets == 0 or closing_brackets == 0: Label(self.error_message_frame, text="Missing brackets", fg="red").pack(anchor="c") except InvalidLeaves: #No labelled leaves in the input Label(self.error_message_frame, text="Must have at least one labelled leaf", fg="red").pack(anchor="c") def _clear_error_messages(self): """Clear any error messages in dialog""" for widget in self.error_message_frame.winfo_children(): widget.destroy() empty_frame = Frame(self.error_message_frame) empty_frame.pack() self.error_message_frame.update() def _exit(self): """Hide window""" self._clear_error_messages() self.withdraw()
class WiFiCrack(object): def __init__(self): self.win = Tk() self.win.title(soft_tk_title) soft_tk_x = int((self.win.winfo_screenwidth() - soft_tkwidth) / 2) soft_tk_y = int((self.win.winfo_screenheight() - soft_tkheight) / 2) soft_tk_size = '{}x{}+{}+{}'.format(soft_tkwidth, soft_tkheight, soft_tk_x, soft_tk_y) self.win.geometry(soft_tk_size) self.e1_str = StringVar() self.l1_str = StringVar() self.cancel_flag = False self.canvas_posx = (5, 5) self.canvas_posy = (5, 24) self.ftop = Frame(self.win) self.ftop.pack(side='top') self.flef = Frame(self.win) self.flef.pack(side='left') self.frig = Frame(self.win) self.frig.pack(side='right') self.fbot = Frame(self.win) self.fbot.pack(side='bottom') tree_columns = ('order', 'wifi_name', 'signal_strength') self.tree = ttk.Treeview(self.flef, show='headings', columns=tree_columns) self.tree.column('order', width=50) self.tree.column('wifi_name', width=150) self.tree.column('signal_strength', width=80) self.tree.heading('order', text='序号') self.tree.heading('wifi_name', text='WiFi名称') self.tree.heading('signal_strength', text='信号强度') self.tree.pack() self.but0 = Button(self.frig, text='显示WIFI', command=self.check_wifi_module) self.but1 = Button(self.frig, text='点击获取', command=self.get_password) self.but2 = Button(self.frig, text='取消获取', command=self.cancel_get_password) self.but3 = Button(self.frig, text='退出', command=self.win.quit) self.but0.pack() self.but1.pack() self.but2.pack() self.but3.pack() self.lb2 = Label(self.ftop, text='密码:') self.lb2.grid(row=0, column=0) self.ent1 = Entry(self.ftop, textvariable=self.e1_str) self.ent1.grid(row=0, column=1) self.cv1 = Canvas(self.ftop, width=150, height=24, bg='white') self.cv1.grid(row=1, column=0) self.lb1 = Label(self.ftop, textvariable=self.l1_str, width=5, height=1, bg='white') self.lb1.grid(row=1, column=1) def get_password(self): max_num = 600 # 填充进度条 self.out_rec = self.cv1.create_rectangle(self.canvas_posx[0], self.canvas_posx[1], self.canvas_posy[0] + 100, self.canvas_posy[1], outline="green", width=1) self.fill_rec = self.cv1.create_rectangle(self.canvas_posx[0], self.canvas_posx[1], self.canvas_posy[0], self.canvas_posy[1], outline="", width=0, fill="green") for i in range(max_num): time.sleep(0.1) self.change_schedule(i, max_num - 1) if self.cancel_flag: self.l1_str.set('') break #更新进度条函数 def change_schedule(self, now_schedule, all_schedule): self.cv1.coords( self.fill_rec, (self.canvas_posx[0], self.canvas_posx[1], self.canvas_posy[0] + 1 + (now_schedule / all_schedule) * 100, self.canvas_posy[1])) self.ftop.update() self.l1_str.set(str(round(now_schedule / all_schedule * 100, 2)) + '%') if round(now_schedule / all_schedule * 100, 2) == 100.00: self.l1_str.set("完成") def cancel_get_password(self): self.cv1.delete(self.out_rec) self.cv1.delete(self.fill_rec) self.l1_str.set('') self.cancel_flag = True def check_wifi_module(self): wifi_obj = pywifi.PyWiFi() wireless_lists = wifi_obj.interfaces() warn_title = '警告' warn_no_wifi_module_msg = '该电脑没有无线网卡模块!' warn_has_wifi_module_msg = '该电脑存在无线网卡模块,可以尝试获取密码!' if wireless_lists == []: messagebox.showwarning(warn_title, warn_no_wifi_module_msg) else: messagebox.showwarning(warn_title, warn_has_wifi_module_msg) def show(self): self.win.mainloop()
class App(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.tileList = [] self.currentNumOfQueens = None self.initUI() # Hàm này có nhiệm vụ khởi tạo các widget chứa bên trong App def initUI(self): # Cấu hình layout cho cửa sổ này # Tham số side = "left" cho biết layout sẽ cố định bên trái, fill = "both" thì kích thước của layout # sẽ lắp đầy 2 bên, expand = True cho phép mở rộng self.pack(side="left", fill="both", expand=True) # Tạo một frame, frame này sẽ chứa MAP đặt n Queens # Tham số self cho biết widget sẽ chứa nó, width là chiều rộng, height là chiều cao self.map = Frame(self, width=600, height=600) self.map.pack(side="left", fill="both", expand=True) # Lấy ra thông tin chiều dài và rộng tính theo pixel của MAP, ta trừ đi kích thước 20 # để cách đều ra 2 bên self.map.update() self.x = int(self.map.winfo_width() - 20) self.y = int(self.map.winfo_width() - 20) # Tạo frame thứ 2, frame này sẽ chưa textbox cho ta nhập số n queens, số lần lặp của thuật toán self.frameWidget = Frame(self, width=150) self.frameWidget.pack(side="left", fill="both", expand=True) self.lbNumOfQueens = Label(self.frameWidget, text="Num of Queens") # Tham số pady = 25, để label cách đều về 2 phía theo trục y 25 px self.lbNumOfQueens.pack(pady=25) # Tạo textbox để nhập số quân hậu cần đặt self.entryNumOfQueens = Entry(self.frameWidget) self.entryNumOfQueens.pack() # Tạo button để chạy giải quyết thuậ toán # Tham số command = self.resolving để tạo sự kiện khi nhấn button này self.btnResolving = Button(self.frameWidget, text="Min-conflict algorithm", command=self.resolving) self.btnResolving.pack(pady=50) # Tạo label để hiển thị thời gian chạy của thuật toán self.lbTime = Label(self.frameWidget, text="0.00s") # Tham số pady = 25, để label cách đều về 2 phía theo trục y 25 px self.lbTime.pack(pady=25) # Hàm tạo bàn cờ numOfQueens x numOfQueens def createMap(self, numOfQueens): for widget in self.map.winfo_children(): widget.destroy() self.map.update() self.tileList.clear() # Ta lấy chiều dài và rộng của 1 ô theo pixel w = int(self.x / numOfQueens) h = int(self.y / numOfQueens) # Cấu hình cột hàng cho MAP for k in range(numOfQueens): self.map.columnconfigure(k, pad=2) self.map.rowconfigure(k, pad=2) # Tạo các label đại diện cho một ô trong MAP for i in range(numOfQueens): self.tileList.append([]) for j in range(numOfQueens): # Tạo một ảnh pixel, để khi ta set width và height cho Label thì nó sẽ lấy theo pixel # chứ không phải mm #Ta chỉnh các background xen kẽ nhau bg = "white" if (i + j) % 2 == 0: bg = "gray" pixelVirtual = PhotoImage(width=1, height=1) lb = Label(self.map, image=pixelVirtual, width=w, height=h, bg=bg, padx=2, pady=2) lb.grid(row=i, column=j) # Đặt nó vào hàng i, cột j của MAP self.tileList[i].append(lb) ''' Hàm tìm ra solution và đặt các con hậu lên MAP ''' def resolving(self): # Khi thuật toán bắt đầu tìm kiếm, ta tiến hành khóa button này lại, tránh trường hợp # click nhiều lần từ người dùng self.btnResolving["state"] = "disabled" numOfQueens = int(self.entryNumOfQueens.get()) # Ta kiểm tra xem số hậu được nhập từ người dùng là lần đầu tiên hay là số hậu mới, hay # là chỉ tìm kiếm cách đặt hậu mới # self.currentNumOfQueens = None thì ban đầu ta sẽ tạo ra một cái map mới hoặc # số hậu nhận từ người dùng ở lần tiếp theo khác với số hậu nhập từ người dùng ở lần trước đó # thì ta cũng tạo ra map mới. Ngược lại thì ta không cần tạo map mới mà chỉ cần đặt lại vị trí # hình ảnh quân hậu if self.currentNumOfQueens == None or self.currentNumOfQueens != numOfQueens: self.currentNumOfQueens = numOfQueens self.isNewMap = True else: self.isNewMap = False solution, ti = getResults(numOfQueens) if self.isNewMap == True: self.createMap(numOfQueens) self.setTheQueens(numOfQueens, solution) self.lbTime.configure(text=str(ti) + "s") # Thuật toán chạy xong, các con hậu được đặt, ta mở khóa button cho người dùng tìm kiếm # các cách đặt khác self.btnResolving["state"] = "active" ''' Hàm đặt các quân hậu dựa vào solution tìm được ''' def setTheQueens(self, numOfQueens, solution): for i in range(numOfQueens): for j in range(numOfQueens): self.tileList[i][j].configure(image=None) self.tileList[i][j].image = None for column, row in solution.items(): image = ImageTk.PhotoImage(Image.open(os.getcwd() + "/queen.png")) self.tileList[row][column].configure(image=image) self.tileList[row][column].image = image
class Splash: def __init__(self, design): self.tela_splash = Tk() self.tela_splash.withdraw() self.tela_splash.overrideredirect(1) self.tela_splash.rowconfigure(1, weight=1) self.tela_splash.grid_columnconfigure(1, weight=1) # Design da tela self.design = design self.frame_splash = Frame(master=self.tela_splash) self.fr_splash = Frame(self.frame_splash) self.l1_splash = Label(self.frame_splash, self.design.get("cor_intro")) self.l2_splash = Label(self.frame_splash, self.design.get("cor_intro")) try: background = self.design.get("cor_intro")["background"] except Exception as erro: print(erro) background = "white" self.frame_splash.configure(background=background) self.frame_splash.rowconfigure(1, weight=1) self.frame_splash.grid_columnconfigure(0, weight=1) self.fr_splash.configure(background=background) self.l1_splash.configure(text=" SAFIRA 0.3", font=("Lucida Sans", 90), bd=80) #self.l2_splash.configure(text= ' ___\n (^.^)\n /|\\\n / \\') self.frame_splash.grid(row=1, column=1, sticky=NSEW) self.fr_splash.grid(row=0, column=1, sticky=NSEW) self.l1_splash.grid(row=1, column=1, sticky=NSEW) self.l2_splash.grid(row=2, column=1, sticky=NSEW) # Ocultar tela self.frame_splash.update() self.tela_splash.update() self.tela_splash.withdraw() j_width = self.tela_splash.winfo_reqwidth() j_height = self.tela_splash.winfo_reqheight() t_width = self.tela_splash.winfo_screenwidth() t_heigth = self.tela_splash.winfo_screenheight() geometria = "+{}+{}".format( int(t_width / 2) - int(j_width / 2), int(t_heigth / 2) - int(j_height / 2)) # Tornar tela visível self.tela_splash.geometry(geometria) self.tela_splash.deiconify() self.tela_splash.update() def splash_fim(self): self.frame_splash.update() self.tela_splash.update() self.tela_splash.withdraw() self.fr_splash.destroy() self.l1_splash.destroy() self.l2_splash.destroy() self.frame_splash.destroy() self.tela_splash.destroy()
class simrGUI: def __init__(self): #ROOT WINDOW self.myRoot = Tk() self.myRoot.minsize(640, 480) #self.myRoot.iconbitmap(default=ICON_PATH)#utilize blank icon to cover feather self.projectName = 'New Project' #MAIN MENU self.myMenu = Menu(self.myRoot) self.myRoot.config(menu=self.myMenu) self.myRoot.title("SIMR - Scripture Indices and Ministry Resources") # File Menu self.fileMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="File", menu=self.fileMenu) self.fileMenu.add_command(label="New Project", command=self.newProject) self.fileMenu.add_command(label="Save", command=self.saveProject) self.fileMenu.add_separator() self.fileMenu.add_command(label="Exit", command=self.exitApp) # Edit Menu self.editMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="Edit", menu=self.editMenu) self.editMenu.add_command( label="Undo", accelerator="Ctrl+Z", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Undo>>'), self.undoAction)) self.editMenu.add_command( label="Redo", accelerator="Ctrl+Y", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Redo>>'), self.redoAction)) #Control+Y not working for redo, it is pasting in # Read various bibles self.readMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="Read", menu=self.readMenu) self.readMenu.add_command(label="KJV") self.readMenu.add_command(label="KJV w/ Strong's") self.readMenu.add_command(label="Septuagint") self.readMenu.add_command(label="Berean") # Books (Reference Books - in public domain) self.booksMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="Books", menu=self.booksMenu) self.booksMenu.add_command(label="Number in Scripture") self.booksMenu.add_command(label="Witness of the Stars") self.booksMenu.add_command(label="How to Enjoy the Bible") # TWI Menu self.twiMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="TWI", menu=self.twiMenu) self.twiMenu.add_command(label="Scripture Index Abbreviations") self.twiMenu.add_command(label="STS List") # Help Menu self.helpMenu = Menu(self.myMenu, tearoff=0) self.myMenu.add_cascade(label="Help", menu=self.helpMenu) self.helpMenu.add_command(label="Documentation", command=self.documentation) self.helpMenu.add_command(label="Credits", command=self.getCredits) self.helpMenu.add_command(label="About", command=self.getAbout) #TOOLBAR self.myToolbar = Frame(self.myRoot) #KJV Button self.kjvButton = Button(self.myToolbar, text="KJV", command=self.kjvButtonT) self.kjvButton.pack(side=LEFT, padx=2, pady=2) #KJVS Button self.kjvSButton = Button(self.myToolbar, text="KJV w/ Strong's", command=self.kjvsButtonT) self.kjvSButton.pack(side=LEFT, padx=2, pady=2) #Septuagint Button self.septButton = Button(self.myToolbar, text="Septuagint", command=self.septButtonT) self.septButton.pack(side=LEFT, padx=2, pady=2) #Berean Button self.bereanButton = Button(self.myToolbar, text="Berean", command=self.bereanButtonT) self.bereanButton.pack(side=LEFT, padx=2, pady=2) #Hebrew Button self.hebrewButton = Button(self.myToolbar, text="Hebrew", command=self.hebrewButtonT) self.hebrewButton.pack(side=LEFT, padx=2, pady=2) #Greek Button self.greekButton = Button(self.myToolbar, text="Greek", command=self.greekButtonT) self.greekButton.pack(side=LEFT, padx=2, pady=2) #Scripture Index Button self.scriptIndexButton = Button(self.myToolbar, text="Scripture Index", command=self.scriptIndexButtonT) self.scriptIndexButton.pack(side=LEFT, padx=2, pady=2) #Text Entry Box self.entryText = StringVar(self.myToolbar) #self.entryText.set("") self.searchBox = Entry(self.myToolbar, textvariable=self.entryText) self.searchBox.pack(side=LEFT, padx=2, pady=2) #Search Button self.searchButton = Button(self.myToolbar, text="Search All", command=self.searchAll) self.searchButton.pack(side=LEFT, padx=2, pady=2) self.searchBox.bind('<Return>', self.searchAll) #Clear Button self.clearButton = Button(self.myToolbar, text="[X]", command=self.clearTxt, fg="red") self.clearButton.pack(side=RIGHT, padx=2, pady=2) #Pack the Toolbar self.myToolbar.pack(side=TOP, fill=X) #STATUS BAR AT BOTTOM self.statusBar = Label(self.myRoot, text="Displays your status here...", bd=1, relief=SUNKEN, anchor=E) #try putting a function in the text part to see if you can get text to be dynamic #SEE - https://www.youtube.com/watch?v=Mhwiy8Tr6Wo&index=13&list=PLhTjy8cBISEp6lNKUO3iwbB1DKAkRwutl&t=0s self.statusBar.pack( side=BOTTOM, fill=X ) #displays this at the bottom and at the width of the window #FRAME self.myFrame = Frame(self.myRoot) self.myFrameText = '' self.myFrame.pack(fill=BOTH, expand=True) self.myFrame.update() #SCROLLBAR & TEXT WIDGET self.scrollbar = Scrollbar(self.myFrame) self.scrollbar.pack(side=RIGHT, fill=Y) self.textOut = Text(self.myFrame, wrap=WORD, undo=True, autoseparators=True, maxundo=-1) self.textOut.pack(side=LEFT, fill=BOTH, expand=1) self.scrollbar.config(command=self.textOut.yview) self.textOut.config(yscrollcommand=self.scrollbar.set) self.textOut.insert(END, self.myFrameText) self.textOut.bind("<Button-1>", self.leftClick) self.textOut.bind("<Button-2>", self.middleClick) self.textOut.bind("<Button-3>", self.rightClick) #https://www.python-course.eu/tkinter_text_widget.php #https://www.tutorialspoint.com/python/tk_text.htm # *** http://effbot.org/tkinterbook/text.htm *** THIS IS DETAILED DO NOT DELETE #RIGHT CLICK MENU self.rClickMenu = Menu(self.myFrame, tearoff=0) self.rClickMenu.add_command(label="Copy", accelerator="Ctrl+C", command=lambda: self.textOut.focus_get(). event_generate('<<Copy>>')) self.rClickMenu.add_command( label="Cut", accelerator="Ctrl+X", command=lambda: self.textOut.focus_get().event_generate('<<Cut>>')) self.rClickMenu.add_command(label="Paste", accelerator="Ctrl+V", command=lambda: self.textOut.focus_get(). event_generate('<<Paste>>')) self.rClickMenu.add_command( label="Greek", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Copy>>'), self.rightClickGreekSearch)) self.rClickMenu.add_command( label="Hebrew", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Copy>>'), self.rightClickHebrewSearch)) self.rClickMenu.add_command( label="Search All", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Copy>>'), self.rightClickSearch)) self.rClickMenu.add_command( label="Bible Dict.", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Copy>>'), self.rightClickSearch)) self.rClickMenu.add_command( label="Find Text", command=sequenceOfFunctions( lambda: self.textOut.focus_get().event_generate('<<Copy>>'), self.rightClickFindTxt)) self.rClickMenu.add_command(label="Clear", command=self.clearTxt) self.rClickMenu.add_command(label="Close Menu") #Text for Pop Ups self.about = """\n\n About this program: --------------------------\n This program is called SIMR, which is an abbreviation for "Scripture Indices & Ministry Resources."\n This program was put together with the python programming language, and is a compilation of the works of many, many others. Others who have spent countless hours studying & teaching the Word of God. My thanks to them for making researching God's Word so much easier for us!\n The goal of this program, is to provide a tool to easily compile resources for researching God's Word. A tool to help redeem the time as we diligently study God's Word. To 'simmer' is to be at a temperature just below the boiling point. It's to be in a state of the initial stages of development...\n I thought this fitting, as when we're researching a topic, the research we are doing is developing into something more. Such as a teaching or a research work. Not only that, but if you desire to boil over with God's Word, to heat to that point, you've got to let the Word burn within you. You need to steep in it. My believing is that this tool will help you in your endeavours as you stand for God in this day, time, and hour.\n Love in Christ, N. A. Flesher - 06/03/2018\n""" self.credits = """\n\n Credits, URL Links, & Resources Used: ------------------------------------------------\n Strong's Numbers & Definitions - viz.bible\n The Holy Bible, Berean Study Bible, BSB Copyright ©2016 by Bible Hub Used by Permission. All Rights Reserved Worldwide. http://berean.bible - Berean Bible Homepage\n Data for maps and coordinate locations are from OpenBible.info licensed under a Creative Commons Attribution license.\n The King James Version, Septuagint, and Strong's Concordance, as well Ethelbert W. Bullinger's books utilized in this program: The Witness of the Stars, Number in Scripture, and How to Enjoy the Bible, are all in the public domain.\n Thanks to various Christian believers from different walks of life, for their typing of the various works, for their help in gathering resources, and their advice.\n And thanks to YOU, for studying and speaking God's Word! YOU ARE GOD'S BEST!!! \n\n""" #MAIN LOOP FOR TKINTER self.myRoot.mainloop() # if you save this as .pyw then you can double click the icon and the # python console window will be hidden # ///////////////////////////////////////////////////////////////////// # METHODS OF THE SIMRGUI CLASS # \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ #----------------------------------------------------------------------- # Search Methods #----------------------------------------------------------------------- # WRITE A FUNCTION TO SEARCH FOR WORD OR PHRASE TYPED OR SELECTED (RIGHT CLICK MENU) # AND RETURN LIST OF VERSES CONTAINING THE SEARCH STRING def find_txt(self, text): returnedVerses = [ i for i in scriptures_lst if text.upper() in i[1].upper() ] # THIS IS RETURNING A LIST OF LISTS OF ALL MATCHES (NESTED LIST) return returnedVerses #CURRENTLY ONLY SETUP TO SEARCH THE KJV # Search KJV verse def kjv_search( self, verse ): #CAN SEARCH FOR A LIST OF VERSES TYPED LIKE JOHN 1:1, aCTS 2:4, james 1:1 returnedVerses = [] verses = verse.split(',') for v in verses: v = v.strip() found = next(i for i in scriptures_lst if v in i) returnedVerses.append(' '.join(found)) return returnedVerses # Search KJV w/ Strong's verse #Old Testament def kjvstrnumOT_search(self, searchOT_ks): found_snOT = next(i for i in OT_sn if searchOT_ks in i) return found_snOT #New Testament def kjvstrnumNT_search(self, searchNT_ks): found_snNT = next(i for i in NT_sn if searchNT_ks in i) return found_snNT # Search for Berean verses def berean_search(self, berean_inp): if berean_inp in berean: bi = berean.index( berean_inp) # This is based on verse seached for. # Sets bi to the index of verse searched for return bi # Search through TWI scripture index def twi_scripture_index(self, twi_inp): found2 = next(i for i in twi_index if twi_inp in i) return found2 # Search through septuagint def septuagint_search(self, sept_inp): found3 = next(i for i in septuagint_lst3 if sept_inp in i) return found3 # Search for Strong's defintion def strongs_search(self, strongsNumber): if strongsNumber in strongscsvlst: sc = strongscsvlst.index( strongsNumber) # This is based on verse seached for. # Sets sc to the strongs number searched for return sc # OT Hebrew Strong's Definitions Search def strnumOT(self, OTsearch): # OT Strongs Search # This finds all <strongs numbers> on all lines printing result without <> OTstring = ''.join(OTsearch) sn_listOT = re.findall('\<(\d+)\>', OTstring) # print(sn_listOT) strongsNumberHebrew = [] for items in sn_listOT: hebrew = 'H' + items strongsNumberHebrew.append(hebrew) # print(hebrew) return strongsNumberHebrew def get_strongsHebrewDefs( self, strongsNumberHebrew ): #THIS DEFINITION PULLS ALL THE HEBREW DEFINITIONS FOR A VERSE scH_lst = [] for item in strongsNumberHebrew: if item in strongscsvlst: sc = strongscsvlst.index( item) # This is based on verse seached for. # Sets sc to the strongs number searched for sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] scH = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6 + '\n') if scH not in scH_lst: scH_lst.append(scH) return scH_lst # NT Greek Strong's Definitions Search def strnumNT(self, NTsearch): # NT Strongs Search # This finds all <strongs numbers> on all lines printing result without <> NTstring = ''.join(NTsearch) sn_listNT = re.findall('\<(\d+)\>', NTstring) # print(sn_listNT) strongsNumberGreek = [] for items in sn_listNT: greek = 'G' + items strongsNumberGreek.append(greek) # print(greek) return strongsNumberGreek def get_strongsGreekDefs( self, strongsNumberGreek ): #THIS DEFINITION PULLS ALL THE GREEK DEFINITIONS FOR A VERSE scG_lst = [] for item in strongsNumberGreek: if item in strongscsvlst: sc = strongscsvlst.index( item) # This is based on verse seached for. # Sets sc to the strongs number searched for sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] scG = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6 + '\n') if scG not in scG_lst: scG_lst.append(scG) return scG_lst #----------------------------------------------------------------------- # MENU METHODS #----------------------------------------------------------------------- # METHOD FOR TESTING PURPOSES def showIt(self): print("This button works...") # NEW PROJECT def newProject(self): print("New Project...") self.statusBar['text'] = "Starting new project..." # SAVE PROJECT def saveProject(self): with open("NewProject.txt", "w", encoding='utf-8') as txtFile: txtFile.write(self.getAllText()) print("Saving...") self.statusBar['text'] = "Saving..." #NEED TO ADD A POPUP WINDOW THAT ASKS FOR FILE NAME AND FILEPATH LOCATION TO SAVE THE FILE #FIX ENCODING - SEE OLD SIMR PROGRAM FOR ENCODINGS TO COPY OVER FOR WRITING TO TEXT FILE # EXIT APP def exitApp(self): print("Exiting...") self.statusBar['text'] = "Exiting..." exit() # REDO - FOR UPDATING STATUS BAR ONLY def redoAction(self): print("Redoing...") self.statusBar['text'] = "Redoing previous action..." # UNDO - FOR UPDATING STATUS BAR ONLY def undoAction(self): print("Undoing...") self.statusBar['text'] = "Undoing last action..." # GET DOCUMENTATION def documentation(self): print("Getting documentation...") self.statusBar['text'] = "Getting documentation..." # GET KJV def kjv(self): print("Getting King James Version...") self.statusBar['text'] = "Getting the King James Version text..." # GET KJVS def kjvs(self): print("Getting King James Version with Strong's...") self.statusBar[ 'text'] = "Getting the King James Version text with Strong's Numbers..." # GET SEPTUAGINT def sept(self): print("Getting Septuagint...") self.statusBar['text'] = "Getting the Septuagint text..." # GET BEREAN def berean(self): print("Getting Berean...") self.statusBar['text'] = "Getting the Berean texts..." # GET SCRIPTURE INDEX def scriptIndex(self): print("Getting Scripture Index...") self.statusBar[ 'text'] = "Getting The Way International resources scripture index..." # GET ABOUT INFO def getAbout(self): #Mbox('About', self.about, 0)# only works in windows self.messBox('About', self.about) self.statusBar['text'] = "Getting about information..." # GET CREDITS INFO def getCredits(self): #Mbox('Credits', self.credits, 0)# only works in windows self.messBox('Credits', self.credits) self.statusBar['text'] = "Getting credits..." #Message box def messBox(self, title, message): top = Toplevel() top.title(title) msg = Message(top, text=message) msg.pack() button = Button(top, text="OK", command=top.destroy) button.pack() #----------------------------------------------------------------------- # TOOLBAR METHODS #----------------------------------------------------------------------- #search button on toolbar def searchAll( self, event=None ): #ONLY WORKS WHEN SEARCHING FOR ONE VERSE AT A TIME BECAUSE ONLY KJV IS SET UP TO SEARCH FOR LIST OF VERSES SEPARATED BY A COMMA searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Gathering all resources for you..." #GET KJV kjv = self.kjv_search(searchText) kjvLabel = "KJV:\n" + '\n\n'.join(kjv) #GET KJV W/STRONGS try: kjvs = self.kjvstrnumOT_search(searchText) except: kjvs = self.kjvstrnumNT_search(searchText) kjvsLabel = "KJV w/Strong's - " + ' - '.join(kjvs) #GET SEPTUAGINT try: sept = self.septuagint_search(searchText) septLabel = "Septuagint - " + ' - '.join(sept) except: sept = "No verse found in Septuagint for your search..." septLabel = "Septuagint - " + sept #ISSUES WITH SEPTUAGINT TRY GENESIS 1:1 ALSO SOME JEREMIAH VERSES FOR EXAMPLE - LOOK INTO JSON FILE - # json showing first index as "\ufeffGenesis 1:1" - that's the issue #berean = self. #bereanLabel = #GET TWI SCRIPTURE INDEX try: twi = self.twi_scripture_index(searchText) twiLabel = "Scripture Index : \n" + ' '.join(twi) except: twiLabel = "Nothing found in Scripture Index for your search..." #GET ALL GREEK AND HEBREW DEFINITIONS HERE... try: ots = self.kjvstrnumOT_search(searchText) ots1 = self.strnumOT(ots) ots2 = self.get_strongsHebrewDefs(ots1) strongsDefinitions = ''.join(ots2) except: nts = self.kjvstrnumNT_search(searchText) nts1 = self.strnumNT(nts) nts2 = self.get_strongsGreekDefs(nts1) strongsDefinitions = ''.join(nts2) self.update_textOut(kjvLabel + '\n\n' + kjvsLabel + '\n\n' + strongsDefinitions + '\n\n' + septLabel + '\n\n' + twiLabel) #self.statusBar['text'] = "Ready..." #FOR KJV BUTTON def kjvButtonT( self, event=None ): #CAN NOW SEARCH FOR MORE THAN ONE VERSE WHEN VERSES ARE SEPARATED BY A COMMA print("Getting King James Version...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting KJV..." try: txt = self.kjv_search(searchText) self.update_textOut("KJV:\n" + '\n\n'.join(txt)) print(txt) return "KJV:\n" + '\n\n'.join(txt) except: self.update_textOut( "No verse found in the King James Version for your search.") #self.statusBar['text'] = "Ready..." #FOR KJV W/STRONGS BUTTON def kjvsButtonT(self, event=None): print("Getting King James Version with Strong's...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting KJV w/Strong's Numbers..." try: ot = self.kjvstrnumOT_search(searchText) self.update_textOut("KJV w/ Strong's - " + ' - '.join(ot)) print(ot) return "KJV w/ Strong's - " + ' - '.join(ot) except: nt = self.kjvstrnumNT_search(searchText) self.update_textOut("KJV w/ Strong's - " + ' - '.join(nt)) print(nt) return "KJV w/ Strong's - " + ' - '.join(nt) #self.statusBar['text'] = "Ready..." #FOR SEPTUAGINT BUTTON def septButtonT(self, event=None): print("Getting Septuagint...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting Septuagint..." try: txt = self.septuagint_search(searchText) self.update_textOut("Septuagint - " + ' - '.join(txt)) print(txt) return "Septuagint - " + ' - '.join(txt) except: txt = "No verse found in Septuagint for your search." self.update_textOut("Septuagint - " + txt) print(txt) return "Septuagint - " + txt #self.statusBar['text'] = "Ready..." #FOR BEREAN BUTTON def bereanButtonT(self, event=None): print("Getting Berean...") self.statusBar['text'] = "Getting Berean Bible..." # searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting Berean Bible..." # txt = # self.update_textOut(searchText) # print("Berean - " + searchText) #self.statusBar['text'] = "Ready..." #FOR SCRIPTURE INDEX BUTTON def scriptIndexButtonT(self, event=None): print("Getting Scripture Index...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar[ 'text'] = "Getting The Way International resources scripture index..." try: txt = self.twi_scripture_index(searchText) self.update_textOut("Scripture Index : \n" + ' '.join(txt)) print(txt) except: self.update_textOut( "No verse found in Scripture index for your search.") #self.statusBar['text'] = "Ready..." #FOR HEBREW BUTTON def hebrewButtonT(self, event=None): print("Getting Hebrew definitions...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting Strong's Hebrew definition..." try: sc = self.strongs_search(searchText) sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] txt = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6) self.update_textOut(txt) print(txt) except: self.update_textOut("No Hebrew definitions found for your search.") #self.statusBar['text'] = "Ready..." #FOR GREEK BUTTON def greekButtonT(self, event=None): print("Getting Greek definitions...") searchText = self.searchBox.get().title() self.searchBox.delete(0, END) self.statusBar['text'] = "Getting Strong's Greek definition..." try: sc = self.strongs_search(searchText) sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] txt = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6) self.update_textOut(txt) print(txt) except: self.update_textOut("No Greek defintions found for your search.") #self.statusBar['text'] = "Ready..." #NEED TO MAKE A FUNCTION TO SEARCH FOR GREEK WORDS BY GREEK CHARACTERS YOU CAN COPY AND PASTE FROM STRONGS #ALSO ONE FOR HEBREW #NEED TO ADD A SEARCH FUNCTION TO PULL ALL GREEK DEFINITIONS IN WHEN YOU HIT GREEK BUTTON WITH A VERSE TYPED IN #NEED TO ADD A SEARCH FUNCTION TO PULL ALL HEBREW DEFINITIONS IN WHEN YOU HIT GREEK BUTTON WITH A VERSE TYPED IN #----------------------------------------------------------------------- #HANDLE MOUSE EVENTS METHODS #----------------------------------------------------------------------- #RIGHT CLICK SEARCH ALL FUNTION - TO SEARCH FOR ALL INFORMATION ABOUT SELECTED VERSE REFERENCE TEXT def rightClickSearch(self, event=None): searchText = self.textOut.clipboard_get().title().strip() self.statusBar['text'] = "Gathering all resources for you..." #GET KJV try: kjv = self.kjv_search(searchText) kjvLabel = "KJV:\n" + '\n\n'.join(kjv) except: pass #GET KJV W/STRONGS try: try: kjvs = self.kjvstrnumOT_search(searchText) except: kjvs = self.kjvstrnumNT_search(searchText) kjvsLabel = "KJV w/Strong's - " + ' - '.join(kjvs) except: pass #GET SEPTUAGINT try: try: sept = self.septuagint_search(searchText) septLabel = "Septuagint - " + ' - '.join(sept) except: sept = "No verse found in Septuagint for your search..." septLabel = "Septuagint - " + sept #ISSUES WITH SEPTUAGINT TRY GENESIS 1:1 ALSO SOME JEREMIAH VERSES FOR EXAMPLE - LOOK INTO JSON FILE - # json showing first index as "\ufeffGenesis 1:1" - that's the issue except: pass #berean = self. #bereanLabel = #GET TWI SCRIPTURE INDEX try: try: twi = self.twi_scripture_index(searchText) twiLabel = "Scripture Index : \n" + ' '.join(twi) except: twiLabel = "Nothing found in Scripture Index for your search..." except: pass try: #GET ALL GREEK AND HEBREW DEFINITIONS HERE... try: ots = self.kjvstrnumOT_search(searchText) ots1 = self.strnumOT(ots) ots2 = self.get_strongsHebrewDefs(ots1) strongsDefinitions = ''.join(ots2) except: nts = self.kjvstrnumNT_search(searchText) nts1 = self.strnumNT(nts) nts2 = self.get_strongsGreekDefs(nts1) strongsDefinitions = ''.join(nts2) except: pass #NEED TO THINK THIS THROUGH BETTER (BELOW TRY/EXCEPT NESTED TRY/EXCEPT) - MAY NEED TO USE IF ELIF ELSE STATEMENT TO DETERMINE WHICH #self.update_textOut() HAPPENS. BECAUSE THIS IS PULLING HEBREW, WHICH SHOULD PULL GREEK FIRST...??? #That is because of (see lines 721 to 733 above) H# being generated skipping the except statement to generate a G# try: self.update_textOut(kjvLabel + '\n\n' + kjvsLabel + '\n\n' + strongsDefinitions + '\n\n' + septLabel + '\n\n' + twiLabel) except: pass #self.statusBar['text'] = "Ready..." # RIGHT CLICK SEARCH FOR GREEK DEFINITION OF SELECTED TEXT NUMBER def rightClickGreekSearch(self, event=None): searchText = self.textOut.clipboard_get().title() self.statusBar['text'] = "Getting Greek word and definition for you..." try: sc = self.strongs_search('G' + searchText) sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] gTxt = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6) print(gTxt) self.update_textOut(gTxt) except: pass #self.statusBar['text'] = "Ready..." # RIGHT CLICK SEARCH FOR HEBREW DEFINITION OF SELECTED TEXT NUMBER def rightClickHebrewSearch(self, event=None): searchText = self.textOut.clipboard_get().title() self.statusBar[ 'text'] = "Getting Hebrew word and definition for you..." try: sc = self.strongs_search('H' + searchText) sc_index0 = strongscsvlst[sc] sc_index1 = strongscsvlst[sc + 1] sc_index2 = strongscsvlst[sc + 2] sc_index3 = strongscsvlst[sc + 3] sc_index4 = strongscsvlst[sc + 4] sc_index5 = strongscsvlst[sc + 5] sc_index6 = strongscsvlst[sc + 6] hTxt = ('\n' + sc_index0 + ' - ' + sc_index1 + ' - ' + sc_index2 + ' (' + sc_index3 + ') ' + sc_index4 + ' ' + sc_index5 + ', ' + sc_index6) print(hTxt) self.update_textOut(hTxt) except: pass #self.statusBar['text'] = "Ready..." def rightClickFindTxt(self, event=None): #THIS IS NOT WORKING THE WAY I WANT self.statusBar['text'] = "Searching for text phrase..." searchText = self.textOut.clipboard_get().title().strip() returnedVerses = self.find_txt(searchText) tCount = 0 for r in returnedVerses: tCount += 1 combinedVerses = [ item for sublist in returnedVerses for item in sublist ] # combine nested lists into a single list #print("combinedVerses") #print(combinedVerses) cv = [] for count, i in enumerate( combinedVerses ): # Add the " - " between the verse reference & scripture if count % 2 == 1: cv.append(i) else: cv.append(i + " - ") cVerses = [x + y for x, y in zip(cv[0::2], cv[1::2])] #combines slices #every 2 steps starting with index 0, with every 2 steps starting with index 1 #print("cv:\n") #print(cv) self.update_textOut('Total KJV verses with translated usages of "*' + searchText.lower() + '*": ' + str(tCount) + '\n' + '\n'.join(cVerses)) #self.statusBar['text'] = "Ready..." def leftClick(self, event): print("Left") #make selection here, etc def middleClick(self, event): print("Middle") def rightClick(self, event): print("Right") self.rClickMenu.post(event.x_root, event.y_root) #----------------------------------------------------------------------- #TEXT WIDGET METHODS #----------------------------------------------------------------------- # UPDATES THE TEXT ON THE TEXT WIDGET - should probably rename myFrameText to myTextOutText or something def update_textOut(self, text): self.myFrameText = text + '\n\n' self.textOut.insert(END, self.myFrameText) # NEED A METHOD TO CLEAR ALL TEXT def clearTxt(self): self.statusBar['text'] = "Clearing all text..." self.textOut.delete(1.0, END) #self.statusBar['text'] = "Ready..." # COLLECTS ALL TEXT IN THE TEXT WIDGET TO A VARIABLE - USED TO SAVE FILE def getAllText(self): contents = self.textOut.get("1.0", "end-1c") print("Getting all text...") return contents