def test_gui(self): """ The GUI interactions by simulating user actions """ tl = Toplevel() gui = ClassicGUI(tl) gui.colorPicker = DummyColorPicker(tl) controller = DrawController(gui) self.assertEquals(gui.ioButtons.__len__(), 5, "There should be 5 IO buttons") self.assertEquals(gui.commandButtons.__len__(), 4, "There should be 4 draw command buttons") gui.onChangeColor(gui.colorPickerButton) self.assertEquals(gui.colorPickerButton.cget('bg'), gui.colorPicker.getColor()) dummyButton = Button() gui.onDrawCommandButtonClick(dummyButton, LineDrawCommand) self.assertEquals(dummyButton.cget('relief'), SUNKEN, "Selected button should have style SUNKEN") for btn in gui.commandButtons: self.assertEquals(btn.cget('relief'), FLAT, "Selected button should have style FLAT") self.assertEquals(type(controller.activeCommand), LineDrawCommand, "Active command should be LineDrawCommand") for cmd in controller.commands: controller.canvas.getDrawArea().delete(ALL) self.assertCommandOperations(controller, cmd) clearCmd = NewDrawCommand() gui.onIOCommandClick(dummyButton, clearCmd) self.assertEquals(gui.canvas.getDrawArea().find_all().__len__(), 0, "The canvas should be cleared on NewDrawCommand")
def add_operator(button: Button): global current_number if len(numbers[current_number]) > 0: operators.append(button.cget('text')) numbers.append('') current_number += 1 display.config(text=display.cget('text') + f'\n{button.cget("text")}\n{numbers[current_number]}')
def read_numeric_str(label: tk.Button): now = '' while now != Key.enter._value_: #print(now, Key.enter) x = ml.read_button() #print("raw_key= ", x) if (x[0] != ''): x[0] = int(x[0]) now = ml.to_KeyCode(x) if now.vk == Key.enter._value_: return print(now.vk, Key.backspace._value_) if now.vk == int(str(Key.backspace._value_)[1:-1]): text = label.cget("text") if text[-1] != ' ': text = text[:-1] edit(label, text) if now.char and len(now.char) == 1 and now.char in "1234567890": #print("LUL") text = (label.cget("text") + now.char) #print(text) edit(label, text)
def test_gui(self): """ The GUI interactions by simulating user actions """ tl = Toplevel() gui = ClassicGUI(tl) gui.colorPicker = DummyColorPicker(tl) controller = DrawController(gui) self.assertEquals(gui.ioButtons.__len__(), 5, "There should be 5 IO buttons") self.assertEquals(gui.commandButtons.__len__(), 4, "There should be 4 draw command buttons") gui.onChangeColor(gui.colorPickerButton) self.assertEquals(gui.colorPickerButton.cget('bg'), gui.colorPicker.getColor()) dummyButton = Button() gui.onDrawCommandButtonClick(dummyButton, LineDrawCommand) self.assertEquals(dummyButton.cget('relief'), SUNKEN, "Selected button should have style SUNKEN") for btn in gui.commandButtons: self.assertEquals(btn.cget('relief'), FLAT, "Selected button should have style FLAT") self.assertEquals(type(controller.activeCommand), LineDrawCommand, "Active command should be LineDrawCommand") for cmd in controller.commands: controller.canvas.getDrawArea().delete(ALL) self.assertCommandOperations(controller, cmd) clearCmd = NewDrawCommand() gui.onIOCommandClick(dummyButton, clearCmd) self.assertEquals(gui.canvas.getDrawArea().find_all().__len__(), 0, "The canvas should be cleared on NewDrawCommand")
def knights_tour(self, n): # create board mainframe = Frame(self, padx=5, pady=5) mainframe.grid(column=0, row=0, sticky="n,e,s,w") self.board = Canvas( mainframe, width=self.boardsize, height=self.boardsize, borderwidth=0, highlightthickness=0, bg="white", ) self.board.grid(row=1, column=0) clicked = [None] gcolor = {0: "brown3", 1: "saddle brown"} coords = {} finalGridColor = {} buttons = [] for row in range(n): for col in range(n): button = Button(self.board) button.grid( column=col, row=row, sticky="n,e,s,w", command=self.showGrid(button, coords, row, col), ) button.config( width=int(self.boardsize / (10 * n)), height=int(self.boardsize / (20 * n)), bg=gcolor[(row + col) % 2], ) button["command"] = lambda button=button: self.action( button, coords, clicked, finalGridColor, n, buttons) finalGridColor[button] = button.cget("bg") buttons.append(button)
class PasswordWindow(Toplevel): def __init__(self, master, success, failure): Toplevel.__init__(self, master) self.geometry('+%d+%d' % (master.winfo_x(), master.winfo_y())) self.title('Nescient password request:') self.lock_image = PhotoImage(data=LOCK_DATA) try: self.tk.call('wm', 'iconphoto', self._w, self.lock_image) except Exception: pass self.resizable(False, False) self.success = success self.failure = failure self.grab_set() self.focus_set() self.protocol('WM_DELETE_WINDOW', self.close) self.bind('<Return>', self.test_submit) self.grid() self.lock = Label(self, image=self.lock_image) self.lock_text = Message( self, text='Please enter the password with which to pack/unpack files:', width=256) self.label1 = Label(self, text='Insert password:'******'*', bg='white', fg='black') self.password.focus_set() self.label2 = Label(self, text='Verify password:'******'*', validate='key', validatecommand=(vcmd, '%P'), bg='white', fg='black') self.button = Button(self, text='Submit', state=DISABLED, command=lambda: self.close(self.password.get())) self.lock.grid(column=0, row=0) self.lock_text.grid(column=1, row=0) self.label1.grid(column=0, row=1, padx=5, pady=5) self.password.grid(column=1, row=1, padx=2, pady=5) self.label2.grid(column=0, row=2, padx=5, pady=5) self.password2.grid(column=1, row=2, padx=2, pady=5) self.button.grid(column=0, row=3, columnspan=2) def test_submit(self, *args): if self.button.cget('state') == NORMAL: self.close(self.password.get()) def can_submit(self, password2): password = self.password.get() if password == password2 and password != '': self.button.config(state=NORMAL) else: self.button.config(state=DISABLED) return True def close(self, password=None): self.grab_release() self.master.grab_set() self.master.focus_force() if password: self.success(password) else: self.failure(password) self.destroy()
class Controls: ''' Class Controls containing the methods to control: - handleargs : handle the arguments at startup - create : create buttons - reset_controls : reset control variables to steer the program - pause_status : toggles from pause to run - previous_item : jumps to previous news item - next_item : jumps to next news item - site_select : select a news site depending on what news site button is pressed - banner_status : toggles from banner display to normal display - exit_news : exit the program ''' def __init__(self): root.bind("<Escape>", self.exit_news) root.protocol('WM_DELETE_WINDOW', self.exit_news) root.bind("<b>", self.change_background) self.run = True self.pause = False self.next = False self.previous = False self.orig_bg = '' def handleargs(self): ''' handle the arguments: python news.py [-b] <news_site> ''' try: if sys.argv[1] == '-b': self.displaybanner = True argid = 2 else: self.displaybanner = False argid = 1 except IndexError: argid = 1 self.displaybanner = False try: self.news_site = sys.argv[argid] if self.news_site not in news_list: self.news_site = 'BBC Business' except IndexError: self.news_site = 'Nu.nl' def create(self): ''' Method to create control buttons, including news sites defined in the Dictonary ''' bwidth = 8 padx = 3 buttonframe = Frame(root, bd=2, relief='sunken') self.pause_button = Button(buttonframe, text='Pause', width=bwidth, command=self.pause_status) self.pause_button.pack(side='left', padx=padx) self.orig_bg = self.pause_button.cget("bg") self.previous_button = Button(buttonframe, text='Previous', width=bwidth, command=self.previous_item) self.previous_button.pack(side='left', padx=padx) self.next_button = Button(buttonframe, text='Next', width=bwidth, command=self.next_item) self.next_button.pack(side='left', padx=padx) self.banner_button = Button(buttonframe, text='Banner', width=bwidth, command=self.banner_status) self.banner_button.pack(side='left', padx=padx) # note that banner_status will reverse the flag! self.displaybanner = not self.displaybanner self.banner_status() self.exit_button = Button(buttonframe, text='Exit', width=bwidth, command=self.exit_news) self.exit_button.pack(side='left', padx=padx) buttonframe.pack(side='bottom', anchor='sw') bwidth = 12 newsbuttonframe = Frame(root, bd=2, relief='sunken') rows = 10 self.site_button = {} for i, site in enumerate(news_list): btn = Button(newsbuttonframe, text=site, width=bwidth, command=lambda x=site: self.site_select(x)) row = i % rows column = i // rows btn.grid(row=row, column=column) self.site_button[site] = btn newsbuttonframe.pack(side='right', anchor='ne') def reset_controls(self): ''' Method to reset all control booleans ''' self.pause = False self.next = False self.previous = False self.exit_banner = False def pause_status(self): ''' Method to toggle between pause and run ''' self.pause = not self.pause while self.pause and self.run: self.pause_button.config(relief='sunken', bg='grey') root.update() self.pause_button.config(relief='raised', bg=self.orig_bg) def previous_item(self): ''' Method to return to a previous news item ''' self.previous = True self.pause = False self.exit_banner = True self.previous_button.config(relief='raised') def next_item(self): ''' Method to jump to a next news item ''' self.next = True self.pause = False self.exit_banner = True self.next_button.config(relief='raised') def site_select(self, site): ''' Method to select another news site ''' self.news_site = site for x in news_list: self.site_button[x].config(relief='raised', bg=self.orig_bg) self.exit_banner = True self.pause = False self.site_button[self.news_site].config(relief='sunken', bg='grey') def banner_status(self): self.displaybanner = not self.displaybanner if self.displaybanner: self.banner_button.config(relief='raised', bg='grey') else: self.banner_button.config(relief='raised', bg=self.orig_bg) self.pause = False self.exit_banner = True def change_background(self, *event): ''' Method to change background color ''' if root['bg'] == bg_purple: root.config(bg=bg_darkblue) else: root.config(bg=bg_purple) def exit_news(self, *event): ''' Method to leave the program ''' print("we will leave the program now....") root.after(1000) # 1000 ms self.run = False self.exit_banner = True
def add_digit(button: Button): global current_number last_index = None if numbers[current_number] == '' else -1 numbers[current_number] += button.cget('text') update_display(last_index)
class Minesweeper(): #Button style and dimensions BUTTON_HEIGHT = 1 BUTTON_WIDTH = 4 BUTTON_BORDER_WIDTH = 4 BUTTON_STYLE = "raised" GAME_DIFFICULTY_OPTIONS = ["Easy", "Medium", "Hard"] EASY_ROWS = 10 EASY_COLUMNS = 10 EASY_MINES = 10 MEDIUM_ROWS = 20 MEDIUM_COLUMNS = 20 MEDIUM_MINES = 40 HARD_ROWS = 30 HARD_COLUMNS = 30 HARD_MINES = 99 previous_game_difficulty = "Medium" win_flag = True def __init__(self, rows, columns, number_of_mines): self.rows = rows self.columns = columns self.buttons = [] self.number_of_mines = number_of_mines self.flag_count = self.number_of_mines self.start_time = time.time() self.revealed = list(range(0, self.rows * self.columns)) self.revealed[:] = ['nr'] * len(self.revealed) self.flag = list(range(0, self.rows * self.columns)) self.flag[:] = ['nf'] * len(self.flag) self.mine_cells, self.mine_counts = self.load_mines( self.number_of_mines) self.window = Tk() self.window.title("Minesweeper") self.window.config(bg="#9ba2a3") self.upper_frame = Frame(self.window, bg="#9ba2a3") self.lower_frame = Frame(self.window) self.upper_frame.pack() self.lower_frame.pack() self.difficulty = StringVar(self.upper_frame) self.difficulty.set( self.GAME_DIFFICULTY_OPTIONS[self.GAME_DIFFICULTY_OPTIONS.index( self.previous_game_difficulty)]) self.difficulty.trace("w", self.set_difficulty) opt = OptionMenu(self.upper_frame, self.difficulty, *self.GAME_DIFFICULTY_OPTIONS) opt.grid(row=0, column=0, padx=50) self.flag_label = Label(self.upper_frame, text="Flags: " + str(number_of_mines)) self.flag_label.grid(row=0, column=1, padx=50) self.score_display = Label(self.upper_frame, text="Time") self.score_display.after(200, self.timer) self.score_display.grid(row=0, column=2, padx=50) for self.row in range(0, self.rows): for self.column in range(0, self.columns): if self.previous_game_difficulty == "Easy": self.button = Button(self.lower_frame, height=self.BUTTON_HEIGHT, font='sans 10 bold', width=self.BUTTON_WIDTH, borderwidth=self.BUTTON_BORDER_WIDTH, relief=self.BUTTON_STYLE) elif self.previous_game_difficulty == "Medium": self.button = Button(self.lower_frame, height=self.BUTTON_HEIGHT, font='sans 8 bold', width=self.BUTTON_WIDTH, borderwidth=self.BUTTON_BORDER_WIDTH, relief=self.BUTTON_STYLE) elif self.previous_game_difficulty == "Hard": self.button = Button(self.lower_frame, height=self.BUTTON_HEIGHT, font='sans 5 bold', width=self.BUTTON_WIDTH, borderwidth=self.BUTTON_BORDER_WIDTH, relief=self.BUTTON_STYLE) self.position = [self.row, self.column] self.button.bind("<Button-2>", lambda event, position=self.position: self. right_click(event, position)) self.button.bind("<Button-3>", lambda event, position=self.position: self. right_click(event, position)) self.button.bind("<Button-1>", lambda event, position=self.position: self. left_click(event, position)) self.button.grid(row=self.row, column=self.column, sticky="NSEW") self.button.grid_columnconfigure(0, weight=1) self.button.grid_rowconfigure(0, weight=1) self.button.grid_propagate(False) self.buttons.append(self.button) self.BUTTON_DEFAULT_COLOR = self.button.cget('bg') self.window.resizable(False, False) self.window.mainloop() def left_click(self, event, position): row = position[0] column = position[1] if self.flag[self.rows * row + column] == 'f': return self.label_to_button(row, column) def right_click(self, event, position): row = position[0] column = position[1] if self.flag[self.rows * row + column] == 'f' and self.revealed[self.rows * row + column] != 'r': event.widget.configure(bg=self.BUTTON_DEFAULT_COLOR) self.flag[self.rows * position[0] + position[1]] = 'nf' self.flag_count += 1 #this is for upper frame self.flag_label.configure(text="Flags: " + str(self.flag_count)) elif self.revealed[self.rows * row + column] != 'r': if self.flag_count == 0: return event.widget.configure(bg="#808080", state=DISABLED) self.flag[self.rows * position[0] + position[1]] = 'f' self.flag_count -= 1 #this is for upper frame self.flag_label.configure(text="Flags: " + str(self.flag_count)) def timer(self): self.score_display.configure(text="Time: " + str(int(time.time() - self.start_time))) if self.win_flag: self.score_display.after(200, self.timer) def surroundings(self, row, column): surrounding = [] if row != 0 and column != 0 and row != self.rows - 1 and column != self.columns - 1: surrounding.append([(self.rows * (row + 1)) + (column - 1), row + 1, column - 1]) surrounding.append([(self.rows * (row + 1)) + (column), row + 1, column]) surrounding.append([(self.rows * (row + 1)) + (column + 1), row + 1, column + 1]) surrounding.append([(self.rows * (row - 1)) + (column - 1), row - 1, column - 1]) surrounding.append([(self.rows * (row - 1)) + (column), row - 1, column]) surrounding.append([(self.rows * (row - 1)) + (column + 1), row - 1, column + 1]) surrounding.append([(self.rows * row) + column - 1, row, column - 1]) surrounding.append([(self.rows * row) + column + 1, row, column + 1]) elif row == 0 and column == 0: surrounding.append([1, 0, 1]) surrounding.append([self.columns, 1, 0]) surrounding.append([self.columns + 1, 1, 1]) elif row == 0 and column == self.columns - 1: surrounding.append([self.columns - 2, 0, self.columns - 2]) surrounding.append([2 * self.columns - 1, 1, self.columns - 1]) surrounding.append([2 * self.columns - 2, 1, self.columns - 2]) elif row == 0 and column != 0 and column != self.columns - 1: surrounding.append([(self.rows * (row + 1)) + (column - 1), row + 1, column - 1]) surrounding.append([(self.rows * (row + 1)) + (column), row + 1, column]) surrounding.append([(self.rows * (row + 1)) + (column + 1), row + 1, column + 1]) surrounding.append([(self.rows * row) + column + 1, row, column + 1]) surrounding.append([(self.rows * row) + column - 1, row, column - 1]) elif row == self.rows - 1 and column != 0 and column != self.columns - 1: surrounding.append([(self.rows * (row - 1)) + (column - 1), row - 1, column - 1]) surrounding.append([(self.rows * (row - 1)) + (column), row - 1, column]) surrounding.append([(self.rows * (row - 1)) + (column + 1), row - 1, column + 1]) surrounding.append([(self.rows * row) + column + 1, row, column + 1]) surrounding.append([(self.rows * row) + column - 1, row, column - 1]) elif column == 0 and row != 0 and row != self.rows - 1: surrounding.append([(self.rows * (row + 1)) + (column), row + 1, column]) surrounding.append([(self.rows * (row + 1)) + (column + 1), row + 1, column + 1]) surrounding.append([(self.rows * (row - 1)) + (column), row - 1, column]) surrounding.append([(self.rows * (row - 1)) + (column + 1), row - 1, column + 1]) surrounding.append([(self.rows * row) + column + 1, row, column + 1]) elif column == self.columns - 1 and row != 0 and row != self.rows - 1: surrounding.append([(self.rows * (row + 1)) + (column - 1), row + 1, column - 1]) surrounding.append([(self.rows * (row + 1)) + (column), row + 1, column]) surrounding.append([(self.rows * (row - 1)) + (column - 1), row - 1, column - 1]) surrounding.append([(self.rows * (row - 1)) + (column), row - 1, column]) surrounding.append([(self.rows * row) + column - 1, row, column - 1]) elif row == self.rows - 1 and column == 0: surrounding.append([(self.rows * row) + column + 1, row, column + 1]) surrounding.append([(self.rows * (row - 1)) + column, row - 1, column]) surrounding.append([(self.rows * (row - 1)) + column + 1, row - 1, column + 1]) elif column == self.columns - 1 and row == self.rows - 1: surrounding.append([(self.rows * row) + column - 1, row, column - 1]) surrounding.append([(self.rows * (row - 1)) + column, row - 1, column]) surrounding.append([(self.rows * (row - 1)) + column - 1, row - 1, column - 1]) return surrounding def load_mines(self, number_of_mines): mine_cells = list(range(self.rows * self.columns)) mine_cells[0:number_of_mines] = [1] * number_of_mines mine_cells[number_of_mines:] = [0 ] * (len(mine_cells) - number_of_mines) random.shuffle(mine_cells) random.shuffle(mine_cells) mine_counts = [] for row in range(0, self.rows): for column in range(0, self.columns): if mine_cells[self.rows * row + column] == 1: mine_counts.append('b') continue mine_count = 0 surroundings = self.surroundings(row, column) for cell in surroundings: mine_count += mine_cells[cell[0]] mine_counts.append(mine_count) for row in range(0, len(mine_counts)): if int(mine_cells[row]) == 1: mine_cells[row] = 'b' else: mine_cells[row] = mine_counts[row] print('\n') for row in range(0, self.rows): li = [] for column in range(0, self.columns): li.append(mine_cells[self.rows * row + column]) print(li) return mine_cells, mine_counts def label_to_button(self, row, column): if self.revealed[self.rows * row + column] == 'r': return if self.flag[self.rows * row + column] == 'f': self.buttons[self.rows * row + column].configure(bg=self.BUTTON_DEFAULT_COLOR) self.flag[self.rows * row + column] = 'nf' self.flag_count += 1 #this is for upper frame self.flag_label.configure(text="Flags: " + str(self.flag_count)) if self.mine_cells[self.rows * row + column] == 'b': #,height=1,width=3, #mine_image = PhotoImage(file="E:\My git repos\minesweeper-using-tkinter\mines.gif") for k in range(0, self.rows): for l in range(0, self.columns): if self.mine_cells[self.rows * k + l] == 'b': self.buttons[self.rows * k + l].configure( state=DISABLED, bg='#d97707') self.revealed[self.rows * k + l] = 'r' self.mine_counts[self.rows * k + l] = " self.revealed" self.buttons[self.rows * row + column].configure( state=DISABLED, bg='#b03320') self.revealed[self.rows * row + column] = 'r' self.game_lost() return elif self.mine_cells[self.rows * row + column] != 0 and self.mine_cells[self.rows * row + column] != 'b': if self.mine_cells[self.rows * row + column] == 1: self.buttons[self.rows * row + column].configure( fg='green', text=str(self.mine_counts[self.rows * row + column])) elif self.mine_cells[self.rows * row + column] == 2: self.buttons[self.rows * row + column].configure( fg='blue', text=str(self.mine_counts[self.rows * row + column])) else: self.buttons[self.rows * row + column].configure( fg='red', text=str(self.mine_counts[self.rows * row + column])) self.revealed[self.rows * row + column] = 'r' elif self.mine_counts[self.rows * row + column] == 0: def clear_cell(cell_data): if self.revealed[cell_data[0]] == 'r': return elif self.revealed[cell_data[0]] == 'nr' and self.mine_counts[ cell_data[0]] != 0: self.label_to_button(cell_data[1], cell_data[2]) return elif self.mine_counts[cell_data[0]] == 0 and self.revealed[ cell_data[0]] == 'nr': if self.flag[cell_data[0]] == 'f': self.flag_count += 1 #this is for upper frame self.flag_label.configure(text="Flags: " + str(self.flag_count)) self.buttons[self.rows * cell_data[1] + cell_data[2]].configure(state=DISABLED, bg='#0096e0') self.revealed[self.rows * cell_data[1] + cell_data[2]] = 'r' surroundings = self.surroundings(cell_data[1], cell_data[2]) for cell in surroundings: clear_cell(cell) clear_cell([self.rows * row + column, row, column]) win_count = 0 for check_win in range(0, self.rows * self.columns): if self.mine_counts[check_win] != 'b' and self.revealed[ check_win] == 'r': win_count += 1 if win_count == (self.rows * self.columns) - self.number_of_mines: self.win_flag = False self.game_win() def game_win(self): self.score = int(time.time() - self.start_time) self.window.update_idletasks() message_answer = messagebox.askyesno( title="Win Game", message="You swept all the mines " + "\n" + "Score: " + str(self.score) + ". Do you want to play again??") if message_answer: self.new_game() else: self.window.destroy() def game_lost(self): self.window.update_idletasks() message_answer = messagebox.askyesno( title="Better luck next time :(", message="Game lost!!. Do you want to try again??") if message_answer: self.new_game() else: self.window.destroy() def set_difficulty(self, *args): self.new_game() pass def new_game(self): #self.difficulty.get() self.window.destroy() self.set_option = False difficulty = self.difficulty.get() if difficulty == "Easy": self.previous_game_difficulty = "Easy" self.__init__(self.EASY_ROWS, self.EASY_COLUMNS, self.EASY_MINES) if difficulty == "Medium": self.previous_game_difficulty = "Medium" self.__init__(self.MEDIUM_ROWS, self.MEDIUM_COLUMNS, self.MEDIUM_MINES) if difficulty == "Hard": self.previous_game_difficulty = "Hard" self.__init__(self.HARD_ROWS, self.HARD_COLUMNS, self.HARD_MINES)
class PushButton(WidgetMixin, ScheduleMixin, DestroyMixin, EnableMixin, FocusMixin, DisplayMixin, ReprMixin): def __init__(self, master, command, args=None, text="Button", icon=None, pady=10, padx=10, grid=None, align=None): self._master = master self._grid = grid self._align = align self._visible = True self._text = StringVar() self._text.set(text) self._current_font = "Arial" self._font_size = 11 self._value = 0 self.change_command(command, args) # Description of this object (for friendly error messages) self.description = "[PushButton] object with text \"" + self._text.get( ) + "\"" # Create a tk Button object within this object self.tk = Button(master.tk, textvariable=self._text) # Add padding if necessary self.tk.config(pady=pady, padx=padx) # Setup events for press and release self.tk.bind("<ButtonPress>", self._on_press) self.tk.bind("<ButtonRelease>", self._on_release) # Try to instantiate a picture if icon is not None: try: self._icon = PhotoImage(file=icon) self.tk.config(image=self._icon) except AttributeError: utils.error_format( "Image import error - image must be a gif, check correct path" ) # Pack or grid depending on parent try: utils.auto_pack(self, master, grid, align) except AttributeError: utils.error_format( self.description + "\n" + "Could not add to interface - check first argument is [App] or [Box]" ) # PROPERTIES # ---------------------------------- # Get the value of the button (pressed, released) @property def value(self): return self._value # Get the text on the button @property def text(self): return (self._text.get()) # Set the text on the button @text.setter def text(self, value): self._text.set(str(value)) self.description = "[Text] object with text \"" + str(value) + "\"" # Get the text colour as a string @property def text_color(self): return (self.tk.cget("fg")) # Set the text colour @text_color.setter def text_color(self, color): self.tk.config(fg=color) # Get the background colour as a string @property def bg(self): return (self.tk.cget("bg")) # Set the background colour @bg.setter def bg(self, color): self.tk.config(bg=color) # Get the current font as a string @property def font(self): return (self._current_font) # Set the current font @font.setter def font(self, font): self._current_font = font self.tk.config(font=(self._current_font, self._font_size)) # Get the current text size as an integer @property def text_size(self): return (self._font_size) # Set the font size @text_size.setter def text_size(self, size): self._font_size = int(size) self.tk.config(font=(self._current_font, self._font_size)) # Get the current height as an integer (does not include padding) @property def height(self): return int(self.tk.cget("height")) # Set the height @height.setter def height(self, height_px): self.tk.config(height=int(height_px)) # Get the current width as an integer (does not include padding) @property def width(self): return int(self.tk.cget("width")) # Set the height @width.setter def width(self, width_px): self.tk.config(width=int(width_px)) # METHODS # ------------------------------------------- # Internal use only # Called when the button is pressed def _on_press(self, event): if self.enabled: self._value = 1 # Called when the button is released def _on_release(self, event): if self.enabled: self._value = 0 self._command() # Change command - needs the name of a function and optional args as a list def change_command(self, newcommand, args=None): if args is None: self._command = newcommand else: # If the args LIST was not blank, allow args self._command = utils.with_args(newcommand, *args) # Change padding def padding(self, padx, pady): self.tk.config(padx=padx, pady=pady) # Set the icon def icon(self, icon): try: img = PhotoImage(file=icon) self._icon = img self.tk.config(image=img) except AttributeError: utils.error_format( "Image import error - image must be a gif, check correct path") def toggle(self): self.enabled = not self.enabled # DEPRECATED # ------------------------------------------- # Change text def set_text(self, text): self.text = text utils.deprecated( "PushButton set_text() is deprecated. Please use the value property instead." ) # Toggle button state - renamed to just toggle def toggle_state(self): self.toggle() utils.deprecated( "PushButton toggle_state() is deprecated - renamed to toggle()")
def render(self): ''' The function that renders the calculator. ''' # Window self.root.geometry("256x300") self.root.resizable(False, False) self.root.title("Chrispy Calculator") self.root.iconbitmap("./favicon.ico") # Output Box self.output_box.grid(row=0, column=0, columnspan=5, pady=(0, 20)) # Create number buttons button_0 = Button(self.root, text="0", bg="#2D2D2D", fg="#EEEEEE", width=5, height=2, font=("Consolas 12")) button_0.config(command=partial(self.calculator.append_expression, button_0.cget("text"))) button_0.grid(row=4, column=0) current_row = 3 current_column = 0 for i in range(1, 10): current_button = Button(self.root, text=str(i), bg="#2D2D2D", fg="#EEEEEE", width=5, height=2, font=("Consolas 12")) current_button.config( command=partial(self.calculator.append_expression, current_button.cget("text"))) current_button.grid(row=current_row, column=current_column) current_column += 1 if int(current_button.cget("text")) % 3 == 0: current_row -= 1 current_column = 0 # Operator Buttons operators = ["+", "−", "×", "÷"] current_row = 1 for operator in operators: current_button = Button(self.root, text=operator, bg="#2D2D2D", fg="#EEEEEE", width=5, height=2, font=("Consolas 12")) current_button.config( command=partial(self.calculator.append_expression, current_button.cget("text"))) current_button.grid(row=current_row, column=4) current_row += 1 decimal_button = Button(self.root, text=".", bg="#2D2D2D", fg="#EEEEEE", width=5, height=2, font=("Consolas 12")) decimal_button.config(command=partial( self.calculator.append_expression, decimal_button.cget("text"))) decimal_button.grid(row=4, column=1) equals_button = Button(self.root, text="=", bg="#2D2D2D", fg="#EEEEEE", width=5, height=2, font=("Consolas 12")) equals_button.config( command=lambda: [self.calculator.evaluate_expression(), self.output_expression()]) equals_button.grid(row=4, column=2) self.root.after(1, self.output_expression) self.root.mainloop()
class MyFirstGUI: def __init__(self, master): self.master = master master.title("Basic Calculator") self.num1 = Button(self.master, text='1', command=self.getOne) self.num1.grid(row=2, column=0) self.num2 = Button(self.master, text='2', command=self.getTwo) self.num2.grid(row=2, column=1) self.num3 = Button(self.master, text='3', command=self.getThree) self.num3.grid(row=2, column=2) self.num4 = Button(self.master, text='4', command=self.getFour) self.num4.grid(row=3, column=0) self.num5 = Button(self.master, text='5', command=self.getFive) self.num5.grid(row=3, column=1) self.num6 = Button(self.master, text='6', command=self.getSix) self.num6.grid(row=3, column=2) self.num7 = Button(self.master, text='7', command=self.getSeven) self.num7.grid(row=4, column=0) self.num8 = Button(self.master, text='8', command=self.getEight) self.num8.grid(row=4, column=1) self.num9 = Button(self.master, text='9', command=self.getNine) self.num9.grid(row=4, column=2) self.equal = Button(self.master, text='=', command=self.evaluate) self.equal.grid(row=5, column=2) self.zero = Button(self.master, text='0', command=self.getZero) self.zero.grid(row=5, column=1) self.add = Button(self.master, text='+', command=self.addition) self.add.grid(row=2, column=3) self.multiply = Button(self.master, text='*', command=self.multiplication) self.multiply.grid(row=3, column=3) self.divide = Button(self.master, text='/', command=self.division) self.divide.grid(row=4, column=3) self.minus = Button(self.master, text='-', command=self.substract) self.minus.grid(row=5, column=3) self.delete = Button(self.master, text='AC', command=self.clear) self.delete.grid(row=5, column=0) self.s = '' self.display = Label(self.master, text=self.s) self.display.grid(row=0) self.quit = Button(self.master, text='OFF', command=self.close) self.quit.grid(row=8) def clear(self): self.s = '' self.display = Label(self.master, text=self.s) self.display.grid(row=0) def getOne(self): self.s += self.num1.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def getTwo(self): self.s += self.num2.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def getThree(self): self.s += self.num3.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def getFour(self): self.s += self.num4.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def getFive(self): self.s += self.num5.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def getSix(self): self.s += self.num6.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def getSeven(self): self.s += self.num7.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def getEight(self): self.s += self.num8.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def getNine(self): self.s += self.num9.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def multiplication(self): self.s += self.multiply.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def getZero(self): self.s += self.zero.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def addition(self): self.s += self.add.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def substract(self): self.s += self.minus.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def division(self): self.s += self.divide.cget('text') self.display = Label(self.master, text=self.s) self.display.grid(row=0) def evaluate(self): self.s = eval(self.s) print(self.s) self.display = Label(self.master, text='') self.display.grid(row=0) self.display = Label(self.master, text=self.s) self.display.grid(row=0) self.s = '' def close(self): self.master.destroy()
def _get_num_input(input_button: tk.Button): return int(input_button.cget('text'))
class TaskAdder(Frame): """Classe permettant d'ajouter des tâches (widget de gauche de l'Application).""" def __init__(self, master=None, menubar=None, **kwargs): """ master : TaskEditor. menubar : MenuBar. **kwargs : options de configuration du Frame, voir Frame.config() et Frame.keys() """ Frame.__init__(self, master, **kwargs) # Note : self.master est une référence vers TaskEditor self.menu = menubar # Attributs normaux: date = time.localtime() self.debut = None # datetime.datetime(date.tm_year, date.tm_mon, date.tm_mday) self.fin = datetime.datetime(date.tm_year, date.tm_mon, date.tm_mday) del date # Widgets non référencés. Label(self, text="Nom :").grid(row=0, column=0, sticky="e") Label(self, text="De :").grid(row=1, column=0, sticky="e") Label(self, text="À :").grid(row=1, column=6, sticky="e") Label(self, text="Répétitions :").grid(row=2, column=0, columnspan=2, sticky="e") Label(self, text="répétitions tout les").grid(row=2, column=3, columnspan=2) # Widgets : # Nom : self.champNom = Entry(self) # Debut : self.champDebut = Button(self, command=self.askDateDebut) # Fin : self.champFin = Button(self, command=self.askDateFin) # Duree self.champJour = Spinbox(self, from_=0, to=31, increment=1, width=4) self.champHeure = Spinbox(self, from_=0, to=23, increment=1, width=4) self.champMinute = Spinbox(self, from_=0, to=59, increment=1, width=4) # Répétitions : self.champNbRepetition = Spinbox(self, from_=-1, to=100, increment=1, width=4) # Nombre de répétition self.champRepetition = Spinbox( self, from_=1, to=100, increment=1, width=4) # quantitée d'unitée de temps entre 2 rép. self.champUniteeRepet = Combobox(self, values=[ "minutes", "heures", "jours", "semaines", "mois", "années" ], state="readonly", width=4) # valeurs par défaut : self.champNbRepetition.set(0) self.champRepetition.set(1) self.champUniteeRepet.set(self.champUniteeRepet.cget("values")[2]) # Autres : self.champDescription = Text(self, height=3, width=10, wrap="word") self.boutonColor = TkButton(self, command=self.askcolor, width=4, relief=GROOVE, bg="white", activebackground="white") # Valider self.boutonValider = Button(self, command=self.valider, text="Ajouter") # Placement : # Ligne 0 : self.champNom.grid(row=0, column=1, columnspan=4, sticky="ew") self.boutonColor.grid(row=0, column=5, sticky="ew", padx=2) self.boutonValider.grid(row=0, column=6, columnspan=2, sticky="ew") # Ligne 1 : self.champDebut.grid(row=1, column=1, columnspan=2) self.champJour.grid(row=1, column=3) self.champHeure.grid(row=1, column=4) self.champMinute.grid(row=1, column=5) self.champFin.grid(row=1, column=7) # Column 6 est pris par label "À :" # Ligne 2 : self.champNbRepetition.grid(row=2, column=2, sticky="ew") self.champRepetition.grid(row=2, column=5, sticky="ew") self.champUniteeRepet.grid(row=2, column=6, sticky="ew", columnspan=2) # Ligne 3 : self.champDescription.grid(row=3, column=0, columnspan=8, sticky="ew") def askcolor(self): self.color = askcolor()[1] self.boutonColor.config(bg=self.color, activebackground=self.color) def askDateDebut(self): # Pour un obscure raison, il faut appeler cette méthode : self.master.redessiner() # demande de la date date = askdate(self.menu.variableHorlogeStyle.get()) self.debut = date self.champDebut.config(text=date if date is not None else "") self.autoSetDuree() def askDateFin(self): # Pour un obscure raison, il faut appeler cette méthode : self.master.redessiner() # demande de la date date = askdate(self.menu.variableHorlogeStyle.get()) if date is not None: self.fin = date self.champFin.config(text=date if date is not None else "") self.autoSetDuree() def getDuree(self): print(self.debut, self.fin) ecart = self.fin - (self.debut if self.debut is not None else self.fin) print(ecart) return ecart def autoSetDuree(self): ecart = self.getDuree() self.champJour.set(ecart.days) self.champHeure.set(ecart.seconds // 3600) self.champMinute.set(ecart.seconds // 60 % 60) def getRepetitionTime(self): unit = self.champUniteeRepet.get() val = int(self.champRepetition.get()) return val, unit def valider(self): nom = self.champNom.get() if self.debut is not None: debut = self.debut + datetime.timedelta( ) # Faire une copie de la date else: debut = None duree = self.getDuree() rep = self.getRepetitionTime() nbrep = int(self.champNbRepetition.get()) desc = self.champDescription.get("0.0", END) color = self.boutonColor.cget("bg") self.master.ajouter(Task(nom, debut, duree, rep, nbrep, desc, color))
def viewFrame(self, button: tk.Button): if button.cget('bg') == Acc.black: self.colorAll() self.forgetAll() button.config(bg=Acc.white) self.configureOtherFrames(self.getButtonFrame(button))
class GUI: """ This is the view and controller Controller inits the model for the view and responds to events from the view View is responsible for displaying the data """ SAVE_NAME = 'last_state.json' def __init__(self, master): self.master = master master.title('Mines-Weeper by Agent Orange') self.menu_frame = Frame(master) self.menu_frame.pack(side=TOP) self.rem_mines = StringVar() self.rem_mines_label = Label(self.menu_frame, textvariable=self.rem_mines) self.rem_mines_label.pack(side=LEFT) self.reset_button = Button(self.menu_frame, text='Reset', command=self.board_reset) self.reset_button.pack(side=LEFT) self.easy_button = Button(self.menu_frame, text='easy', command=self.easy) self.easy_button.pack(side=LEFT) self.intermediate_button = Button(self.menu_frame, text='intermediate', command=self.intermediate) self.intermediate_button.pack(side=LEFT) self.hard_button = Button(self.menu_frame, text='hard', command=self.hard) self.hard_button.pack(side=LEFT) self.custom_button = Button(self.menu_frame, text='custom', command=self.custom) self.custom_button.pack(side=LEFT) self.bar_colour = self.hard_button.cget("background") self.win_lose = [ self.reset_button, self.easy_button, self.intermediate_button, self.hard_button, self.custom_button ] self.grid_squares = [] self.asshats = Asshats() if self.load_board() is None: self.board_reset(EASY) def init_board_frame(self): # noinspection PyAttributeOutsideInit self.board_frame = Frame(self.master) self.board_frame.pack(side=BOTTOM) self.grid_squares = [] for y in range(self.config.y): current_row = [] for x in range(self.config.x): square = SquareButton(self.board_frame, x, y, self) square.config(image=self.asshats.photo_closed, width='20', height='20') square.grid(row=y, column=x) current_row.append(square) self.grid_squares.append(current_row) # noinspection PyAttributeOutsideInit def board_reset(self, config: Config = None): if len(self.grid_squares) > 0: self.board_frame.pack_forget() if config is not None: self.config = config else: config = self.config self.board = Board(config.x, config.y, config.n) self.board_render() def board_render(self): self.init_board_frame() self.update_counter() self.reset_bar_color() def update_counter(self): if self.board.rem_mines < 0: self.rem_mines_label.configure(foreground='red') else: self.rem_mines_label.configure(foreground='black') self.rem_mines.set('{}/{}'.format(self.board.rem_mines, self.board.num_mines)) root.update_idletasks() def easy(self): self.board_reset(EASY) def intermediate(self): self.board_reset(INTERMEDIATE) def hard(self): self.board_reset(HARD) def change_bar_color(self, is_fail: bool): color = 'red' if is_fail else 'green' for butt in self.win_lose: butt.configure(background=color) def reset_bar_color(self): for butt in self.win_lose: butt.configure(background=self.bar_colour) def custom(self): CustomPopUp(self) def load_board(self): if os.path.exists(self.SAVE_NAME): with open(self.SAVE_NAME) as file: self.board, exposed, markers = Board.from_json(file.read()) self.config = Config(self.board.x, self.board.y, self.board.num_mines) self.board_render() self.grid_squares[0][0].expose(None, exposed) for x, y, marc in markers: self.grid_squares[y][x].mark(None, marc) os.remove(self.SAVE_NAME) return self.board else: return None def save_board(self): with open(self.SAVE_NAME, 'wt') as file: json = self.board.to_json() file.write(json)
class Pomodoro(Frame): def __init__(self, parent, abspath): super().__init__(parent) self.root = parent self.abspath = abspath self.work_count = 0 # Tk variables self.tagVar = StringVar() self.tagVar.set("") self.actionVar = StringVar() self.actionVar.set(WORK) self.displayVar = StringVar() self.displayVar.set("00:00") self.initUI() def initUI(self): # toplevel self.root.title("PomodoroPy") self.root.resizable(0, 0) # main frame self.pack() self.timeLabel = Label(self, textvariable=self.displayVar) self.timeLabel["background"] = YELLOW self.timeLabel["padx"] = "10px" self.timeLabel["font"] = "helvetica 48 bold" self.timeLabel["fg"] = "gray" self.timeLabel.pack(expand=True, fill=tk.X) self.actionButton = Button(self) self.actionButton["text"] = WORK self.actionButton["font"] = "helvetica 16" self.actionButton["command"] = lambda: self.action( self.actionButton.cget("text")) self.actionButton.pack(expand=True, fill=tk.X) def action(self, action): if action == WORK: self.work_count += 1 self.timeLabel["fg"] = BLUE self.actionButton["text"] = PAUSE self.clock(T_WORK) self.actionButton["text"] = BREAK elif action == PAUSE: self.timeLabel["fg"] = RED self.actionButton["text"] = CONTINUE elif action == CONTINUE: self.timeLabel["fg"] = BLUE self.actionButton["text"] = PAUSE elif action == BREAK: self.actionButton["state"] = "disable" if self.work_count < 4: self.timeLabel["fg"] = GREEN self.clock(T_BREAK) elif self.work_count >= 4: self.timeLabel["fg"] = ORANGE self.clock(T_LONG) self.work_count = 0 self.actionButton["state"] = "normal" self.actionButton["text"] = WORK def clock(self, minutes): finish = time() + minutes * 60 while(time() < finish): self.actionButton.update() if self.actionButton.cget("text") != CONTINUE: seconds = finish - time() remaining = gmtime(seconds) self.displayVar.set(strftime("%M:%S", remaining)) self.update_idletasks() sleep(1) else: finish = time() + seconds self.playSound() def playSound(self): mixer.init() soundPath = path.join(self.abspath, "sounds/alert2.mp3") mixer.music.load(soundPath) mixer.music.play()
class ConstructorFrames: def __init__(self, tk: Manipulator): self.tk = tk self.__canvas = Canvas(tk, height=CANVAS_SIZE, width=CANVAS_SIZE) self.__frame_top = Frame(tk, bg=FRAME_COLOR, bd=2) self.__frame_top.place(relx=0.15, rely=0.05, relwidth=RELWIDTH, relheight=0.50) self.__frame_bottom_1 = Frame(tk, bg=FRAME_COLOR, bd=2) self.__frame_bottom_1.place(relx=0.15, rely=0.60, relwidth=RELWIDTH, relheight=0.05) self.__frame_bottom_2 = Frame(tk, bg=FRAME_COLOR, bd=2) self.__frame_bottom_2.place(relx=0.15, rely=0.65, relwidth=RELWIDTH, relheight=0.05) self.__frame_bottom_3 = Frame(tk, bg=FRAME_COLOR, bd=2) self.__frame_bottom_3.place(relx=0.15, rely=0.70, relwidth=RELWIDTH, relheight=0.05) self.__frame_bottom_3 = Frame(tk, bg=FRAME_COLOR, bd=2) self.__frame_bottom_3.place(relx=0.15, rely=0.75, relwidth=RELWIDTH, relheight=0.05) self.__frame_bottom_4 = Frame(tk, bg=FRAME_COLOR, bd=2) self.__frame_bottom_4.place(relx=0.15, rely=0.80, relwidth=RELWIDTH, relheight=0.05) self.__frame_bottom_5 = Frame(tk, bg=FRAME_COLOR, bd=2) self.__frame_bottom_5.place(relx=0.15, rely=0.85, relwidth=RELWIDTH, relheight=0.05) self.__frame_debug = Frame(tk, bg=FRAME_COLOR, bd=2) self.__frame_debug.place(relx=0.15, rely=0.90, relwidth=RELWIDTH, relheight=0.05) self.__scale_x = Scale(self.__frame_top, from_=MAX, to=MIN, length=LENGTH, label='x', command=self.__transmitting_value_x) self.__scale_y = Scale(self.__frame_top, from_=MAX, to=MIN, length=LENGTH, label='y', command=self.__transmitting_value_y) self.__scale_z = Scale(self.__frame_top, orient='horizontal', from_=MIN, to=MAX, length=LENGTH, label='z', command=self.__transmitting_value_z) self.__scan_vars_x_min = StringVar() self.__scan_vars_x_max = StringVar() self.__scan_vars_y_min = StringVar() self.__scan_vars_y_max = StringVar() self.__label_x_min = Label(self.__frame_bottom_1, text="x_min") self.__label_y_min = Label(self.__frame_bottom_2, text="y_min") self.__label_x_max = Label(self.__frame_bottom_3, text="x_max") self.__label_y_max = Label(self.__frame_bottom_4, text="y_max") self.__scan_vars_entry_x_min = Entry(self.__frame_bottom_1, textvariable=self.__scan_vars_x_min) self.__scan_vars_entry_y_min = Entry(self.__frame_bottom_2, textvariable=self.__scan_vars_y_min) self.__scan_vars_entry_x_max = Entry(self.__frame_bottom_3, textvariable=self.__scan_vars_x_max) self.__scan_vars_entry_y_max = Entry(self.__frame_bottom_4, textvariable=self.__scan_vars_y_max) self.__scan_vars_entry_x_min.place(width=5, height=5) self.__scan_vars_entry_x_max.place(width=5, height=5) self.__scan_vars_entry_y_min.place(width=5, height=5) self.__scan_vars_entry_y_max.place(width=5, height=5) self.__label_x_min.place(width=5, height=5) self.__label_x_max.place(width=5, height=5) self.__label_y_min.place(width=5, height=5) self.__label_y_max.place(width=5, height=5) self.__auto_on_off_btn = Button(self.__frame_bottom_4, text='go/stop auto_scan', bg='#595959', command=self.auto) self.__build_surface_btn = Button(self.__frame_bottom_1, text='on/off build surface', command=self.__build_surface) # не строит поверхноть, но копит данные о ней # self.__is_it_surface_btn = Button(self.__frame_bottom_1, text='is it surface', bg='#595959', # command=self.__is_it_surface) # кнопка для дебага self.__scan_mode = Button(self.__frame_bottom_2, text='on/off scan mode', command=self.__scan_mode) self.__stop_render_btn = Button(self.__frame_bottom_3, text='stop/go render', command=self.__stop_go_render) # stop/go __drow_graph: canvas.draw_idle() self.__snap_to_point_btn = Button(self.__frame_bottom_5, text='snap_to_point', command=self.__snap_to_point) # self.__remove_surface_btn = Button(self.__frame_bottom_2, text='remove_surface', command=self.__remove_surface) # self.__show_surface_btn = Button(self.__frame_bottom_2, text='show_surface', command=self.__show_surface) # self.__is_atom_btn = Button(self.__frame_bottom_2, text='is_atom', command=self.__is_atom) # кнопка для дебага self.__is_atom_captured_btn = Button(self.__frame_bottom_5, text='is_atom_captured', command=self.__is_atom_captured) self.__file_name = StringVar() self.__save_data_entry = Entry(self.__frame_debug, textvariable=self.__file_name) self.__save_data_entry.place(width=20, height=5) self.__save_data_btn = Button(self.__frame_debug, text='save data', command=self.__save_file) self.__load_data_entry = Entry(self.__frame_debug, textvariable=self.__file_name) self.__load_data_entry.place(width=20, height=5) self.__load_data_btn = Button(self.__frame_debug, text='load data', command=self.__load_file) self.default_bg = self.__stop_render_btn.cget("background") self.scanAlgorithm = ScanAlgorithms(SLEEP_BETWEEN_SCAN_ITERATION) self.__snap_to_point() def __transmitting_value_x(self, x: int): y = self.tk.graph.frame.atoms_logic.get_dto_val(DTO_Y) z = self.tk.graph.frame.atoms_logic.get_dto_val(DTO_Z) try: self.tk.graph.frame.atoms_logic.set_val_to_dto(DTO_X, (x, y, z)) except TouchingSurface as e: self.__snap_to_point() print(traceback.format_exc()) print(str(e)) def __transmitting_value_y(self, y: int): x = self.tk.graph.frame.atoms_logic.get_dto_val(DTO_X) z = self.tk.graph.frame.atoms_logic.get_dto_val(DTO_Z) try: self.tk.graph.frame.atoms_logic.set_val_to_dto(DTO_Y, (x, y, z)) except TouchingSurface as e: self.__snap_to_point() print(traceback.format_exc()) print(str(e)) def __transmitting_value_z(self, z: int): x = self.tk.graph.frame.atoms_logic.get_dto_val(DTO_X) y = self.tk.graph.frame.atoms_logic.get_dto_val(DTO_Y) try: self.tk.graph.frame.atoms_logic.set_val_to_dto(DTO_Z, (x, y, z)) except TouchingSurface as e: self.__snap_to_point() print(traceback.format_exc()) print(str(e)) def __snap_to_point(self): self.__scale_x.set(self.tk.graph.frame.atoms_logic.get_dto_val(DTO_X)) self.__scale_y.set(self.tk.graph.frame.atoms_logic.get_dto_val(DTO_Y)) self.__scale_z.set(self.tk.graph.frame.atoms_logic.get_dto_val(DTO_Z)) def __remove_surface(self): self.tk.graph.frame.remove_surface() def __show_surface(self): self.tk.graph.frame.show_surface() # def __is_atom(self): # if self.tk.graph.frame.atoms_logic.is_atom(): # self.tk.graph.frame.atoms_logic.set_is_atom(False) # else: # self.tk.graph.frame.atoms_logic.set_is_atom(True) def __is_atom_captured(self): if self.tk.graph.frame.atoms_logic.is_atom_captured(): self.tk.graph.frame.atoms_logic.set_is_atom_captured(False) else: self.tk.graph.frame.atoms_logic.set_is_atom_captured(True) def __build_surface(self): if self.tk.graph.frame.condition_build_surface: self.tk.graph.frame.condition_build_surface = False self.__remove_surface() else: self.tk.graph.frame.condition_build_surface = True self.__show_surface() def __is_it_surface(self): if self.tk.graph.frame.atoms_logic.is_surface(): self.tk.graph.frame.atoms_logic.set_is_surface(False) else: self.tk.graph.frame.atoms_logic.set_is_surface(True) def __scan_mode(self): if self.tk.graph.frame.atoms_logic.is_scan_mode(): self.tk.graph.frame.atoms_logic.set_scan_mode(False) else: self.tk.graph.frame.atoms_logic.set_scan_mode(True) def __save_file(self): GraphFrame.write_data_to_json_file(self.__file_name.get(), self.tk.graph.frame.get_data()) def __load_file(self): pass def auto(self): if self.scanAlgorithm.stop: self.scanAlgorithm.stop = False else: self.scanAlgorithm.stop = True vars = self.__get_vars() threading.Thread(target=self._go_auto, args=vars).start() def __get_vars(self) -> tuple: return ( int(self.__scan_vars_x_min.get().strip() if self.__scan_vars_x_min.get().strip() != '' else 0), int(self.__scan_vars_y_min.get().strip() if self.__scan_vars_x_min.get().strip() != '' else 0), int(self.__scan_vars_x_max.get().strip() if self.__scan_vars_x_min.get().strip() != '' else 0), int(self.__scan_vars_y_max.get().strip() if self.__scan_vars_x_min.get().strip() != '' else 0), ) def _go_auto(self, x_min: int = 0, y_min: int = 0, x_max: int = FIELD_SIZE, y_max: int = FIELD_SIZE) -> None: get_val_func = self.tk.graph.frame.atoms_logic.get_dto_val self.tk.graph.frame.atoms_logic.set_val_to_dto( DTO_X, ( x_max, get_val_func(DTO_Y), get_val_func(DTO_Z) ) ) set_x_func = self.tk.graph.frame.atoms_logic.set_val_dto_curried(DTO_X) set_y_func = self.tk.graph.frame.atoms_logic.set_val_dto_curried(DTO_Y) set_z_func = self.tk.graph.frame.atoms_logic.set_val_dto_curried(DTO_Z) self.scanAlgorithm.scan( get_val_func, set_x_func, set_y_func, set_z_func, x_min=x_min, y_min=y_min, x_max=x_max, y_max=y_max, ) def __stop_go_render(self): if self.tk.graph.frame.quit: self.tk.graph.frame.quit = False threading.Thread(target=self.tk.graph.frame.draw_graph).start() else: self.tk.graph.frame.quit = True def pack(self): self.__build_surface_btn.bind('<Button-1>', lambda e, cause='tk.graph.frame.condition_build_surface': self.change_button(e, cause)) self.__scan_mode.bind('<Button-1>', lambda e, cause='tk.graph.frame.condition_scan_mode': self.change_button(e, cause)) # self.__is_it_surface_btn.bind('<Button-1>', # lambda e, cause='tk.graph.frame.condition_is_it_surface': self.change_button(e, cause)) self.__stop_render_btn.bind('<Button-1>', lambda e, cause='tk.graph.frame.quit': self.change_button(e, cause)) self.__auto_on_off_btn.bind('<Button-1>', lambda e, cause='scanAlgorithm.stop': self.change_button(e, cause)) self.__canvas.pack() self.__scale_x.pack(side=c.LEFT, padx=10) self.__scale_y.pack(side=c.LEFT, padx=10) self.__scale_z.pack(side=c.BOTTOM, pady=5) self.__label_x_min.pack(side=c.LEFT) self.__label_x_max.pack(side=c.LEFT) self.__label_y_min.pack(side=c.LEFT) self.__label_y_max.pack(side=c.LEFT) self.__scan_vars_entry_x_min.pack(side=c.LEFT) self.__scan_vars_entry_y_min.pack(side=c.LEFT) self.__scan_vars_entry_x_max.pack(side=c.LEFT) self.__scan_vars_entry_y_max.pack(side=c.LEFT) self.__auto_on_off_btn.pack(side=c.LEFT) self.__stop_render_btn.pack(side=c.RIGHT, padx=5) self.__scan_mode.pack(side=c.RIGHT, padx=5) self.__build_surface_btn.pack(side=c.RIGHT, padx=5) # self.__is_it_surface_btn.pack(side=c.LEFT, padx=5) self.__is_atom_captured_btn.pack(side=c.RIGHT) self.__snap_to_point_btn.pack(side=c.RIGHT, padx=5) # self.__remove_surface_btn.pack(side=c.LEFT, padx=50) # self.__show_surface_btn.pack(side=c.LEFT) # self.__is_atom_btn.pack(side=c.LEFT, padx=5) self.__save_data_entry.pack(side=c.LEFT) self.__save_data_btn.pack(side=c.LEFT, padx=5) self.__load_data_entry.pack(side=c.LEFT, padx=5) self.__load_data_btn.pack(side=c.LEFT) def scale_set(self, x, y, z): self.__scale_x.set((x, y, z)) self.__scale_y.set((x, y, z)) self.__scale_z.set((x, y, z)) def change_button(self, event, cause): cause = { 'scanAlgorithm.stop': {'condition': not self.scanAlgorithm.stop, 'button': self.__auto_on_off_btn}, 'tk.graph.frame.quit': {'condition': not self.tk.graph.frame.quit, 'button': self.__stop_render_btn}, 'tk.graph.frame.condition_build_surface': {'condition': self.tk.graph.frame.condition_build_surface, 'button': self.__build_surface_btn}, 'tk.graph.frame.condition_scan_mode': {'condition': self.tk.graph.frame.atoms_logic.is_scan_mode(), 'button': self.__scan_mode}, # 'tk.graph.frame.condition_is_it_surface': {'condition': self.tk.graph.frame.atoms_logic.is_it_surface(), 'button': self.__is_it_surface_btn}, }.get(cause) self.cycle_change_bg(cause) def cycle_change_bg(self, cause): if cause['condition']: if self.default_bg == '#595959': cause['button'].configure(bg='#d9d9d9') else: cause['button'].configure(bg='#595959') else: cause['button'].configure(bg=self.default_bg)
class caesarCipherGUI(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.constructGUI() def constructGUI(self): self.parent.title("Encryption Software") self.parent.geometry("700x700+100+100") encryptLabel = Label(self.parent, text="Message to Encrypt") encryptLabel.place(x=10, y=10) decryptLabel = Label(self.parent, text="Message to Decrypt") decryptLabel.place(x=570, y=10) #Encrypt/Decrypt Text Boxes self.encryptText = Text(self.parent, width=40, height=20, wrap='word') self.encryptText.place(x=10, y=40) self.resultText = Text(self.parent, width=40, height=20, wrap='word') self.resultText.place(x=360, y=40) #Encrypt/Decrypt Buttons self.encryptButton = Button(self.parent, text='Encrypt Message', command=self.encryptPressed) self.encryptButton.place(x=80, y=400) self.decryptButton = Button(self.parent, text='Decrypt Message', command=self.decryptPressed) self.decryptButton.place(x=500, y=400) #Keypad self.button1 = Button(self.parent, text='1') self.button1.config( command=lambda: self.numberPressed(self.button1.cget('text'))) self.button1.place(x=325, y=530) self.button2 = Button(self.parent, text='2') self.button2.config( command=lambda: self.numberPressed(self.button2.cget('text'))) self.button2.place(x=350, y=530) self.button3 = Button(self.parent, text='3') self.button3.config( command=lambda: self.numberPressed(self.button3.cget('text'))) self.button3.place(x=375, y=530) self.button4 = Button(self.parent, text='4') self.button4.config( command=lambda: self.numberPressed(self.button4.cget('text'))) self.button4.place(x=325, y=565) self.button5 = Button(self.parent, text='5') self.button5.config( command=lambda: self.numberPressed(self.button5.cget('text'))) self.button5.place(x=350, y=565) self.button6 = Button(self.parent, text='6') self.button6.config( command=lambda: self.numberPressed(self.button6.cget('text'))) self.button6.place(x=375, y=565) self.button7 = Button(self.parent, text='7') self.button7.config( command=lambda: self.numberPressed(self.button7.cget('text'))) self.button7.place(x=325, y=600) self.button8 = Button(self.parent, text='8') self.button8.config( command=lambda: self.numberPressed(self.button8.cget('text'))) self.button8.place(x=350, y=600) self.button9 = Button(self.parent, text='9') self.button9.config( command=lambda: self.numberPressed(self.button9.cget('text'))) self.button9.place(x=375, y=600) self.button0 = Button(self.parent, text='0') self.button0.config( command=lambda: self.numberPressed(self.button0.cget('text'))) self.button0.place(x=350, y=635) self.numpadBackspace = Button(self.parent, text='<--', command=self.backspacePressed) self.numpadBackspace.place(x=300, y=635) self.numpadClear = Button(self.parent, text='CLR', command=self.clearPressed) self.numpadClear.place(x=380, y=635) self.numpadDisplay = Text(self.parent, width=12, height=1, state='disabled') self.numpadDisplay.place(x=310, y=490) numpadLabel = Label(self.parent, text='Enter key for Encryption and Decryption') numpadLabel.place(x=260, y=460) def encryptPressed(self): PIN = self.numpadDisplay.get('1.0', 'end-1c') if len(PIN) > 0: message = self.encryptText.get('1.0', 'end-1c') encrypted = cp.encrypt(message, int(PIN)) self.resultText.delete('1.0', 'end') self.resultText.insert('1.0', encrypted) def decryptPressed(self): PIN = self.numpadDisplay.get('1.0', 'end-1c') if len(PIN) > 0: message = self.resultText.get('1.0', 'end-1c') decrypted = cp.decrypt(message, int(PIN)) self.encryptText.delete('1.0', 'end') self.encryptText.insert('1.0', decrypted) def numberPressed(self, num): PIN = self.numpadDisplay.get('1.0', 'end-1c') if len(PIN) < 12: self.numpadDisplay.config(state='normal') self.numpadDisplay.insert('end', num) print(int(num)) self.numpadDisplay.config(state='disabled') def backspacePressed(self): PIN = self.numpadDisplay.get('1.0', 'end-1c') if len(PIN) > 0: self.numpadDisplay.config(state='normal') self.numpadDisplay.delete('1.0', 'end-1c') self.numpadDisplay.insert('1.0', PIN[:-1]) self.numpadDisplay.config(state='disabled') def clearPressed(self): self.numpadDisplay.config(state='normal') self.numpadDisplay.delete('1.0', 'end-1c') self.numpadDisplay.config(state='disabled')
class ButtonControl: ''' class to define button control, which are self explantory Button actions are equivalent to Space, (s, S), (w, W), (c, C), (m, M) and Escape. When the Exit window is pressed program is ended. Methods: - buttons - in_button_area - out_button_area - color_buttons - remove_color_buttons - _repr__ ''' def buttons(self): ''' definition and display of buttons ''' self.logger.info(f'==> button called: {setup.b_w_o}') self.setup_button = Button(self.root, text='Setup', relief='raised', width=BWIDTH, command=self.setup_status) self.setup_button.place(x=setup.b_w_o[0][0], y=setup.b_w_o[0][1]) self.setup_button.bind('<Enter>', self.in_button_area) self.setup_button.bind('<Leave>', self.out_button_area) self.default_button_bg = self.setup_button.cget('background') self.pause_button = Button(self.root, text='Pause', relief='sunken', width=BWIDTH, command=self.pause_status, bg=self.select_color) self.pause_button.place(x=setup.b_w_o[1][0], y=setup.b_w_o[1][1]) self.pause_button.bind('<Enter>', self.in_button_area) self.pause_button.bind('<Leave>', self.out_button_area) self.clear_button = Button(self.root, text='Clear', relief='raised', width=BWIDTH, command=self.clear_status) self.clear_button.place(x=setup.b_w_o[2][0], y=setup.b_w_o[2][1]) self.clear_button.bind('<Enter>', self.in_button_area) self.clear_button.bind('<Leave>', self.out_button_area) self.monitor_button = Button(self.root, text='Monitor', relief='sunken', width=BWIDTH, command=self.monitor_status, bg=self.select_color) self.monitor_button.place(x=setup.b_w_o[3][0], y=setup.b_w_o[3][1]) self.monitor_button.bind('<Enter>', self.in_button_area) self.monitor_button.bind('<Leave>', self.out_button_area) self.select_button = Button(self.root, text='Select', relief='raised', width=BWIDTH, command=self.select_status) self.select_button.place(x=setup.b_w_o[4][0], y=setup.b_w_o[4][1]) self.select_button.bind('<Enter>', self.in_button_area) self.select_button.bind('<Leave>', self.out_button_area) self.exit_button = Button(self.root, text='Exit', relief='raised', width=BWIDTH, command=self.exit_program) self.exit_button.place(x=setup.b_w_o[5][0], y=setup.b_w_o[5][1]) self.exit_button.bind('<Enter>', self.in_button_area) self.exit_button.bind('<Leave>', self.out_button_area) def in_button_area(self, event): ''' set in_button to True, mouse pointer is in a button area ''' self.in_button = True def out_button_area(self, event): ''' set in_button to False, mouse pointer has left a button area ''' self.in_button = False def color_buttons(self): ''' Method to define and display the color buttons ''' self.color_button = {} for color in setup.color_buttons: self.color_button[color] =\ Button(self.root, bg=tools.hex_color(color), activebackground=tools.hex_color(color), borderwidth=2, relief='raised', width=1, command=lambda x=color: self.color_select(x)) self.color_button[color].place(x=setup.color_buttons[color][0], y=setup.color_buttons[color][1]) self.color_button[color].bind('<Enter>', self.in_button_area) self.color_button[color].bind('<Leave>', self.out_button_area) def remove_color_buttons(self): ''' Methond to remove the color buttons ''' for color in setup.color_buttons: self.color_button[color].destroy() def __repr__(self): ''' method to represent the contents of this class ''' s = ''.join('{} = {}\n'.format(k, v) for k, v in self.__dict__.items()) s = ('\n{self.__module__}/{self.__class__.__name__}:\n'.format( self=self)) + s return s