def __init__(self, parent=None): QtGui.QWidget.__init__(self) self.parent = parent self.setWindowTitle('imrenderin') ## Widgets self.menu_bar = MenuBar(self) self.menu_bar.setFixedHeight(25) self.status_bar = StatusBar(self) self.status_bar.setFixedHeight(35) ## Redirect stdout,stderr to dialog self.console = ConsoleDialog(sys.stdout) sys.stdout = self.console sys.stderr = self.console ## UI Elements self.display = Display(self) self.controls = DefaultUI(self, self.display) ## Layout vbox = QtGui.QVBoxLayout(self) vbox.addWidget(self.menu_bar) vbox.addWidget(self.controls) vbox.addWidget(self.status_bar) vbox.setSpacing(2) vbox.setContentsMargins(2, 2, 2, 2) self.setLayout(vbox) self.setMinimumWidth(200) self.setMinimumHeight(150) self.resize(_width, _height)
def __init__(self, game_board, game_controller, master, settings): # # ─── ASSIGN REFERENCE VARIABLES ────────────────────────────────── self.board = game_board self.controller = game_controller # # ─── EXTRACT SETTINGS ──────────────────────────────────────────── self.height = settings['window_dimension'] self.width = settings['window_dimension'] self.game_size = settings['game_size'] self.tile_dimension = settings['tile_dimension'] self.mode = settings['game_mode'] self.difficulty = settings['game_difficulty'] self.position_service = PositionService(self.mode, self.tile_dimension) # # ─── CALCULATE CANVAS DIMENSIONS ───────────────────────────────── canvas_dimension = self.tile_dimension * self.game_size canvas_width = canvas_dimension canvas_height = canvas_dimension if self.mode == "HEX": canvas_height = canvas_dimension * 0.75 + self.tile_dimension / 2 canvas_width += self.tile_dimension / 2 # # ─── DEFINE THE FRAME ──────────────────────────────────────────── self.frame = Frame(master, background="#F19C79", borderwidth=23) self.frame.pack() # # ─── LOAD SQUARE TILE SET ───────────────────────────────────────── self.square_up = PhotoImage(file="assets/square_up.png") self.square_down = PhotoImage(file="assets/square_down.png") self.square_bomb = PhotoImage(file="assets/square_bomb.png") self.square_cover = PhotoImage(file="assets/square_cover.png") # # ─── LOAD HEXAGONAL TILE SET ───────────────────────────────────── self.hex_up = PhotoImage(file="assets/hex_up.png") self.hex_down = PhotoImage(file="assets/hex_down.png") self.hex_bomb = PhotoImage(file="assets/hex_bomb.png") self.hex_cover = PhotoImage(file="assets/hex_cover.png") # # ─── CREATE COMPONENTS ─────────────────────────────────────────── self.canvas = Canvas(self.frame, width=canvas_width, height=canvas_height, background="#F19C79", bd=0, highlightthickness=0) self.canvas.bind("<Button-1>", self.callback_toggle) self.canvas.bind("<Button-3>", self.callback_cover) self.score_board = ScoreBoard(self.frame, self.width, self.difficulty) self.score_board.pack(side="top") self.canvas.pack() self.render_handler() self.menubar = MenuBar(self.frame, self) self.menubar.pack(side="bottom", pady=(40,0))
def __init__(self): # On définie la fenetre de jeu Frame.__init__(self) # Et on lui donne les dimensions initiale self.master.geometry("900x600") # On donne ensuite un titre à cette fenêtre self.master.title(" Jeu de Demineur") # On créer une instance mbar de MenuBar # C'est la barre qui se situe en haut de la fenêtre et # qui permet de paramètrer le jeu. self.mbar = MenuBar(self) # On place ceci en indiquant quelques paramètres. self.mbar.pack(side=TOP, expand=NO, fill=X) # De même on créer une instance jeu de Jeu. # C'est le cadre de jeu , celui sur lequel la grille # est dessinée. self.jeu = Jeu(self) # On place ceci en indiquant quelques paramètres # notemment celui expand qui permet au cadre de prendre # le maximum de place self.jeu.pack( side=LEFT, expand=YES, fill=BOTH, ) # De même on créer une instance affichage d'Afficahge # C'est le cadre situé à droite de la fenêtre de jeu # il permet un affichage de l'évolution de la partie. self.affichage = Affichage(self) # On place ceci en indiquant quelques paramètres self.affichage.pack(side=RIGHT, expand=NO, fill=BOTH) # Ici on utilise la fonction pack du module tkinter. self.pack() # Pour lancer la musique pendant le jeu on a besoin de # lancer une fonction particulière en fonction du système # d'exploitation sur lequel le programme tourne et donc # d'enregistrer le nom du système dans une variable global # Ici on va determiner sur quelle systeme le jeu tourne global operatingSystem # On initialise une variable qui va enregistrer le nom du # systeme operatingSystem = 'none' # On attribut a cette variable le nom du system grace a la # librairie platform operatingSystem = platform.system() print('Demineur : Le jeu tourne actuellement sous :', operatingSystem)
def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.title("ScriptLauncher by FARBEX97") self.shared_data = { "script_name": tk.StringVar(), "src_dir": json.load(open("config.json"))["src_dir"] } # MenuBar menubar = MenuBar(self) self.config(menu=menubar) # MainFrame config container = MainFrame(self) self.geometry("500x200") # Window style config s = ttk.Style() s.configure(".", background="#c0c5ce") s.configure("TButton", background="#343d46") # Load all frames self.frames = {} for F in (StartPage, RunScriptPage): frame = F(container, self) self.frames[F] = frame frame.grid(row=0, column=0, sticky="nsew") self.show_frame(StartPage)
def __init__(self, parent=None, width=800, height=800): """ Initialisation parent : une application width,height : dimension de l'oscilloscpe """ Frame.__init__(self) self.master.title("Oscilloscope - Diquélou - Toscer") # doit-on afficher la courbe de lissajoux self.drawXY = IntVar() # Modele self.time = 0 # gestion des signaux X et Y self.signal_X = None self.signal_Y = None self.signal_XY = None # Vues self.view = Screen(parent=self) self.lissajoux = Screen(parent= self) # Controleurs self.control_time = TimeBase(parent=self) self.control_X = Generator(self,'X') self.control_Y = Generator(self, 'Y') # menu menuBar = MenuBar(self) menuBar.pack(fill="x"); # Affichage Vues, Controleurs self.view.pack(fill="both") self.control_time.pack(side="left", fill="y") self.control_X.pack(side="left",fill="y") self.lissajoux.pack(fill="both", side="left", expand=1) self.control_Y.pack(side="right", fill="both") self.configure(width=width, height=height) self.master.protocol("WM_DELETE_WINDOW", self.quitter)
def __init__(self): Gtk.Window.__init__(self) self.set_title("TimeControl") self.set_icon_from_file( os.path.join(BASE_PATH, "img", "timecontrol.png")) self.set_resizable(True) self.set_border_width(2) self.set_position(Gtk.WindowPosition.CENTER) base_hbox = Gtk.HBox() self.menuBar = MenuBar() self.calendario = Gtk.Calendar() self.calendario.connect('day_selected', self.__changed_date) frame = Gtk.Frame() frame.set_label(' Ingreso de Datos: ') frame.set_border_width(15) hbox = Gtk.HBox() hbox.set_border_width(15) self.tabla = Tabla() hbox.pack_start(self.tabla, True, False, 0) frame.add(hbox) vbox = Gtk.VBox() vbox.pack_start(self.menuBar, False, False, 0) vbox.pack_start(self.calendario, True, False, 0) vbox.pack_start(frame, True, False, 0) self.tablasemana = TablaSemana() base_hbox.pack_start(vbox, True, True, 0) base_hbox.pack_start(self.tablasemana, True, True, 0) self.add(base_hbox) self.connect("delete-event", self.__salir) self.menuBar.connect("newuser", self.__newUser) self.tabla.connect("viewuser", self.__viewUser) self.tabla.connect('save', self.__guardar) self.show_all()
def __init__(self): Gtk.Window.__init__(self) self.set_title("TimeControl") self.set_icon_from_file( os.path.join(BASE_PATH, "img", "timecontrol.png")) self.set_resizable(True) self.set_size_request(640, 480) self.set_border_width(2) self.set_position(Gtk.WindowPosition.CENTER) self.menuBar = MenuBar() self.info = Info() self.notebook = Notebook() panel = Gtk.Paned(orientation=Gtk.Orientation.HORIZONTAL) panel.pack1(self.notebook, resize=True, shrink=False) panel.pack2(self.info, resize=False, shrink=True) vbox = Gtk.VBox() vbox.pack_start(self.menuBar, False, False, 0) vbox.pack_start(panel, True, True, 0) self.add(vbox) self.show_all() self.connect("delete-event", self.__salir) self.menuBar.connect("adduser", self.__newUser) self.menuBar.connect("viewuser", self.__viewUser) self._current_user = '' self._current_dict = OrderedDict() self.notebook.hide() # Se hace visible cuando se cargan los datos self.info.frame.hide() # Se hace visible cuando se cargan los datos self.info.saldo.hide() # Se hace visible cuando se cargan los datos self.notebook.connect('switch_page', self.__switch_page) self.notebook.connect('updateuser', self.__update)
def Init(): RootWindow.root=Tk() RootWindow.root.title("Generator wizytówek") RootWindow.root.iconbitmap(r"ikona.ico") MainWindow.Init(RootWindow.root) EntryWindow.Init() ConfigFile.Read(RootWindow.root) if ConfigFile.lastTemplate!="": error=TemplateFile.Read(ConfigFile.lastTemplate,RootWindow.root) if error==1: ConfigFile.lastTemplate="" RootWindow.newTemp=0 MenuBar.Init(RootWindow.root) RootWindow.root.config(menu=MenuBar.GetMenu()) RootWindow.root.protocol("WM_DELETE_WINDOW",RootWindow.Close)
def __init__(self): super(EClassWindow, self).__init__(None, -1, 'EClass') self.SetClientSizeWH(800, 600) self.SetBackgroundColour('#FFFFFF') self.menuBar = MenuBar(self) self.CreateStatusBar() self.initialPrompt = InitialPrompt(self) self.importPresentation = ImportPresentation(self) self.Bind(wx.EVT_CLOSE, self.onClose) self.Centre() self.Show()
def __init__(self, get_session, get_chat): Gtk.Window.__init__(self, title="emesene log viewer") self.get_session = get_session self.get_chat = get_chat self.connect("delete-event", Gtk.main_quit) self.resize(300,500) self.set_position(Gtk.WindowPosition.CENTER) self.hpaned = Gtk.HPaned() view = Viewer() self.scroll_view = Gtk.ScrolledWindow() self.scroll_view.set_border_width(1) self.scroll_view.add(view) img_remove = Gtk.Image() img_remove.set_from_stock(Gtk.STOCK_CLOSE, Gtk.IconSize.MENU) self.b_remove = Gtk.Button() self.b_remove.set_image(img_remove) self.b_alig = Gtk.Alignment(xalign=1, yalign=1, xscale=0.0, yscale=1.0) self.b_alig.add(self.b_remove) self.b_remove.connect('clicked', self._clicked) self.view_box = Gtk.VBox(False,1) self.view_box.set_border_width(8) self.view_box.pack_start(self.b_alig, False, False, 1) self.view_box.pack_start(self.scroll_view, True, True, 1) contacts = ContactList(view.load_contact_log, self.get_chat, self.hpaned, self.view_box, self.resize) mb = MenuBar(self.get_session, contacts.fill_contact_list, self.show_widget, self.unload, self._about) self.login = Login(self.get_session, contacts.fill_contact_list, self.show_widget, self.unload, mb.filemenu, mb.unload_item) scroll_contact = Gtk.ScrolledWindow() scroll_contact.set_border_width(1) scroll_contact.add(contacts) self.hpaned.add1(scroll_contact) self.hpaned.set_position(250) self.vbox = Gtk.VBox(False, 7) self.vbox.pack_start(mb, False, False, 1) self.vbox.pack_start(self.login, False, False, 10) self.add(self.vbox) self.show_all()
def __init__(self, parent, *args, **kwargs): tk.Frame.__init__(self, parent, *args, **kwargs) self.parent = parent LC_result = None old_age_choice = None old_gender_choices = None old_smk_years_choices = None old_qt_years_choices = None old_cpd_choices = None old_race_choices = None old_emp_choices = None old_flt_choices = None old_bmi_entry = None old_edu6_choices = None # init reading data table life_table = read_life_table_from_file( "input/Copy of Lung cancer_7-19-2019.xlsx") local_cancer = read_LC_table_from_file( "input/Copy of Lung cancer_7-19-2019.xlsx") regional_cancer = read_regional_cancer_table_from_file( "input/Copy of Lung cancer_7-19-2019.xlsx") distant_cancer = read_distant_cancer_table_from_file( "input/Copy of Lung cancer_7-19-2019.xlsx") # initiate the basehaz and the model_coef array to calculate the LCRAT_1mon_risk basehaz_G = get_basehaz_from_file("input/lcrisk_tool.xlsx", 6) basehaz_H = get_basehaz_from_file("input/lcrisk_tool.xlsx", 7) basehaz_J = get_basehaz_from_file("input/lcrisk_tool.xlsx", 9) model_coef_D = get_model_coef_from_file("input/lcrisk_tool.xlsx", 3) model_coef_F = get_model_coef_from_file("input/lcrisk_tool.xlsx", 5) self.memubar = MenuBar(parent) self.statusbar = StatusBar(self) self.toolbar = ToolBar(self) self.navbar = NavigationBar(self) self.main = Main(root) self.statusbar.pack(side="bottom", fill="x") self.toolbar.pack(side="top", fill="x") self.navbar.pack(side="left", fill="y") self.main.pack(side="right", fill="both", expand=True)
def __init__(self, master): master.title("TSM Image View") # Create frames for right and left "columns" of the window frame_left = Frame(master) frame_right = Frame(master) # Default start pic/array a = np.fromfile('wa_cl99122.img', dtype='uint8') self.file_path = None # Menu MenuBar(self, master) # Create format frame with widgets frame_format = Frame(frame_left) # Use self(tsm_imageview) as parameter to call display method self.frameF = FrameFormat(self, master, frame_format) # Create histogram frame_hist = Frame(frame_left) self.frameH = FrameHist(frame_hist, a) # Create map frame with widgets frame_map = Frame(frame_right) self.frameV = FrameView(frame_map, a) # Create scale frame with widgets frame_scale = Frame(frame_left) self.frameS = FrameScale(a, frame_scale, self.frameV) # Create combobox for colormap selection CmapBox(frame_right, self.frameV) # Layout - widget positioning frame_left.pack(side=LEFT, fill=Y, padx=5, pady=5) frame_right.pack(fill=BOTH, expand=True, padx=5, pady=5) frame_format.pack(fill=X, expand=True) frame_hist.pack(fill=Y, expand=True, padx=10, pady=20) frame_scale.pack(side=BOTTOM, expand=True) frame_map.pack(fill=BOTH, expand=True)
def Init(): FileManager.ConfigFile.Read() RootWindow.root = Tk() RootWindow.root.title("Menedżer urlopów") ikonaDir = FileManager.ConfigFile.mainDirectory + 'logo_ikona.ico' #RootWindow.root.iconbitmap(r'logo_ikona.ico') RootWindow.root.iconbitmap(ikonaDir) FileManager.InputFile.root = RootWindow.root FileManager.OutputFile.root = RootWindow.root FileManager.FileStatus.root = RootWindow.root RootWindow.mainWnd = MainWindow(RootWindow.root) RootWindow.menuBar = MenuBar(RootWindow.root) RootWindow.root.config(menu=RootWindow.menuBar.GetMenuBar()) RootWindow.root.protocol("WM_DELETE_WINDOW", RootWindow.CloseMainWindow) RootWindow.currentWidget = None RootWindow.root.bind_all("<B1-Motion>", RootWindow.MouseLeftButtonMove) RootWindow.root.bind_all("<Button-1>", RootWindow.MouseLeftButtonPressed) if FileManager.ConfigFile.lastDataFilename != "" and len( sys.argv) <= 1: inFile = FileManager.InputFile( FileManager.ConfigFile.lastDataFilename) inFile.ClearAndWriteDataToDataEngine() MainTable.ChoosePerson.UpdatePersonList() elif len(sys.argv) > 1: print(sys.argv[1]) print((sys.argv[1])[-4:]) if ((sys.argv[1])[-4:] == ".bls"): FileManager.ConfigFile.lastDataFilename = sys.argv[1] inFile = FileManager.InputFile(sys.argv[1]) inFile.ClearAndWriteDataToDataEngine() MainTable.ChoosePerson.UpdatePersonList()
logger.info('Get error messages displayed on fields') self.wait_UI(self.__field_error_loc) field_errors = self.find_elements(*self.__field_error_loc) error_messages = [] for error in field_errors: error_messages.append(error.text) return error_messages if __name__ == '__main__': webdriver = webdriver.Firefox() webdriver.maximize_window() webdriver.implicitly_wait(10) login_page = LoginPage(webdriver) login_page.login() menu_bar = MenuBar(webdriver) menu_bar.wait_UI(menu_bar.menu_button_loc) menu_bar.action_toggle_menu() time.sleep(1) menu_bar.action_expand_app_group('Supply Chain Advantage') menu_bar.action_expand_menu('Advantage Dashboard') menu_bar.action_expand_menu('searchTest', False, 'search test') searchPage = SearchPage(webdriver) print(searchPage.get_page_title()) time.sleep(1) print(searchPage.get_all_labels_name(1)) searchPage.action_searchlike_input('searchLike', 'abc', 2, 'Exactly') searchPage.action_listbox_select('ListBox', 'Warehouse 02', 2) searchPage.action_checkbox_check('checkbox2', 2) searchPage.action_dropdown_input('time', '1:30 AM', 2) menu_bar.action_toggle_menu()
#clean up and add clicked element to the key Entry setGet.enterKeyEntry.delete(0, END) setGet.enterKeyEntry.insert(0, keyValue) #enter value for the selected Key setGet.findValue("<ButtonRelease-1>") #creating a Treeview tree = MyTreeVeiw(frameDB, redisClient) #fill the tree tree.treeKeyItems.bind('<Double-1>', selectItem) #draw SetGet frame setGet = RedisSetGet(frameSetGet, redisClient, tree) #creating a menu menuMain = MenuBar(root, redisClient, tree) #creating CLI window redisCLI = RedisCLI(frameCLI, redisClient, tree, host, port) #Frame Button Section #close Button closeButton = Button(frameButtons, borderwidth=5, text="Close") closeButton.pack(side=RIGHT) #close window def closeWindow(event): root.destroy() #when you click close button closeButton.bind("<Button-1>", closeWindow)
class TimeControl(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.set_title("TimeControl") self.set_icon_from_file( os.path.join(BASE_PATH, "img", "timecontrol.png")) self.set_resizable(True) self.set_size_request(640, 480) self.set_border_width(2) self.set_position(Gtk.WindowPosition.CENTER) self.menuBar = MenuBar() self.info = Info() self.notebook = Notebook() panel = Gtk.Paned(orientation=Gtk.Orientation.HORIZONTAL) panel.pack1(self.notebook, resize=True, shrink=False) panel.pack2(self.info, resize=False, shrink=True) vbox = Gtk.VBox() vbox.pack_start(self.menuBar, False, False, 0) vbox.pack_start(panel, True, True, 0) self.add(vbox) self.show_all() self.connect("delete-event", self.__salir) self.menuBar.connect("adduser", self.__newUser) self.menuBar.connect("viewuser", self.__viewUser) self._current_user = '' self._current_dict = OrderedDict() self.notebook.hide() # Se hace visible cuando se cargan los datos self.info.frame.hide() # Se hace visible cuando se cargan los datos self.info.saldo.hide() # Se hace visible cuando se cargan los datos self.notebook.connect('switch_page', self.__switch_page) self.notebook.connect('updateuser', self.__update) def __update(self, widget, _dict): self.info.update(_dict) def __switch_page(self, widget, widget_child, indice): self.info.switch_page_and_set_user(self._current_user, indice, self._current_dict) def __viewUser(self, widget, name): self._current_user = name self._current_dict = getDataUser(self._current_user) self.notebook.set_data(self._current_user, self._current_dict) self.info.switch_page_and_set_user(self._current_user, 0, self._current_dict) self.notebook.show_all() # Se hace visible cuando se cargan los datos self.info.show_all() # Se hace visible cuando se cargan los datos def __newUser(self, widget, name): if adduser(name): self.menuBar.adduser(name) else: dialog = Gtk.Dialog(parent=self.get_toplevel(), flags=Gtk.DialogFlags.MODAL, buttons=["OK", Gtk.ResponseType.OK]) dialog.set_border_width(15) label = Gtk.Label("Este Funcionario ya Existe") dialog.vbox.pack_start(label, True, True, 5) dialog.vbox.show_all() dialog.run() dialog.destroy() self.__viewUser(None, name) def __salir(self, widget=None, senial=None): Gtk.main_quit() sys.exit(0)
class View: # # ─── CALLBACK FOR LEFT CLICKING THE CANVAS ────────────────────────────────────── # def callback_toggle(self, event): # # ─── DISABLE THE BOARD ON LOSS ─────────────────────────────────── if self.board.get_state_loss(): return NONE if self.board.get_state_win(): return NONE # # ─── MUTATE THE BOARD THROUGH THE CONTROLLER ───────────────────── coordinates = self.position_service.calculate_coordinates(event.x, event.y) self.controller.activate(coordinates[0], coordinates[1]) # # ─── BEFORE REDRAW CHECK IF THE GAME IS OVER ───────────────────── if self.board.get_state_loss(): self.draw_mines() self.score_board.stop_timer(False) tkMsg.showinfo("Game Over", "You Lost the Game!") else: self.render_handler(); if self.board.get_state_win(): self.score_board.stop_timer() win_string = "Congratulations!\n You won the game with a final score of:{score}" display_string = win_string.format(score=self.score_board.get_score()) tkMsg.showinfo("Game Win!", display_string) def callback_cover(self, event): if self.board.get_state_loss(): return NONE if self.board.get_state_win(): return NONE # # ─── MUTATE THE BOARD THROUGH THE CONTROLLER ───────────────────── coordinates = self.position_service.calculate_coordinates(event.x, event.y) self.controller.cover(coordinates[0], coordinates[1]) self.render_handler() if self.board.get_state_win(): self.score_board.stop_timer() win_string = "Congratulations!\n You won the game with a final score of:{score}" display_string = win_string.format(score=self.score_board.get_score()) tkMsg.showinfo("Game Win!", display_string) def __init__(self, game_board, game_controller, master, settings): # # ─── ASSIGN REFERENCE VARIABLES ────────────────────────────────── self.board = game_board self.controller = game_controller # # ─── EXTRACT SETTINGS ──────────────────────────────────────────── self.height = settings['window_dimension'] self.width = settings['window_dimension'] self.game_size = settings['game_size'] self.tile_dimension = settings['tile_dimension'] self.mode = settings['game_mode'] self.difficulty = settings['game_difficulty'] self.position_service = PositionService(self.mode, self.tile_dimension) # # ─── CALCULATE CANVAS DIMENSIONS ───────────────────────────────── canvas_dimension = self.tile_dimension * self.game_size canvas_width = canvas_dimension canvas_height = canvas_dimension if self.mode == "HEX": canvas_height = canvas_dimension * 0.75 + self.tile_dimension / 2 canvas_width += self.tile_dimension / 2 # # ─── DEFINE THE FRAME ──────────────────────────────────────────── self.frame = Frame(master, background="#F19C79", borderwidth=23) self.frame.pack() # # ─── LOAD SQUARE TILE SET ───────────────────────────────────────── self.square_up = PhotoImage(file="assets/square_up.png") self.square_down = PhotoImage(file="assets/square_down.png") self.square_bomb = PhotoImage(file="assets/square_bomb.png") self.square_cover = PhotoImage(file="assets/square_cover.png") # # ─── LOAD HEXAGONAL TILE SET ───────────────────────────────────── self.hex_up = PhotoImage(file="assets/hex_up.png") self.hex_down = PhotoImage(file="assets/hex_down.png") self.hex_bomb = PhotoImage(file="assets/hex_bomb.png") self.hex_cover = PhotoImage(file="assets/hex_cover.png") # # ─── CREATE COMPONENTS ─────────────────────────────────────────── self.canvas = Canvas(self.frame, width=canvas_width, height=canvas_height, background="#F19C79", bd=0, highlightthickness=0) self.canvas.bind("<Button-1>", self.callback_toggle) self.canvas.bind("<Button-3>", self.callback_cover) self.score_board = ScoreBoard(self.frame, self.width, self.difficulty) self.score_board.pack(side="top") self.canvas.pack() self.render_handler() self.menubar = MenuBar(self.frame, self) self.menubar.pack(side="bottom", pady=(40,0)) # # ─── RENDER HANDLER BASED ON GAME TYPE ────────────────────────────────────────── def render_handler(self): if self.mode == "SQUARE": self.draw_squares() elif self.mode == "HEX": self.draw_hexagons() print("We printed the hexagons") def draw_squares(self): # # ─── GET CURRENT STATE OF THE MODEL ────────────────────────────── toggles = self.board.get_state_toggles() numbers = self.board.get_state_button_numbers() covers = self.board.get_state_covers() # ─── REDRAW THE GAME BOARD ─────────────────────────────────────── self.canvas.delete(ALL) for i in range(self.game_size): for j in range(self.game_size): if covers[i][j] == True: self.place_tile_square(j, i, self.square_cover) elif not toggles[i][j]: self.place_tile_square(j, i, self.square_up) elif numbers[i][j] == 0: self.place_tile_square(j, i, self.square_down) else: self.place_tile_square(j, i, self.square_down, numbers[i][j]) def draw_hexagons(self): # # ─── GET CURRENT STATE OF THE MODEL ────────────────────────────── toggles = self.board.get_state_toggles() numbers = self.board.get_state_button_numbers() covers = self.board.get_state_covers() # ─── REDRAW THE GAME BOARD ─────────────────────────────────────── self.canvas.delete(ALL) for i in range(self.game_size): for j in range(self.game_size): if covers[i][j] == True: self.place_tile_hex(j, i, self.hex_cover) elif not toggles[i][j]: self.place_tile_hex(j, i, self.hex_up) elif numbers[i][j] == 0: self.place_tile_hex(j, i, self.hex_down) else: self.place_tile_hex(j, i, self.hex_down, numbers[i][j]) # # ─── DETERMINE POSITION FOR SQUARE TILE ───────────────────────────────────────── def place_tile_square(self, i, j, image, text=0): img_dimension = 46 pos_x = img_dimension * i pos_y = img_dimension * j self.draw_tile(pos_x, pos_y, image, text) # # ─── DETERMINE POSITION FOR HEXAGONAL TILE ────────────────────────────────────── def place_tile_hex(self, i, j, image, text=0): img_dimension = 46 base_pos_y = j * (img_dimension * 0.75) if j % 2 == 1: base_pos_x = i * img_dimension + (img_dimension / 2) else: base_pos_x = i * img_dimension self.draw_tile(base_pos_x, base_pos_y, image, text) def draw_tile(self, pos_x, pos_y, image, text): self.canvas.create_image(pos_x, pos_y, anchor=NW, image=image, tags="tile"); if text != 0: if text != "zero": self.canvas.create_text(pos_x + 22.5, pos_y + 22.5, text=text) def draw_mines(self): numbers = self.board.get_state_button_numbers() for i in range(self.game_size): for j in range(self.game_size): if numbers[i][j] == -1: if self.mode == "SQUARE": self.place_tile_square(j, i, self.square_bomb) elif self.mode == "HEX": self.place_tile_hex(j, i, self.hex_bomb) # # ─── FUNCTION TO DESTROY ALL TKINTER COMPONENTS AND RETURN TO MENU ────────────── # def cleanup(self): self.canvas.destroy() self.menubar.destroy() self.frame.destroy() self.frame.quit()
class workspace: default_font = FONT namespace = {} def __init__(self, CodeClass): # Configure FoxDot's namespace to include the editor CodeClass.namespace['FoxDot'] = self #CodeClass.namespace['Player'].widget = self #CodeClass.namespace['Ghost'].widget = self # Used for docstring prompt self.namespace = CodeClass.namespace # Set up master widget self.root = Tk() self.root.title("FoxDot - Live Coding with Python and SuperCollider") self.root.columnconfigure(1, weight=1) self.root.rowconfigure(0, weight=1) self.root.rowconfigure(1, weight=0) self.root.grid_columnconfigure(0, weight=0) self.root.protocol("WM_DELETE_WINDOW", self.kill) # --- Set icon try: # Use .ico file by default self.root.iconbitmap(FOXDOT_ICON) except: # Use .gif if necessary self.root.tk.call('wm', 'iconphoto', self.root._w, PhotoImage(file=FOXDOT_ICON)) # --- Setup font if self.default_font not in tkFont.families(): if SYSTEM == WINDOWS: self.default_font = "Consolas" elif SYSTEM == MAC_OS: self.default_font = "Monaco" else: self.default_font = "Courier New" self.font = tkFont.Font(font=(self.default_font, 12), name="CodeFont") self.font.configure(family=self.default_font) # --- start create menu self.menu = MenuBar(self, visible=True) # End menu setup --- # --- init main text box # Create y-axis scrollbar self.y_scroll = Scrollbar(self.root) self.y_scroll.grid(row=0, column=2, sticky='nsew') # Create text box for code self.text = ThreadedText(self.root, padx=5, pady=5, bg=colour_map['background'], fg=colour_map['plaintext'], insertbackground="White", font="CodeFont", yscrollcommand=self.y_scroll.set, width=100, height=20, bd=0, undo=True, autoseparators=True, maxundo=50) self.text.grid(row=0, column=1, sticky="nsew") self.y_scroll.config(command=self.text.yview) self.text.focus_set() # Create box for line numbers self.linenumbers = LineNumbers(self.text, width=25, bg=colour_map['background'], bd=0, highlightthickness=0) self.linenumbers.grid(row=0, column=0, sticky='nsew') # Docstring prompt label self.prompt = TextPrompt(self.text) # Key bindings self.text.bind("<Return>", self.newline) self.text.bind("<BackSpace>", self.delete) self.text.bind("<Delete>", self.delete2) self.text.bind("<Tab>", self.tab) self.text.bind("<Key>", self.keypress) # Use command key on Mac (Temporary) ctrl = "Command" if SYSTEM == MAC_OS else "Control" self.text.bind("<{}-Return>".format(ctrl), self.exec_block) self.text.bind("<Alt-Return>", self.exec_line) self.text.bind("<Alt_L>", lambda event: "break") self.text.bind("<{}-a>".format(ctrl), self.selectall) self.text.bind("<{}-period>".format(ctrl), self.killall) self.text.bind("<Alt-period>".format(ctrl), self.releaseNodes) self.text.bind("<{}-v>".format(ctrl), self.edit_paste) self.text.bind("<{}-bracketright>".format(ctrl), self.indent) self.text.bind("<{}-bracketleft>".format(ctrl), self.unindent) self.text.bind("<{}-equal>".format(ctrl), self.zoom_in) self.text.bind("<{}-minus>".format(ctrl), self.zoom_out) self.text.bind("<{}-z>".format(ctrl), self.undo) self.text.bind("<{}-y>".format(ctrl), self.redo) self.text.bind("<{}-s>".format(ctrl), self.save) self.text.bind("<{}-o>".format(ctrl), self.openfile) self.text.bind("<{}-n>".format(ctrl), self.newfile) self.text.bind("<{}-m>".format(ctrl), self.toggle_menu) # Change ctrl+h on Mac (is used to close) if SYSTEM == MAC_OS: self.text.bind("<{}-k>".format(ctrl), self.help) self.help_key = "K" else: self.text.bind("<{}-h>".format(ctrl), self.help) self.help_key = "H" # Toggle console button keybind try: self.text.bind("<{}-#>".format(ctrl), self.toggle_console) self.toggle_key = "#" except: self.text.bind("<{}-t>".format(ctrl), self.toggle_console) self.toggle_key = "T" # Save feature variabes self.saved = False self.file = None self.filename = None # --- define bracket behaviour self.bracketHandler = BracketHandler(self) # Set tag names and config for specific colours for tier in tag_weights: for tag_name in tier: self.text.tag_config(tag_name, foreground=colour_map[tag_name]) # --- Create console self.console = console(self.root, self.default_font) self.console_visible = True sys.stdout = self.console # Store original location of cursor self.origin = "origin" self.text.mark_set(self.origin, INSERT) self.text.mark_gravity(self.origin, LEFT) # Say Hello to the user print "Welcome to FoxDot! Press Ctrl+{} for help.".format( self.help_key) print "-----------------------------------------" def run(self): """ Starts the Tk mainloop for the master widget """ try: self.root.mainloop() except (KeyboardInterrupt, SystemExit): execute("Clock.stop()") execute("Server.quit()") return def read(self): return self.text.get("1.0", END) """ Key press commands ------------------ """ def keypress(self, event=None): """ Handles any keypress """ # For non string characters, return normally if not event.char or isHex(event.char): self.inbrackets = False self.update_prompt() return # Add character to text box else: self.delete_selection() index = self.text.index(INSERT) self.text.insert(index, event.char) # self.undo_stack.append_keystroke(index) self.text.edit_separator() self.update(event) return "break" """ Getting blocks / lines """ def exec_line(self, event=None, insert=INSERT): """ Highlights a single line and executes """ line, column = index(self.text.index(insert)) a, b = "%d.0" % line, "%d.end" % line self.highlight(a, b, "red") try: execute(self.text.get(a, b)) execute.update_line_numbers(self.text, a, b) except: pass self.root.after(200, self.unhighlight) return "break" def exec_block(self, event=None, insert=INSERT): """ Method to highlight block of code and execute """ # Get start and end of the buffer start, end = "1.0", self.text.index(END) lastline = int(end.split('.')[0]) + 1 # Indicies of block to execute block = [0, 0] # 1. Get position of cursor cur_x, cur_y = index(self.text.index(insert)) # 2. Go through line by line (back) and see what it's value is for line in range(cur_x, 0, -1): if not self.text.get("%d.0" % line, "%d.end" % line).strip(): break block[0] = line # 3. Iterate forwards until we get two \n\n or index==END for line in range(cur_x, lastline): if not self.text.get("%d.0" % line, "%d.end" % line).strip(): break block[1] = line # Now we have the lines of code! a, b = block if a == b: b += 1 for line in range(a, b): start = "%d.0" % line end = "%d.end" % line # Highlight text only to last character, not whole line self.highlight(start, end) # Convert line numbers to Tkinter indices a, b = ("%d.0" % n for n in (a, b)) # Execute the python code try: execute(self.text.get(a, b)) execute.update_line_numbers(self.text, a, b) except: pass # Unhighlight the line of text self.root.after(200, self.unhighlight) return "break" # Scheduling tasks # ---------------- def addTask(self, target, args=(), kwargs={}): self.text.queue.put((target, args, kwargs)) return # Undo action: Ctrl+Z #-------------------- def undo(self, event=None): try: self.text.edit_undo() self.update_all() except: pass return "break" def redo(self, event=None): try: self.text.edit_redo() self.update_all() except: pass return "break" # Help feature: Ctrl+H #--------------------- def help(self, event=None): if SYSTEM == MAC_OS: ctrl = "Cmd" else: ctrl = "Ctrl" print "FoxDot Help:" print "--------------------------------------------" print "{}+Return : Execute code".format(ctrl) print "{}+. : Stop all sound".format(ctrl) print "{}+= : Increase font size".format(ctrl) print "{}+- : Decrease font size".format(ctrl) print "{}+S : Save your work".format(ctrl) print "{}+O : Open a file".format(ctrl) print "{}+M : Toggle the menu".format(ctrl) print "{}+{} : Toggle console window".format( ctrl, self.toggle_key) print "--------------------------------------------" print "Please visit foxdot.org for more information" print "--------------------------------------------" return "break" # Save the current text: Ctrl+s #------------------------------ def save(self, event=None): """ Saves the contents of the text editor """ text = self.text.get("0.0", END) if not self.saved: self.filename = tkFileDialog.asksaveasfilename( defaultextension=".py") if self.filename: with open(self.filename, 'w') as f: f.write(text) f.close() self.saved = True print "Saved '{}'".format(self.filename) return bool(self.filename) # Open save def saveAs(self, event=None): text = self.text.get("0.0", END) self.filename = tkFileDialog.asksaveasfilename(defaultextension=".py") if self.filename is not None: with open(self.filename, 'w') as f: f.write(text) f.close() self.saved = True print "Save successful!" return bool(self.filename) # Open a file: Ctrl+o #-------------------- def openfile(self, event=None): f = tkFileDialog.askopenfile() if f is not None: text = f.read() f.close() self.set_all(text) return "break" def newfile(self, event=None): ''' Clears the document and asks if the user wants to save ''' answer = tkMessageBox.askyesnocancel( "", "Save your work before creating a new document?") if answer is not None: if answer is True: if not self.save(): return "break" self.saved = False self.filename = '' self.set_all("") return "break" # Toggle console: Ctrl+# #----------------------------- def toggle_console(self, event=None): if self.console_visible: self.console.hide() self.text.config(height=self.text.cget('height') + self.console.height) self.console_visible = False else: self.console.show() self.text.config(height=self.text.cget('height') - self.console.height) self.console_visible = True return def toggle_menu(self, event=None): self.menu.toggle() return "break" def edit_paste(self, event=None): """ Pastes any text and updates the IDE """ self.text.event_generate("<<Paste>>") self.update_all() return "break" def edit_cut(self, event=None): self.text.event_generate("<<Cut>>") return "break" def edit_copy(self, event=None): self.text.event_generate("<<Copy>>") return "break" # Newline #-------- def newline(self, event=None, insert=INSERT): """ Adds whitespace to newlines where necessary """ # Remove any highlighted text self.delete_selection() # Get the text from this line i, j = index(self.text.index(insert)) line = self.text.get("%d.0" % i, "%d.end" % i) # Add newline self.text.insert(index(i, j), "\n") # Update player line numbers execute.update_line_numbers(self.text) pos = 0 # amount of whitespace to add while True: # Case 1. Unindented or indented but empty if line.strip() == "": break # Case 2. Open Bracket pos = open_bracket(line) if pos: break # Case 2. Keyword with ending ':' pos = function(line) if pos: break # Case 3. Indented line pos = indented(line) if pos: break # Any other possibilities pos = 0 break # Add the necessary whitespace self.text.insert(index(i + 1, 0), " " * pos) # Update the IDE colours self.update(event) return "break" # Tab #---- def tab(self, event=None, insert=INSERT): """ Move selected text forward 4 spaces """ try: # Move any selected lines forwards a, b = (index(a)[0] for a in (self.text.index(SEL_FIRST), self.text.index(SEL_LAST))) if a < b: self.indent(event) return "break" else: self.delete(event) except: pass # Insert white space line, column = index(self.text.index(insert)) self.text.insert(index(line, column), self.tabspace()) # Update IDE self.update(event) return "break" # Indent: Ctrl+] #--------------- def indent(self, event=None, insert=INSERT): """ Indent the current line or selected text """ try: if not self.text_selected(): a = index(self.text.index(INSERT)) a = a[0], a[1] - 1 b = a[0], a[1] + 1 self.text.tag_add(SEL, index(*a), index(*b)) sel_a = index(index(self.text.index(SEL_FIRST))[0], 0) sel_b = index(index(self.text.index(SEL_LAST))[0], 'end') start, end = (index(a) for a in (self.text.index(SEL_FIRST), self.text.index(SEL_LAST))) for row in range(start[0], end[0] + 1): # Add intentation self.text.insert(index(row, 0), self.tabspace()) self.text.tag_add(SEL, sel_a, sel_b) except: pass return "break" # Un-inden: Ctrl+[ #----------------- def unindent(self, event): """ Moves the current row or selected text back by 4 spaces """ if not self.text_selected(): a = index(self.text.index(INSERT)) a = a[0], a[1] - 1 b = a[0], a[1] + 1 self.text.tag_add(SEL, index(*a), index(*b)) sel_a = index(index(self.text.index(SEL_FIRST))[0], 0) sel_b = index(index(self.text.index(SEL_LAST))[0], 'end') start, end = (index(a) for a in (self.text.index(SEL_FIRST), self.text.index(SEL_LAST))) for row in range(start[0], end[0] + 1): # Unindent line = self.text.get(index(row, 0), index(row, 'end')) for n, char in enumerate(line[:tabsize]): if char != " ": break self.text.delete(index(row, 0), index(row, n + 1)) #self.text.insert(index(row,0), self.tabspace()) self.text.tag_add(SEL, sel_a, sel_b) return "break" # Deletion #--------- def delete(self, event=None, insert=INSERT): """ Deletes a character or selected area """ # If there is a selected area, delete that if self.delete_selection(): # Update player line numbers execute.update_line_numbers(self.text) return "break" # Handle delete in brackets if self.bracketHandler.delete(): return "break" # Else, work out if there is a tab to delete line, column = index(self.text.index(insert)) # If we are at the start of a line, delete that if column == 0: self.update(event) # Update player line numbers execute.update_line_numbers(self.text, start="%d.0" % (i - 1), remove=int(i != 1)) self.text.delete(index(line - 1, END), insert) else: tab = index(line, column - tabsize) # Check if there's a tab if self.text.get(tab, insert) == self.tabspace(): self.text.delete(tab, insert) else: self.text.delete(index(line, column - 1), insert) # Update the IDE self.update(event) return "break" def delete2(self, event=None, insert=INSERT): """ Delete the next character """ if not self.delete_selection(): self.text.delete(self.text.index(insert)) self.update(event) execute.update_line_numbers(self.text) return "break" def delete_selection(self): """ If an area is selected, it is deleted and returns True """ try: text = self.text.get(SEL_FIRST, SEL_LAST) a, b = self.text.index(SEL_FIRST), self.text.index(SEL_LAST) self.text.delete(SEL_FIRST, SEL_LAST) self.undo_stack.append_delete(text, a, b) return True except: return False def text_selected(self): """ Returns True if text is selected """ try: self.text.index(SEL_FIRST) return True except: return False """ Keyboard Shortcuts ================== """ # Select all: Ctrl+a #------------------- def selectall(self, event=None): """ Select the contents of the editor """ self.text.tag_add(SEL, "1.0", END) self.text.mark_set(INSERT, "1.0") self.text.see(INSERT) return 'break' # Kill all: Ctrl+. #----------------- def killall(self, event=None): """ Stops all player objects """ execute("Clock.clear()") return "break" # Zoom in: Ctrl+= #---------------- def zoom_in(self, event=None): """ Ctrl+= increases text size """ self.root.grid_propagate(False) font = tkFont.nametofont("CodeFont") size = font.actual()["size"] + 2 font.configure(size=size) # Increase size of line number self.linenumbers.config(width=self.linenumbers.winfo_width() + 3) return 'break' # Zoom out: Ctrl+- #----------------- def zoom_out(self, event=None): """ Ctrl+- decreases text size (minimum of 8) """ self.root.grid_propagate(False) font = tkFont.nametofont("CodeFont") size = font.actual()["size"] - 2 if size >= 8: font.configure(size=size) self.linenumbers.config(width=self.linenumbers.winfo_width() - 3) return 'break' def submit(self, code_str): """ Runs the chunk of code through FoxDot processing and execute """ try: execute(code_str) except Exception as e: print e def highlight(self, start, end, colour="Red"): """ Highlights an area of text """ # Label block (start and end are the lines before and after the code itself) self.text.tag_add("code", start, end) # Highlight self.text.tag_config("code", background=colour, foreground="White") return def unhighlight(self): """ Creates thread to wait 0.2 seconds before removing any highlights from the text """ # Remove labels self.text.tag_delete("code") return """ Methods that view the FoxDot namespace -------------------------------------- """ def update_prompt(self): return def update_prompt2(self): if self.inbrackets: # Show prompt line, column = index(self.text.index(INSERT)) text = self.text.get(index(line, 0), index(line, column)) x = self.font.measure(text) y = self.font.metrics("linespace") * line self.prompt.move(x, y) # If cursor is in between brackets that follow a type word try: self.check_namespace() except: pass else: # Hide prompt self.prompt.hide() def check_namespace(self): """ Sets the label """ obj = self.namespace[self.last_word] if obj: if obj.__doc__ is not None: self.prompt.value.set(obj.__doc__) else: self.prompt.hide() """ Methods that update the contents of the IDE ------------------------------------------- """ def update(self, event=None, insert=INSERT): """ Updates the the colours of the IDE """ # Move the window to view the current line self.text.see(INSERT) # 1. Get the contents of the current line cur = self.text.index(insert) line, column = index(cur) self.colour_line(line) self.update_prompt() return "break" def update_all(self): """ Updates every line in the IDE """ row, col = index(self.text.index(END)) lines = row + 1 for line in range(lines): self.colour_line(line) return def colour_line(self, line): """ Checks a line for any tags that match regex and updates IDE colours """ start, end = index(line, 0), index(line, "end") thisline = self.text.get(start, end) try: # Remove tags at current point for tag_name in self.text.tag_names(): self.text.tag_remove(tag_name, start, end) # Re-apply tags for tag_name, start, end in findstyles(thisline): self.text.tag_add(tag_name, index(line, start), index(line, end)) except Exception as e: print e def get_last_word(self): line, column = index(self.text.index(INSERT)) string = "" while True: char = self.text.get(index(line, column - 1)) if char.isalpha(): string = char + string else: break column -= 1 if column == 0: break self.last_word = string """ Generic functions ----------------- - Correct exiting - Tabspace (todo: customise) """ def kill(self): """ Proper exit function """ self.terminate() self.root.destroy() return def tabspace(self): return " " * tabsize def terminate(self): """ Called on window close. Ends Clock thread process """ execute("Clock.stop()") execute("Server.quit()") return def releaseNodes(self, event=None): execute("Server.freeAllNodes()") return def replace(self, line, old, new): """ Replaces text on a specified line and updates the IDE """ try: # Store cursor origin = self.text.index(INSERT) # Get contents of the line a = index(line, 0) b = index(line, END) contents = self.text.get(a, b) # Find the part to replace i = contents.index(old) j = i + len(old) a = index(line, i) b = index(line, j) self.text.delete(a, b) self.text.insert(a, new) self.update(insert=a) self.text.mark_set(INSERT, origin) except: return def replace_re(self, line, new=""): """ Replaces text on a specified line and updates the IDE """ try: # Store cursor origin = self.text.index(INSERT) # Get contents of the line a = index(line, 0) b = index(line, END) contents = self.text.get(a, b) # Search using RegEx match = re_pat(contents) if match: # Find the part to replace i = match.start() j = match.end() a = index(line, i) b = index(line, j) self.text.delete(a, b) self.text.insert(a, new) self.update(insert=a) self.text.mark_set(INSERT, origin) except Exception as e: print e return def set_all(self, text): self.text.delete("1.0", END) self.text.insert("1.0", text.strip()) self.update_all() return def get_all(self): return self.text.get("1.0", END) def openhomepage(self): webbrowser.open("www.foxdot.org") return def opendocumentation(self): webbrowser.open( "https://github.com/Qirky/FoxDot/tree/master/docs/FoxDot/lib") return
def __init__(self, CodeClass): # Configure FoxDot's namespace to include the editor CodeClass.namespace['FoxDot'] = self #CodeClass.namespace['Player'].widget = self #CodeClass.namespace['Ghost'].widget = self # Used for docstring prompt self.namespace = CodeClass.namespace # Set up master widget self.root = Tk() self.root.title("FoxDot - Live Coding with Python and SuperCollider") self.root.columnconfigure(1, weight=1) self.root.rowconfigure(0, weight=1) self.root.rowconfigure(1, weight=0) self.root.grid_columnconfigure(0, weight=0) self.root.protocol("WM_DELETE_WINDOW", self.kill) # --- Set icon try: # Use .ico file by default self.root.iconbitmap(FOXDOT_ICON) except: # Use .gif if necessary self.root.tk.call('wm', 'iconphoto', self.root._w, PhotoImage(file=FOXDOT_ICON)) # --- Setup font if self.default_font not in tkFont.families(): if SYSTEM == WINDOWS: self.default_font = "Consolas" elif SYSTEM == MAC_OS: self.default_font = "Monaco" else: self.default_font = "Courier New" self.font = tkFont.Font(font=(self.default_font, 12), name="CodeFont") self.font.configure(family=self.default_font) # --- start create menu self.menu = MenuBar(self, visible=True) # End menu setup --- # --- init main text box # Create y-axis scrollbar self.y_scroll = Scrollbar(self.root) self.y_scroll.grid(row=0, column=2, sticky='nsew') # Create text box for code self.text = ThreadedText(self.root, padx=5, pady=5, bg=colour_map['background'], fg=colour_map['plaintext'], insertbackground="White", font="CodeFont", yscrollcommand=self.y_scroll.set, width=100, height=20, bd=0, undo=True, autoseparators=True, maxundo=50) self.text.grid(row=0, column=1, sticky="nsew") self.y_scroll.config(command=self.text.yview) self.text.focus_set() # Create box for line numbers self.linenumbers = LineNumbers(self.text, width=25, bg=colour_map['background'], bd=0, highlightthickness=0) self.linenumbers.grid(row=0, column=0, sticky='nsew') # Docstring prompt label self.prompt = TextPrompt(self.text) # Key bindings self.text.bind("<Return>", self.newline) self.text.bind("<BackSpace>", self.delete) self.text.bind("<Delete>", self.delete2) self.text.bind("<Tab>", self.tab) self.text.bind("<Key>", self.keypress) # Use command key on Mac (Temporary) ctrl = "Command" if SYSTEM == MAC_OS else "Control" self.text.bind("<{}-Return>".format(ctrl), self.exec_block) self.text.bind("<Alt-Return>", self.exec_line) self.text.bind("<Alt_L>", lambda event: "break") self.text.bind("<{}-a>".format(ctrl), self.selectall) self.text.bind("<{}-period>".format(ctrl), self.killall) self.text.bind("<Alt-period>".format(ctrl), self.releaseNodes) self.text.bind("<{}-v>".format(ctrl), self.edit_paste) self.text.bind("<{}-bracketright>".format(ctrl), self.indent) self.text.bind("<{}-bracketleft>".format(ctrl), self.unindent) self.text.bind("<{}-equal>".format(ctrl), self.zoom_in) self.text.bind("<{}-minus>".format(ctrl), self.zoom_out) self.text.bind("<{}-z>".format(ctrl), self.undo) self.text.bind("<{}-y>".format(ctrl), self.redo) self.text.bind("<{}-s>".format(ctrl), self.save) self.text.bind("<{}-o>".format(ctrl), self.openfile) self.text.bind("<{}-n>".format(ctrl), self.newfile) self.text.bind("<{}-m>".format(ctrl), self.toggle_menu) # Change ctrl+h on Mac (is used to close) if SYSTEM == MAC_OS: self.text.bind("<{}-k>".format(ctrl), self.help) self.help_key = "K" else: self.text.bind("<{}-h>".format(ctrl), self.help) self.help_key = "H" # Toggle console button keybind try: self.text.bind("<{}-#>".format(ctrl), self.toggle_console) self.toggle_key = "#" except: self.text.bind("<{}-t>".format(ctrl), self.toggle_console) self.toggle_key = "T" # Save feature variabes self.saved = False self.file = None self.filename = None # --- define bracket behaviour self.bracketHandler = BracketHandler(self) # Set tag names and config for specific colours for tier in tag_weights: for tag_name in tier: self.text.tag_config(tag_name, foreground=colour_map[tag_name]) # --- Create console self.console = console(self.root, self.default_font) self.console_visible = True sys.stdout = self.console # Store original location of cursor self.origin = "origin" self.text.mark_set(self.origin, INSERT) self.text.mark_gravity(self.origin, LEFT) # Say Hello to the user print "Welcome to FoxDot! Press Ctrl+{} for help.".format( self.help_key) print "-----------------------------------------"
def initUI(self): self.menuBar = MenuBar(self) self.setMenuBar(self.menuBar) self.workspace = Workspace(self) self.setCentralWidget(self.workspace)
class main(ShowBase): def __init__(self): ShowBase.__init__(self) # Disable the default camera movements self.disableMouse() # # VIEW SETTINGS # self.win.setClearColor((0.16, 0.16, 0.16, 1)) render.setAntialias(AntialiasAttrib.MAuto) render2d.setAntialias(AntialiasAttrib.MAuto) # # NODE VIEW # self.viewNP = aspect2d.attachNewNode("viewNP") self.viewNP.setScale(0.5) # # NODE MANAGER # self.nodeMgr = NodeManager(self.viewNP) # # NODE RELATED EVENTS # # Add nodes self.accept("addNode", self.nodeMgr.addNode) # Remove nodes self.accept("removeNode", self.nodeMgr.removeNode) self.accept("x", self.nodeMgr.removeNode) self.accept("delete", self.nodeMgr.removeNode) # Selecting self.accept("selectNode", self.nodeMgr.selectNode) # Deselecting self.accept("mouse3", self.nodeMgr.deselectAll) # Node Drag and Drop self.accept("dragNodeStart", self.setDraggedNode) self.accept("dragNodeMove", self.updateNodeMove) self.accept("dragNodeStop", self.updateNodeStop) # Duplicate/Copy nodes self.accept("shift-d", self.nodeMgr.copyNodes) self.accept("copyNodes", self.nodeMgr.copyNodes) # Refresh node logics self.accept("ctlr-r", self.nodeMgr.updateAllLeaveNodes) self.accept("refreshNodes", self.nodeMgr.updateAllLeaveNodes) # # SOCKET RELATED EVENTS # self.accept("updateConnectedNodes", self.nodeMgr.updateConnectedNodes) # Socket connection with drag and drop self.accept("startPlug", self.nodeMgr.setStartPlug) self.accept("endPlug", self.nodeMgr.setEndPlug) self.accept("connectPlugs", self.nodeMgr.connectPlugs) self.accept("cancelPlug", self.nodeMgr.cancelPlug) # Draw line while connecting sockets self.accept("startLineDrawing", self.startLineDrawing) self.accept("stopLineDrawing", self.stopLineDrawing) # # PROJECT MANAGEMENT # self.accept("new", self.newProject) self.accept("save", self.saveProject) self.accept("load", self.loadProject) self.accept("quit", exit) # # EDITOR VIEW # # Zooming self.accept("zoom", self.zoom) self.accept("zoom_reset", self.zoomReset) self.accept("wheel_up", self.zoom, [True]) self.accept("wheel_down", self.zoom, [False]) # Drag view self.mouseSpeed = 1 self.mousePos = None self.startCameraMovement = False self.accept("mouse2", self.setMoveCamera, [True]) self.accept("mouse2-up", self.setMoveCamera, [False]) # Box select # accept the 1st mouse button events to start and stop the draw self.accept("mouse1", self.startBoxDraw) self.accept("mouse1-up", self.stopBoxDraw) # variables to store the start and current pos of the mousepointer self.startPos = LPoint2f(0, 0) self.lastPos = LPoint2f(0, 0) # variables for the to be drawn box self.boxCardMaker = CardMaker("SelectionBox") self.boxCardMaker.setColor(1, 1, 1, 0.25) self.box = None # # WINDOW RELATED EVENTS # self.screenSize = base.getSize() self.accept("window-event", self.windowEventHandler) # # MENU BAR # self.menuBar = MenuBar() # # TASKS # # Task for handling dragging of the camera/view self.taskMgr.add(self.updateCam, "task_camActualisation", priority=-4) # ------------------------------------------------------------------ # PROJECT FUNCTIONS # ------------------------------------------------------------------ def newProject(self): self.nodeMgr.cleanup() def saveProject(self): Save(self.nodeList, self.connections) def loadProject(self): self.nodeMgr.cleanup() Load(self.nodeMgr) # ------------------------------------------------------------------ # CAMERA SPECIFIC FUNCTIONS # ------------------------------------------------------------------ def setMoveCamera(self, moveCamera): """Start dragging around the editor area/camera""" # store the mouse position if weh have a mouse if base.mouseWatcherNode.hasMouse(): x = base.mouseWatcherNode.getMouseX() y = base.mouseWatcherNode.getMouseY() self.mousePos = Point2(x, y) # set the variable according to if we want to move the camera or not self.startCameraMovement = moveCamera def updateCam(self, task): """Task that will move the editor area/camera around according to mouse movements""" # variables to store the mouses current x and y position x = 0.0 y = 0.0 if base.mouseWatcherNode.hasMouse(): # get the mouse position x = base.mouseWatcherNode.getMouseX() y = base.mouseWatcherNode.getMouseY() if base.mouseWatcherNode.hasMouse() \ and self.mousePos is not None \ and self.startCameraMovement: # Move the viewer node aspect independent wp = self.win.getProperties() aspX = 1.0 aspY = 1.0 wpXSize = wp.getXSize() wpYSize = wp.getYSize() if wpXSize > wpYSize: aspX = wpXSize / float(wpYSize) else: aspY = wpYSize / float(wpXSize) mouseMoveX = (self.mousePos.getX() - x) / self.viewNP.getScale( ).getX() * self.mouseSpeed * aspX mouseMoveY = (self.mousePos.getY() - y) / self.viewNP.getScale( ).getZ() * self.mouseSpeed * aspY self.mousePos = Point2(x, y) self.viewNP.setX(self.viewNP, -mouseMoveX) self.viewNP.setZ(self.viewNP, -mouseMoveY) self.nodeMgr.updateConnections() # continue the task until it got manually stopped return task.cont def zoom(self, zoomIn): """Zoom the editor in or out dependent on the value in zoomIn""" zoomFactor = 0.05 maxZoomIn = 2 maxZoomOut = 0.1 if zoomIn: s = self.viewNP.getScale() if s.getX() - zoomFactor < maxZoomIn and s.getY( ) - zoomFactor < maxZoomIn and s.getZ() - zoomFactor < maxZoomIn: self.viewNP.setScale(s.getX() + zoomFactor, s.getY() + zoomFactor, s.getZ() + zoomFactor) else: s = self.viewNP.getScale() if s.getX() - zoomFactor > maxZoomOut and s.getY( ) - zoomFactor > maxZoomOut and s.getZ() - zoomFactor > maxZoomOut: self.viewNP.setScale(s.getX() - zoomFactor, s.getY() - zoomFactor, s.getZ() - zoomFactor) self.nodeMgr.updateConnections() def zoomReset(self): """Set the zoom level back to the default""" self.viewNP.setScale(0.5) self.nodeMgr.updateConnections() # ------------------------------------------------------------------ # DRAG LINE # ------------------------------------------------------------------ def startLineDrawing(self, startPos): """Start a task that will draw a line from the given start position to the cursor""" self.line = LineNodePath(render2d, thickness=2, colorVec=(0.8, 0.8, 0.8, 1)) self.line.moveTo(startPos) t = self.taskMgr.add(self.drawLineTask, "drawLineTask") t.startPos = startPos def drawLineTask(self, task): """Draws a line from a given start position to the cursor""" mwn = base.mouseWatcherNode if mwn.hasMouse(): pos = Point3(mwn.getMouse()[0], 0, mwn.getMouse()[1]) self.line.reset() self.line.moveTo(task.startPos) self.line.drawTo(pos) self.line.create() return task.cont def stopLineDrawing(self): """Stop the task that draws a line to the cursor""" taskMgr.remove("drawLineTask") if self.line is not None: self.line.reset() self.line = None # ------------------------------------------------------------------ # EDITOR NODE DRAGGING UPDATE # ------------------------------------------------------------------ def setDraggedNode(self, node): """This will set the node that is currently dragged around as well as update other selected nodes which will be moved in addition to the main dragged node""" self.draggedNode = node self.tempNodePositions = {} for node in self.nodeMgr.selectedNodes: self.tempNodePositions[node] = node.frame.getPos(render2d) def updateNodeMove(self, mouseA, mouseB): """Will be called as long as a node is beeing dragged around""" for node in self.nodeMgr.selectedNodes: if node is not self.draggedNode and node in self.tempNodePositions.keys( ): editVec = Vec3(self.tempNodePositions[node] - mouseA) newPos = mouseB + editVec node.frame.setPos(render2d, newPos) self.nodeMgr.updateConnections() def updateNodeStop(self, node=None): """Will be called when a node dragging stopped""" self.draggedNode = None self.tempNodePositions = {} self.nodeMgr.updateConnections() # ------------------------------------------------------------------ # BASIC WINDOW HANDLING # ------------------------------------------------------------------ def windowEventHandler(self, window=None): """Custom handler for window events. We mostly use this for resizing.""" # call showBase windowEvent which would otherwise get overridden and breaking the app self.windowEvent(window) if window != self.win: # This event isn't about our window. return if window is not None: # window is none if panda3d is not started if self.screenSize == base.getSize(): return self.screenSize = base.getSize() # Resize all editor frames self.menuBar.resizeFrame() # ------------------------------------------------------------------ # SELECTION BOX # ------------------------------------------------------------------ def startBoxDraw(self): """Start drawing the box""" if self.mouseWatcherNode.hasMouse(): # get the mouse position self.startPos = LPoint2f(self.mouseWatcherNode.getMouse()) taskMgr.add(self.dragBoxDrawTask, "dragBoxDrawTask") def stopBoxDraw(self): """Stop the draw box task and remove the box""" if not taskMgr.hasTaskNamed("dragBoxDrawTask"): return taskMgr.remove("dragBoxDrawTask") if self.startPos is None or self.lastPos is None: return self.nodeMgr.deselectAll() if self.box is not None: for node in self.nodeMgr.getAllNodes(): # store some view scales for calculations viewXScale = self.viewNP.getScale().getX() viewZScale = self.viewNP.getScale().getZ() # calculate the node edges nodeLeft = node.getLeft() * viewXScale nodeRight = node.getRight() * viewXScale nodeBottom = node.getBottom() * viewZScale nodeTop = node.getTop() * viewZScale # calculate bounding box edges left = min(self.lastPos.getX(), self.startPos.getX()) right = max(self.lastPos.getX(), self.startPos.getX()) top = max(self.lastPos.getY(), self.startPos.getY()) bottom = min(self.lastPos.getY(), self.startPos.getY()) # check for hits xGood = yGood = False if left < nodeLeft and right > nodeLeft: xGood = True elif left < nodeRight and right > nodeRight: xGood = True if top > nodeTop and bottom < nodeTop: yGood = True elif top > nodeBottom and bottom < nodeBottom: yGood = True # check if we have any hits if xGood and yGood: self.nodeMgr.selectNode(node, True, True) # Cleanup the selection box self.box.removeNode() self.startPos = None self.lastPos = None def dragBoxDrawTask(self, task): """This task will track the mouse position and actualize the box's size according to the first click position of the mouse""" if self.mouseWatcherNode.hasMouse(): if self.startPos is None: self.startPos = LPoint2f(self.mouseWatcherNode.getMouse()) # get the current mouse position self.lastPos = LPoint2f(self.mouseWatcherNode.getMouse()) else: return task.cont # check if we already have a box if self.box != None: # if so, remove that old box self.box.removeNode() # set the box's size self.boxCardMaker.setFrame(self.lastPos.getX(), self.startPos.getX(), self.startPos.getY(), self.lastPos.getY()) # generate, setup and draw the box node = self.boxCardMaker.generate() self.box = render2d.attachNewNode(node) self.box.setBin("gui-popup", 25) self.box.setTransparency(TransparencyAttrib.M_alpha) # run until the task is manually stopped return task.cont
def __init__(self): ShowBase.__init__(self) # Disable the default camera movements self.disableMouse() # # VIEW SETTINGS # self.win.setClearColor((0.16, 0.16, 0.16, 1)) render.setAntialias(AntialiasAttrib.MAuto) render2d.setAntialias(AntialiasAttrib.MAuto) # # NODE VIEW # self.viewNP = aspect2d.attachNewNode("viewNP") self.viewNP.setScale(0.5) # # NODE MANAGER # self.nodeMgr = NodeManager(self.viewNP) # # NODE RELATED EVENTS # # Add nodes self.accept("addNode", self.nodeMgr.addNode) # Remove nodes self.accept("removeNode", self.nodeMgr.removeNode) self.accept("x", self.nodeMgr.removeNode) self.accept("delete", self.nodeMgr.removeNode) # Selecting self.accept("selectNode", self.nodeMgr.selectNode) # Deselecting self.accept("mouse3", self.nodeMgr.deselectAll) # Node Drag and Drop self.accept("dragNodeStart", self.setDraggedNode) self.accept("dragNodeMove", self.updateNodeMove) self.accept("dragNodeStop", self.updateNodeStop) # Duplicate/Copy nodes self.accept("shift-d", self.nodeMgr.copyNodes) self.accept("copyNodes", self.nodeMgr.copyNodes) # Refresh node logics self.accept("ctlr-r", self.nodeMgr.updateAllLeaveNodes) self.accept("refreshNodes", self.nodeMgr.updateAllLeaveNodes) # # SOCKET RELATED EVENTS # self.accept("updateConnectedNodes", self.nodeMgr.updateConnectedNodes) # Socket connection with drag and drop self.accept("startPlug", self.nodeMgr.setStartPlug) self.accept("endPlug", self.nodeMgr.setEndPlug) self.accept("connectPlugs", self.nodeMgr.connectPlugs) self.accept("cancelPlug", self.nodeMgr.cancelPlug) # Draw line while connecting sockets self.accept("startLineDrawing", self.startLineDrawing) self.accept("stopLineDrawing", self.stopLineDrawing) # # PROJECT MANAGEMENT # self.accept("new", self.newProject) self.accept("save", self.saveProject) self.accept("load", self.loadProject) self.accept("quit", exit) # # EDITOR VIEW # # Zooming self.accept("zoom", self.zoom) self.accept("zoom_reset", self.zoomReset) self.accept("wheel_up", self.zoom, [True]) self.accept("wheel_down", self.zoom, [False]) # Drag view self.mouseSpeed = 1 self.mousePos = None self.startCameraMovement = False self.accept("mouse2", self.setMoveCamera, [True]) self.accept("mouse2-up", self.setMoveCamera, [False]) # Box select # accept the 1st mouse button events to start and stop the draw self.accept("mouse1", self.startBoxDraw) self.accept("mouse1-up", self.stopBoxDraw) # variables to store the start and current pos of the mousepointer self.startPos = LPoint2f(0, 0) self.lastPos = LPoint2f(0, 0) # variables for the to be drawn box self.boxCardMaker = CardMaker("SelectionBox") self.boxCardMaker.setColor(1, 1, 1, 0.25) self.box = None # # WINDOW RELATED EVENTS # self.screenSize = base.getSize() self.accept("window-event", self.windowEventHandler) # # MENU BAR # self.menuBar = MenuBar() # # TASKS # # Task for handling dragging of the camera/view self.taskMgr.add(self.updateCam, "task_camActualisation", priority=-4)
def menubar(): from MenuBar import MenuBar return MenuBar()
for title in titles: if title == detail_name: row_detail_icons[index].click() return else: index += 1 raise NoSuchElementException('detail row icon does not exist') if __name__ == '__main__': webdriver = webdriver.Firefox() webdriver.maximize_window() webdriver.implicitly_wait(10) login_page = LoginPage(webdriver) login_page.login() menu_bar = MenuBar(webdriver) menu_bar.wait_UI(menu_bar.menu_button_loc) menu_bar.action_toggle_menu() time.sleep(1) menu_bar.action_expand_app_group('Supply Chain Advantage') menu_bar.action_expand_menu('Advantage Dashboard') menu_bar.action_expand_menu('Receiving') menu_bar.action_expand_menu('ASNs', False) searchPage = SearchPage(webdriver) searchPage.wait_page('Search ASNs') print(searchPage.get_page_title()) # time.sleep(1) print(searchPage.get_all_labels_name(1)) searchPage.action_dropdown_select('Warehouse ID', 'Warehouse2 - Warehouse 02') # searchPage.action_checkbox_check('Search by Date')
class TimeControl(Gtk.Window): def __init__(self): Gtk.Window.__init__(self) self.set_title("TimeControl") self.set_icon_from_file( os.path.join(BASE_PATH, "img", "timecontrol.png")) self.set_resizable(True) self.set_border_width(2) self.set_position(Gtk.WindowPosition.CENTER) base_hbox = Gtk.HBox() self.menuBar = MenuBar() self.calendario = Gtk.Calendar() self.calendario.connect('day_selected', self.__changed_date) frame = Gtk.Frame() frame.set_label(' Ingreso de Datos: ') frame.set_border_width(15) hbox = Gtk.HBox() hbox.set_border_width(15) self.tabla = Tabla() hbox.pack_start(self.tabla, True, False, 0) frame.add(hbox) vbox = Gtk.VBox() vbox.pack_start(self.menuBar, False, False, 0) vbox.pack_start(self.calendario, True, False, 0) vbox.pack_start(frame, True, False, 0) self.tablasemana = TablaSemana() base_hbox.pack_start(vbox, True, True, 0) base_hbox.pack_start(self.tablasemana, True, True, 0) self.add(base_hbox) self.connect("delete-event", self.__salir) self.menuBar.connect("newuser", self.__newUser) self.tabla.connect("viewuser", self.__viewUser) self.tabla.connect('save', self.__guardar) self.show_all() def __guardar(self, widget): num, _dict = self.tabla.get_data() dialog = Gtk.Dialog(parent=self.get_toplevel(), flags=Gtk.DialogFlags.MODAL, buttons=["OK", Gtk.ResponseType.OK]) dialog.set_border_width(15) if addData(str(num), _dict): label = Gtk.Label("Datos Almacenados.") self.__viewUser(None, num) else: label = Gtk.Label("Este Funcionario no Existe") dialog.vbox.pack_start(label, True, True, 5) dialog.vbox.show_all() dialog.run() dialog.destroy() def __get_date_to_string(self): res = self.calendario.get_date() f = '%s/%s/%s' % (res.day, res.month + 1, res.year) fecha = datetime.datetime.strptime(f, '%d/%m/%Y') return str(datetime.date.strftime(fecha, '%d/%m/%Y')) def __changed_date(self, widget=False): self.__viewUser(None, self.tabla.get_data()[0]) def __viewUser(self, tabla, num): fecha = self.__get_date_to_string() data = getDataUser(str(num)) self.tabla.set_data(fecha, num, data) semana = datetime.datetime.strptime(fecha, '%d/%m/%Y').isocalendar()[1] self.tablasemana.set_data(semana, getDataSemana(num, semana, data)) def __newUser(self, widget, num, name): dialog = Gtk.Dialog(parent=self.get_toplevel(), flags=Gtk.DialogFlags.MODAL, buttons=["OK", Gtk.ResponseType.OK]) dialog.set_border_width(15) if adduser(num, name): label = Gtk.Label("Usuario Almacenado") else: label = Gtk.Label("Este Funcionario ya Existe") dialog.vbox.pack_start(label, True, True, 5) dialog.vbox.show_all() dialog.run() dialog.destroy() self.__viewUser(None, num) def __salir(self, widget=None, senial=None): Gtk.main_quit() sys.exit(0)
class Application(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self) self.parent = parent self.setWindowTitle('imrenderin') ## Widgets self.menu_bar = MenuBar(self) self.menu_bar.setFixedHeight(25) self.status_bar = StatusBar(self) self.status_bar.setFixedHeight(35) ## Redirect stdout,stderr to dialog self.console = ConsoleDialog(sys.stdout) sys.stdout = self.console sys.stderr = self.console ## UI Elements self.display = Display(self) self.controls = DefaultUI(self, self.display) ## Layout vbox = QtGui.QVBoxLayout(self) vbox.addWidget(self.menu_bar) vbox.addWidget(self.controls) vbox.addWidget(self.status_bar) vbox.setSpacing(2) vbox.setContentsMargins(2, 2, 2, 2) self.setLayout(vbox) self.setMinimumWidth(200) self.setMinimumHeight(150) self.resize(_width, _height) def about(self): msg = ''' About this thing ''' mb = QMessageBox(self) mb.setText(msg.strip()) mb.setIcon(QtGui.QMessageBox.Information) mb.setWindowTitle('About') mb.show() def showConsole(self): self.console.show() def help(self): msg = ''' Don't Panic! ''' mb = QMessageBox(self) mb.setText(msg.strip()) mb.setIcon(QtGui.QMessageBox.Information) mb.setWindowTitle('About') mb.show() def open(self): fd = QtGui.QFileDialog() path = fd.getOpenFileName(None, 'Open image file...', '') self.display.imshow(path) def toggleFullscreen(self): self.showNormal() if self.isFullScreen() else self.showFullScreen()