class GUI: """For reciprocal space maps""" def __init__(self, master): self.file_path = None self.RSM = None #Defaul scale for RSM and Linescan is logarithmic self.rsm_scale = StringVar() self.rsm_scale.set("log") self.line_scale = StringVar() self.line_scale.set("log") #Default parameters for RSM self.rsm_parallel_lower = -0.01 self.rsm_parallel_upper = 0 self.rsm_normal_lower = 0.5 self.rsm_normal_upper = 0.52 #Default parameters for linescan self.origin_parallel = -0.0007 self.origin_normal = 0.51192 self.linescan_angle = 0.0 self.linescan_width = 0.000015 self.window_frame = Frame(master, bd=2, relief=GROOVE) self.fileselect_button = Button(self.window_frame, text="Select XRDML file", command=self.select_file) self.busy_label = Label(self.window_frame, text="") self.savebutton1 = Button(self.window_frame, text="Save RSM", command=lambda: self.savefigure(self.rsm_plot_figure)) self.savebutton2 = Button(self.window_frame, text="Save Linescan", command=lambda: self.savefigure(self.linescan_plot_figure)) self.rsm_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.rsm_label = Label(self.rsm_frame, text="Amerigo - RSM Viewer Space Map") self.rsm_parallel_lower_label = Label(self.rsm_frame, text="Lower q-parallel bound") self.rsm_parallel_lower_entry = Entry(self.rsm_frame) self.rsm_parallel_upper_label = Label(self.rsm_frame, text="Upper q-parallel bound") self.rsm_parallel_upper_entry = Entry(self.rsm_frame) self.rsm_normal_lower_label = Label(self.rsm_frame, text="Lower q-normal bound") self.rsm_normal_lower_entry = Entry(self.rsm_frame) self.rsm_normal_upper_label = Label(self.rsm_frame, text="Upper q-normal bound") self.rsm_normal_upper_entry = Entry(self.rsm_frame) self.rsm_sclae_linear = Radiobutton(self.rsm_frame, text="Linear", variable=self.rsm_scale, value="linear") self.rsm_sclae_log = Radiobutton(self.rsm_frame, text="Logarithmic", variable=self.rsm_scale, value="log") self.create_rsm_button = Button(self.rsm_frame, text="Create RSM", command=self.create_rsm) self.linescan_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.linescan_label = Label(self.linescan_frame, text="Line Scan") self.origin_parallel_label = Label(self.linescan_frame, text="Point of origin parallel coordinate") self.origin_normal_label = Label(self.linescan_frame, text="Point of origin normal coordinate") self.linescan_angle_label = Label(self.linescan_frame, text="Angle to parallel axis in degrees") self.linescan_width_label = Label(self.linescan_frame, text="Linescan thickness intervall") self.origin_parallel_entry = Entry(self.linescan_frame) self.origin_normal_entry = Entry(self.linescan_frame) self.linescan_angle_entry = Entry(self.linescan_frame) self.linescan_width_entry = Entry(self.linescan_frame) self.create_linescan_button = Button(self.linescan_frame, text="Create linescan", command=self.create_line_scan) self.line_scale_log = Radiobutton(self.linescan_frame, text="Logarithmic", variable=self.line_scale, value="log") self.line_scale_linear = Radiobutton(self.linescan_frame, text="Linear", variable=self.line_scale, value="linear") self.rsm_plot_frame = Frame(master, relief=GROOVE, bd=2) self.rsm_plot_figure = Figure() self.rsm_canvas = FigureCanvasTkAgg(self.rsm_plot_figure, master=self.rsm_plot_frame) self.rsm_toolbar = NavigationToolbar2TkAgg(self.rsm_canvas, self.rsm_plot_frame) self.rsm_toolbar.update() self.rsm_canvas.show() self.linescan_plot_frame = Frame(master, relief=GROOVE, bd=2) self.linescan_plot_figure = Figure() self.linescan_canvas = FigureCanvasTkAgg(self.linescan_plot_figure, master=self.linescan_plot_frame) self.linescan_toolbar = NavigationToolbar2TkAgg(self.linescan_canvas, self.linescan_plot_frame) self.linescan_toolbar.update() self.linescan_canvas.show() self.place_widgets() def place_widgets(self): self.window_frame.place(x=10, y=10, width=425, height=520) self.fileselect_button.place(x=5, y=5, width=415, height=25) self.savebutton1.place(x=5, y=485, height=25, width=205) self.savebutton2.place(x=215, y=485, height=25, width=200) self.rsm_frame.place(x=5, y=35, height=220, width=415) self.rsm_label.place(x=5, y=5, height=25, width=405) self.rsm_parallel_lower_label.place(x=5, y=35, height=25, width=200) self.rsm_normal_lower_label.place(x=5, y=65, height=25, width=200) self.rsm_parallel_upper_label.place(x=5, y=95, height=25, width=200) self.rsm_normal_upper_label.place(x=5, y=125, height=25, width=200) self.rsm_parallel_lower_entry.place(x=210, y=35, height=25, width=200) self.rsm_parallel_upper_entry.place(x=210, y=65, height=25, width=200) self.rsm_normal_lower_entry.place(x=210, y=95, height=25, width=200) self.rsm_normal_upper_entry.place(x=210, y=125, height=25, width=200) self.rsm_sclae_linear.place(x=5, y=155, height=25, width=200) self.rsm_sclae_log.place(x=210, y=155, height=25, width=200) self.create_rsm_button.place(x=5, y=185, height=25, width=405) self.linescan_frame.place(x=5, y=260, width=415, height=220) self.linescan_label.place(x=5, y=5, width=405, height=25) self.origin_parallel_label.place(x=5, y=35, width=200, height=25) self.origin_normal_label.place(x=5, y=65, width=200, height=25) self.linescan_angle_label.place(x=5, y=95, width=200, height=25) self.linescan_width_label.place(x=5, y=125, width=200, height=25) self.origin_parallel_entry.place(x=210, y=35, width=200, height=25) self.origin_normal_entry.place(x=210, y=65, width=200, height=25) self.linescan_angle_entry.place(x=210, y=95, width=200, height=25) self.linescan_width_entry.place(x=210, y=125, width=200, height=25) self.line_scale_linear.place(x=5, y=155, width=200, height=25) self.line_scale_log.place(x=210, y=155, width=200, height=25) self.create_linescan_button.place(x=5, y=185, width=405, height=25) self.rsm_plot_frame.place(x=440, y=10, width=480, height=520) self.rsm_canvas.get_tk_widget().place(x=5, y=5, height=470, width=470) self.linescan_plot_frame.place(x=925, y=10, width=480, height=520) self.linescan_canvas.get_tk_widget().place(x=5, y=5, height=470, width=470) def select_file(self): self.file_path = askopenfilename() self.busy_label.configure(text="Be patient, I have a lot of data to read") self.RSM = Reciprocal(self.file_path) self.RSM.readfile() self.RSM.refine_data() self.busy_label.configure(text="") def create_rsm(self): if self.RSM is not None: self.busy_label.configure(text="Busy! Plotting %s data points." % len(self.RSM.intensity)) if self.rsm_parallel_lower_entry.get() != "": self.rsm_parallel_lower = float(self.rsm_parallel_lower_entry.get()) if self.rsm_parallel_upper_entry.get() != "": self.rsm_parallel_upper = float(self.rsm_parallel_upper_entry.get()) if self.rsm_normal_lower_entry.get() != "": self.rsm_normal_lower = float(self.rsm_normal_lower_entry.get()) if self.rsm_normal_upper_entry.get() != "": self.rsm_normal_upper = float(self.rsm_normal_upper_entry.get()) x = self.RSM.q_parallel y = self.RSM.q_normal if self.rsm_scale == "linear": z = self.RSM.intensity else: z = self.RSM.log_intensity ax = self.rsm_plot_figure.gca() ax.clear() ax.tricontourf(x, y, z, 1000, cmap="gist_rainbow") ax.tricontour(x, y, z, 8, colors="black") ax.set_ylabel(r"$q_{\perp} [\AA^{-1}]$") ax.set_xlabel(r"$q_{\parallel} [\AA^{-1}]$") ax.set_xlim(self.rsm_parallel_lower, self.rsm_parallel_upper) ax.set_ylim(self.rsm_normal_lower, self.rsm_normal_upper) ax.axis("equal") self.rsm_plot_figure.subplots_adjust(left=0.2) self.rsm_canvas.draw() self.busy_label.configure(text="") else: self.busy_label.configure(text="Select XRDML file first!") def create_line_scan(self): if self.RSM is not None: self.busy_label.configure(text="Busy! Processing %s data points." % len(self.RSM.intensity)) if self.origin_parallel_entry.get() != "": self.origin_parallel = float(self.origin_parallel_entry.get()) if self.origin_normal_entry.get() != "": self.origin_normal = float(self.origin_normal_entry.get()) if self.linescan_angle_entry.get() != "": self.linescan_angle = float(self.linescan_angle_entry.get()) if self.linescan_width_entry.get() != "": self.linescan_width = float(self.linescan_width_entry.get()) line = self.RSM.create_line_scan(self.origin_parallel, self.origin_normal, self.linescan_angle, self.linescan_width) bx = self.linescan_plot_figure.gca() bx.clear() bx.plot(line[0], line[1], '-o') bx.set_xlim(-0.005, 0.005) bx.set_yscale(self.line_scale.get()) bx.set_ylabel("Counts") bx.set_xlabel(r"Distance from origin $[\AA]^{-1}$") self.linescan_canvas.draw() self.busy_label.configure(text="") else: self.busy_label.configure(text="Select XRDML file first!") def savefigure(self, figure): if figure: figure.savefig(self.file_path+"_picture.png")
def select_image(): # grab a referance to the image panels global panelA, panelB, path # open a file chooser dialog path = tkFileDaialog.askopenfilename() # ensure a file path was selected if len(path) > 0: # load the image from disk image = cv2.imread(path) gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) edged = cv2.Canny(gray, 50, 100) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = Image.fromarray(image) image = ImageTk.PhotoImage(image) if panelA is None: panelA = Label(image=image) panelA.image = image panelA.pack(fill="both", expand="1") else: panelA.configure(image=image) panelA.image = image
def open_image(): global panel_original, panel_processed, btn_save, path, img_processed # работа с референсами path = filedialog.askopenfilename() # работа с диалогами if len(path) > 0: img_original = io.imread(path) # обработка изображений img_processed = feature.canny(img_original) # потенциальное место для создания вариантов - разные фильтры img_original_pil = Image.fromarray(img_original) # преобразование изображений в формат для демонстрации img_processed_pil = Image.fromarray(img_processed) img_original_tk = ImageTk.PhotoImage(img_original_pil) img_processed_tk = ImageTk.PhotoImage(img_processed_pil) if panel_original is None or panel_processed is None: panel_original = Label(image=img_original_tk) # работа с созданием гуйни panel_original.image = img_original_tk panel_original.grid(row=0, column=0, padx=10, pady=10) # размещение элементов гуйни panel_processed = Label(image=img_processed_tk) panel_processed.image = img_processed_tk panel_processed.grid(row=0, column=1, padx=10, pady=10) btn_save = Button(root, text="Сохранить результат", command=save_result) btn_save.grid(row=1, column=1, padx=10, pady=10) btn_open.grid(row=1, column=0, padx=10, pady=10) else: panel_original.configure(image=img_original_tk) panel_original.image = img_original_tk panel_processed.configure(image=img_processed_tk) panel_processed.image = img_processed_tk
def append_chords(self, chords=[]): '''pass a [list] of Chords to the Accordion object''' self.update_idletasks() row = 0 width = max([c.winfo_reqwidth() for c in chords]) for c in chords: i = PhotoImage() # blank image to force Label to use pixel size label = Label(self, text=c.title, image=i, compound='center', width=width, anchor='w', font=('Franklin Gothic Book', 11), bg=self.style['title_bg'], fg=self.style['title_fg'], cursor=self.style['cursor'], bd=1, relief='flat') label.grid(row=row, column=0, sticky='nsew') c.grid(row=row+1, column=0, sticky='nsew') c.grid_remove() row += 2 label.bind('<Button-1>', lambda e, c=c: self._click_handler(c)) label.bind('<Enter>', lambda e, label=label, i=i: label.configure(bg=self.style['highlight'],fg=self.style['highlight_fg'])) label.bind('<Leave>', lambda e, label=label, i=i: label.configure(bg=self.style['title_bg'],fg=self.style['title_fg']))
def update_info(): global numInfo global idInfo global wordInfo global gameDescInfo global gameDescTxt global searchInput global newStdInput global countInfo numInfo = Label(frame1, text=df.iloc[currentRow].game_num) numInfo.place(x=10, y=35) numInfo.configure(background = "black", foreground="white") idInfo = Label(frame1, text=df.iloc[currentRow].id) idInfo.place(x=100, y=35) idInfo.configure(background = "black", foreground="white") wordInfo = Label(frame1, text=df.iloc[currentRow].changed_word) wordInfo.place(x=200, y=35) wordInfo.configure(background = "black", foreground="white") countInfo = Label(frame1, text=df.iloc[currentRow].occurances) countInfo.place(x=200, y=125) countInfo.configure(background = "black", foreground="white") gameDescInfo = Label(frame1, text=df.iloc[currentRow].game_name) gameDescInfo.place(x=10, y=130) gameDescInfo.configure(background = "black", foreground="white") gameDescTxt.insert(1.0, "{}".format(df.iloc[currentRow].game_description)) searchInput.insert(0, df.iloc[currentRow].changed_word.split("_")[0]) newStdInput.insert(0, df.iloc[currentRow].changed_word.split("_")[0]) #inserts new value assigned by 2nd parameter highlight_word() search_word()
def createUI(self): FONT_SETTINGS = ('Consolas', 12) root = Tk() _ICON=PhotoImage(height=32, width=32) _ICON.blank() root.title('rsachatclient') root.resizable(width=True, height=True) root.geometry('1000x700') root.tk.call('wm', 'iconphoto', root._w, _ICON) frame = Frame(root, bg='#000') frame.place(relx=0, rely=0, relwidth=1, relheight=1) txt = Entry(frame, bg='#000', fg='#fff', font=FONT_SETTINGS) txt.place(relx=0.1, rely=0.95, relwidth=1, relheight=0.05) aliasLabel = Label(frame, bg='#000', fg='#fff', font=FONT_SETTINGS) aliasLabel.place(relx=0, rely=0.95, relwidth=0.1, relheight=0.05) outputMsgBox = Text(frame, bg='#000', fg='#fff', font=FONT_SETTINGS) outputMsgBox.place(relx=0, rely=0, width=1000, relheight=0.95) txt.bind('<Key>', self.input_control) txt.focus() self.UIRoot = root aliasLabel.configure(text=self.alias) self.inputTextBox = txt self.outputMsgBox = outputMsgBox
class SubWindow: def __init__(self, parent): self.parent = parent self.window = None self.label = None def init(self): if not self.window: self.window = Toplevel(self.parent) self.window.title("Asahi Serizawa") frame = Frame(self.window, width=256, height=256, relief='sunken') frame.pack_propagate(0) frame.pack(side=LEFT) self.label = Label(frame, text="Nothing yet!") self.label.pack(fill=BOTH, expand=True) self.window.protocol('WM_DELETE_WINDOW', self.this_window_close) self.window.mainloop() def change_image(self, image): self.label.configure(image=image, text="") self.label.image = image self.label.pack() def this_window_close(self): self.window.withdraw() self.window = None return "break"
class GUI: def __init__(self, master): self.master = master master.title("DOK Status") self.label = Label(master, text="DOK Status", bg="red") # Red = Disconnected color self.label.pack() def update_background_color(self): response = requests.get(URL) soup = BeautifulSoup(response.text, 'html.parser') # Check if the string 'Sorry. You are not using Tor.' exists on check.torproject.org not_using_tor_client = soup.findAll( text=compile('Sorry. You are not using Tor.')) # If it does exist, it means that the tor client isn't being used on the router # which means the DoK is disconnected. if not_using_tor_client: color = "red" # Color the background red if the DoK is disconnected. else: color = "green" # Color the background green if the DoK is connected. self.label.configure(bg=color) # Repeat this function every 1,000 milliseconds (1 second) self.label.after(1000, self.update_background_color)
class ServerInit: def __init__(self, master): cav = Canvas(master, width=400, height=50) cav.pack_propagate(0) self.lab = Label(master=cav, text="Test connection server ...", font='Helvetica 12 bold', anchor="center", pady=20) self.lab.pack() cav.pack() status = server_state() if status > 200: self.lab.configure(text="Test connection server ... FAILED", fg="red") master.after(5000, lambda: cav.destroy()) master.destroy() else: master.after( 1000, self.lab.configure(text="Test connection server ... SUCCESS", fg="green")) master.after(1500, lambda: cav.destroy()) master.after(1750, lambda: LoginPage(master))
def open_img(): global panelA, panelB file_path = open_file() image = cv2.imread(file_path) scanned = scanner(file_path) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = cv2.resize(image, (600,600), interpolation=cv2.INTER_NEAREST) #return scanned_image global return_file return_file = scanned image = Image.fromarray(image) scanned = Image.fromarray(scanned) image = ImageTk.PhotoImage(image) scanned = ImageTk.PhotoImage(scanned) if panelA is None or panelB is None: panelA = Label(image=image) panelA.image = image panelA.pack(side="left",padx=10, pady=10) panelB = Label(image=scanned) panelB.image = scanned panelB.pack(side="right",padx=10, pady=10) else: panelA.configure(image=image) panelB.configure(image=scanned) panelA.image = image panelB.image = scanned
def aboutApp(): # creation about-window if there is not (85 = 9x9 + 4; 260 = 16x16 + 4; 484 = 16x32 + 4) if window.winfo_children().__len__() in (85, 260, 484): aboutWindow = Toplevel(window) aboutWindow.title("About Minesweeper") aboutWindow.geometry("270x125") aboutWindow.resizable(False, False) aboutWindow.wm_geometry("+%d+%d" % ((aboutWindow.winfo_screenwidth() / 2 - aboutWindow.winfo_reqwidth()), (aboutWindow.winfo_screenheight() / 2 - aboutWindow.winfo_reqheight()))) _ = Label(aboutWindow, text="Minesweeper by Andrew Jeus", font=("", 18)).grid(row=0, column=0, padx=10, pady=10) _ = Label(aboutWindow, text="Version 1.0 (12 July 2019)", font=("", 18)).grid(row=1, column=0) labelInfo3 = Label(aboutWindow, text="View code in GitHub", font=("", 14)) labelInfo3.grid(row=2, column=0, padx=5, pady=5) # my font for link to GitHub myfont = font.Font(labelInfo3, labelInfo3.cget("font")) myfont.configure(underline=True) labelInfo3.configure(font=myfont) labelInfo3.bind( "<Button-1>", lambda _: webbrowser.open_new( "https://github.com/MickeyMouseMouse/Minesweeper"))
class TInfo(Frame, Observer): def __init__(self, info, master=None): Frame.__init__(self, master=master) Observer.__init__(self, info) self.__info = info self.__info_label = Label(self, text='Information', font='Ubuntu 20 bold') self.__ip_frame = Frame(self) self.__ip_property_label = Label(self.__ip_frame, text='Address IP: ') self.__ip_value_label = Label(self.__ip_frame, text=self.__info.ip, background='orange') self.__port_frame = Frame(self) self.__port_property_label = Label(self.__port_frame, text='Port: ') self.__port_value_label = Label(self.__port_frame, text=self.__info.port, background='orange') self.__description_label = Label(self, text=self.__info.description, wraplength=200) self.__setup_all__() def __setup_all__(self): self.__info_label.pack(pady=10) self.__ip_frame.pack(pady=6) self.__ip_property_label.pack(side=LEFT, padx=3) self.__ip_value_label.pack(side=LEFT, padx=3) self.__port_frame.pack(pady=6) self.__port_property_label.pack(side=LEFT, padx=3) self.__port_value_label.pack(side=LEFT, padx=3) self.__description_label.pack(pady=6) def notify(self, information=None): self.__ip_value_label.configure(text=self.__info.ip) self.__port_value_label.configure(text=self.__info.port)
class TInfo(Frame, Observer): def __init__(self, info, master=None): Frame.__init__(self, master=master) Observer.__init__(self, info) self.__info = info self.__info_label = Label(self, text="Connection information", font="Ubuntu 16 bold") self.__ip_port_frame = Frame(self) self.__ip_property_label = Label(self.__ip_port_frame, text='Address IP: ') self.__ip_value_label = Label(self.__ip_port_frame, text=self.__info.ip, background='orange') self.__port_property_label = Label(self.__ip_port_frame, text=' Port: ') self.__port_value_label = Label(self.__ip_port_frame, text=self.__info.port, background='orange') self.__setup_all__() def __setup_all__(self): self.__info_label.pack(pady=8) self.__ip_port_frame.pack(pady=6) self.__ip_property_label.pack(side=LEFT, padx=3) self.__ip_value_label.pack(side=LEFT, padx=3) self.__port_property_label.pack(side=LEFT, padx=3) self.__port_value_label.pack(side=LEFT, padx=3) def notify(self, information=None): self.__ip_value_label.configure(text=self.__info.ip) self.__port_value_label.configure(text=self.__info.port)
class TkLCD(TkDevice): def __init__(self, root, x, y, name, pins, columns, lines): super().__init__(root, x, y, name) self._redraw() self._pins = pins self._columns = columns self._lines = lines if system() == "Darwin": font = ("Courier", 25) else: font = ("Courier New", 20) self._label = Label(root, font=font, justify="left", anchor="nw", width=columns, height=lines, padx=5, pady=5, background="#82E007", borderwidth=2, relief="solid") self._label.place(x=x, y=y) def update_text(self, pins, text): if pins == self._pins: self._label.configure(text=text) self._root.update()
def build_options_list(self): """ Construit la liste des options disponibles :return: list(IntVar) - Liste contenant les identifiants des options """ # Label opt_label = Label(self, text="Options") opt_label.configure(font=font.Font(family=Config.FONT["main"], size=Config.SIZE["large"]), background=Config.COLOR["main-bg"], foreground=Config.COLOR["main-fg"]) opt_label.grid(sticky='w', padx=10) # Checkbox opt_list = [] for text in Menu.OPTIONS: x = IntVar() ckb = Checkbutton(self, text=text, variable=x, tristatevalue=0) ckb.configure(font=font.Font(family=Config.FONT["main"], size=Config.SIZE["medium"]), background=Config.COLOR["main-bg"], foreground=Config.COLOR["main-fg"], activebackground=Config.COLOR["main-bg"], activeforeground=Config.COLOR["main-fg"], selectcolor=Config.COLOR["main-bg"]) ckb.grid(sticky='w', padx=20) opt_list.append(x) return opt_list
def __create_about_window(self): """ Create about window """ window_about = Toplevel(self._tk_obj, bg='#ccc') window_about.title("About " + str(self.__window_title)) window_about.geometry("250x250") window_about.resizable(width=FALSE, height=FALSE) about_ety_headline = Label(window_about, text="What's this?") about_ety_headline.configure(font=self.__FONT_HEADLINE, background='#ccc') about_ety_headline.pack() txt = "This is a simple GUI for RfCat\n" \ "via Python tkinter.\n\n" \ "The developer of this tool is not\n" \ "responsible for issues, mistakes\n" \ "or illegal activities!\n\n" \ "Feel free to use this software as is\n" \ "for personal use only.\n" \ "Do not use this code in other\n" \ "projects or in commercial products.\n" about_ety_text = Label(window_about, text=txt) about_ety_text.configure(font=self.__FONT_STYLE, background='#ccc') about_ety_text.pack(fill=BOTH)
def build_heuristics_list(self): """ Construit la liste des heuristiques disponibles :return: IntVar - Identifiant de la liste des boutons """ # Label heuristic_label = Label(self, text="Choix de l'heuristique") heuristic_label.configure(font=font.Font(family=Config.FONT["main"], size=Config.SIZE["large"]), background=Config.COLOR["main-bg"], foreground=Config.COLOR["main-fg"]) heuristic_label.grid(sticky='w', padx=10) # Radio buttons x = IntVar(value=1) for index, text in enumerate(Menu.HEURISTICS): rdo = Radiobutton(self, text=text, variable=x, value=index + 1, tristatevalue=0) rdo.configure(font=font.Font(family=Config.FONT["main"], size=Config.SIZE["medium"]), background=Config.COLOR["main-bg"], foreground=Config.COLOR["main-fg"], activebackground=Config.COLOR["main-bg"], activeforeground=Config.COLOR["main-fg"], selectcolor=Config.COLOR["main-bg"]) rdo.grid(sticky='w', padx=20) return x
def __configure_UI(self): self.from_currency = StringVar() menu_from_currency = OptionMenu(self, self.from_currency, *self.Constants.country_list) self.from_currency.set(self.Constants.country_list[30]) menu_from_currency.grid(row = 0, column = 0, sticky = self.Constants.center) self.to_currency = StringVar() menu_to_currency = OptionMenu(self, self.to_currency, *self.Constants.country_list) self.to_currency.set(self.Constants.country_list[18]) menu_to_currency.grid(row = 0, column = 2, sticky = self.Constants.center) separator_label = Label(self) separator_label.configure(text = self.Constants.separator_text) separator_label.grid(row = 1, column = 1, sticky = self.Constants.center) self.__result_label = Label(self) self.__result_label.configure(text = "0") self.__result_label.grid(row = 1, column = 2, sticky = self.Constants.center) self.__convert_button = Button(self) self.__convert_button.configure(text = self.Constants.convert_text) self.__convert_button.grid(row = 2, column = 1, sticky = self.Constants.center) self.__convert_button.bind(self.Constants.event, self.__did_tap_convert) vcmd = (self.register(self.__checkNumberOnly), '%d', '%P') self.__currency_input = Entry(self, validate = "key", validatecommand = vcmd) self.__currency_input.grid(row = 1, column = 0, sticky = self.Constants.center)
def about_Us(): global about_us_window1,Label about_us_window1 = Tk() about_us_window1.geometry("1920x1080") about_us_window1.title("About_Us") about_us_window1.config(bg="gray") phto_label = Label( about_us_window1) phto_label.place(x=50,y=500) Image1 = Image.open("img2.jpg") photo = ImageTk.PhotoImage(Image1) phto_label.configure(image=photo) phto_label.image = photo phto_label.place(x=250, y=30) phto_label = Label(about_us_window1) phto_label.place(x=50, y=900) Image1 = Image.open("img3.jpg") photo = ImageTk.PhotoImage(Image1) phto_label.configure(image=photo) phto_label.image = photo phto_label.place(x=750, y=30) about_us_label_phn_no = Label(about_us_window1, text="Manyavart Sarees", font='Helvetica 25 bold',bg="gray",fg="Blue") about_us_label_phn_no.place(x=600, y=240) var = StringVar() about_us_content = Message(about_us_window1, textvariable=var, width=600, font="Helvetica 15 bold",bg="gray",fg="black") var.set("""Let Manyavart Deliver The Pure Fabrics You Deserve. Stay Safe & Enjoy Your Classy Wear. Don’t Let Your Wardrobe Go Old. Stay Indoors & Shop Online From The Trendy Collections, The wedding you’re invited to is right around the corner, and so is that important presentation at work, or your child’s sports day event. Time has outrun you and now you have nothing to wear? Fear not. We are here to amaze you with our wide collection of beautifully crafted sarees for your day out. At Manyavart, we make the whole experience of designer sarees online shopping as exciting as it ever is. Take it from us, there is hardly anything as enchanting as a well draped nine yard and we know you love it just as much; pamper yourself with a wide range of beautifully crafted sarees for a multitude of occasions ranging from elegant cotton sarees to pompous and dressy designer sarees on our online store. Buy Women Sarees Online at Manyavart & Get 100% Cashback on Every Order Shop Now. Banarasi Saree, Cotton Saree, Silk Saree, Kanjivaram Saree, Printed Saree, Designer Saree. """) about_us_content.place(x=500, y=300) about_us_window1.mainloop()
class BuildBoxEmulator(threading.Thread): def __init__(self): threading.Thread.__init__(self) self._image = None self._panel = None self._tk_image = None self._top = None self._digital_display_value = None self.start() def run(self): self._top = Tk() self._digital_display_value = StringVar() self._digital_display_value.set("42.17") # cf. https://www.google.fr/search?q=digital+7+ttf myFont = Font(family="Digital-7", size=42) # , weight="bold") label = Label(self._top, textvariable=self._digital_display_value, font=myFont, fg="red", bg="black") label.pack() self._top.mainloop() def update_digital_display(self, string): self._digital_display_value.set(string) def update_graphic_display(self, image): self._image = image self._tk_image = ImageTk.PhotoImage(self._image) if self._panel is None: self._panel = Label(self._top, image=self._tk_image) self._panel.pack(side="bottom", fill="both", expand="yes") else: self._panel.configure(image=self._tk_image)
def check_login(): R_name = registration_no.get() #get password from entry R_password = psw.get() #get password from entry success = 0 for x in range(0, len(L)): if (L[x] == (R_name, R_password)): success = 1 if success == 1: print('Login Success') label2 = Label(login_page, text="Login Success") label2.configure(background="#fffff0") label2.configure(foreground="#00ff00") label2.config(font=("Courier", 15)) label2.place(x=750, y=500, height=50, width=500) login_page.update() time.sleep(2) login_page.destroy() Result.get() else: print('Denied') label2 = Label(login_page, text="Login Fail") label2.configure(background="#fffff0") label2.configure(foreground="#ff0000") label2.config(font=("Courier", 15)) label2.place(x=750, y=500, height=50, width=500) login_page.update() time.sleep(2) login_page.destroy()
def __configure_UI(self): self.currency_dropdown_menu_var = StringVar() currency_dropdown_menu = OptionMenu(self, self.currency_dropdown_menu_var,*self.Constants.options_currency) self.currency_dropdown_menu_var.set("USD") currency_select = Label(textvariablecurrency=self.currency_dropdown_menu_var) currency_dropdown_menu.grid(row=0, column=0, sticky=self.Constants.left) self.result_dropdown_menu_var = StringVar() result_dropdown_menu = OptionMenu(self, self.result_dropdown_menu_var,*self.Constants.options_result) self.result_dropdown_menu_var.set("MXN") result_select = Label(textvariableresult=self.result_dropdown_menu_var) result_dropdown_menu.grid(row=0, column=2, sticky=self.Constants.left) separator_label = Label(self) separator_label.configure(text= self.Constants.separator_text) separator_label.grid(row=1, column=1, sticky=self.Constants.center) self.__result_label = Label(self) self.__result_label.configure(text="0") self.__result_label.grid(row=1, column=2, sticky=self.Constants.left) self.__convert_button = Button(self) self.__convert_button.configure(text = self.Constants.convert_text) self.__convert_button.grid(row=2, column=2, sticky=self.Constants.center) self.__convert_button.bind(self.Constants.event, self.__did_tap_convert) vcmd = (self.register(self.__checkNumberOnly), '%d', '%P') self.__currency_input = Entry(self, validate="key", validatecommand = vcmd) self.__currency_input.grid(row=1, column=0, sticky=self.Constants.center)
class ConwaysGame: def __init__(self, root): self.cells = {(0, 0), (1, 0), (2, 0), (0, 1), (1, 2)} self.cells = get_random_cells(30) self.screen_size = int( min(root.winfo_screenwidth(), root.winfo_screenheight()) / 1.5) self.image_label = Label(master=root, bg='white') self.image_label.pack() def run(self): while self.screen_size: img = get_image(self.cells, self.screen_size) self.image_label.configure(image=img) self.cells = self.advance(self.cells) sleep(0.15) self.image_label.quit() def set_inactive(self): self.screen_size = 0 def advance(self, cells): new_cells = defaultdict(int) for cell_x, cell_y in cells: for x in range(cell_x - 1, cell_x + 2): for y in range(cell_y - 1, cell_y + 2): new_cells[(x % size, y % size)] += 1 return set( filter( lambda key: new_cells[key] == 3 or (new_cells[key] == 4 and key in cells), new_cells.keys()))
class Primitive(Frame): def __init__(self, parent=None, **kargs): Frame.__init__(self, parent, **kargs) self.pack() self.construccion() self.iteracion = 0 # estado def construccion(self): Label(self, text='Pulsa el botón para generar una combinación').pack() self.label = Label(self, text="Combinación", width=50) self.label.pack(side="left") Button(self, text="Nueva", command=self.sorteo).pack() def combinacion(self): numeros = random.sample(range(1, 99), 6) numeros.sort() complementarios = random.sample(range(1, 99), 1) joker = random.sample(range(1000000, 9999999), 1) reintegro = random.sample(range(1, 99), 1) return (str(numeros).strip('[]') + ' C: ' + str(complementarios).strip('[]') + ' Joker: ' + str(joker).strip('[]') + ' Reintegro: ' + str(reintegro).strip('[]')) def sorteo(self): self.iteracion += 1 # Actualiza n° de iteraciones self.label.configure(text=self.combinacion())
def body(self, master): dialogframe = Frame(master, width=536, height=225) self.dialogframe = dialogframe dialogframe.pack() self.RadioGroup_1_StringVar = StringVar() self.make_LabelFrame_1( self.dialogframe) # LabelFrame: Colors : at Main(5,1) self.make_Label_1( self.dialogframe) # Label: Left Click Color : at Main(2,1) self.make_Label_3( self.dialogframe ) # Label: Luminance and Contrast Ratio shown above : at Main(4,1) self.make_RadioGroup_1( self.dialogframe) # RadioGroup: Sort By: : at Main(1,1) self.make_Radiobutton_1( self.RadioGroup_1) # Radiobutton: HSV hue : at RadioGroup_1(1,1) self.make_Radiobutton_2( self.RadioGroup_1 ) # Radiobutton: W3 Luminance : at RadioGroup_1(1,2) self.make_Radiobutton_3( self.RadioGroup_1 ) # Radiobutton: HEX String : at RadioGroup_1(1,3) self.make_Radiobutton_4( self.RadioGroup_1 ) # Radiobutton: Color Name : at RadioGroup_1(1,4) self.RadioGroup_1_StringVar.set("1") self.RadioGroup_1_StringVar_traceName = self.RadioGroup_1_StringVar.trace_variable( "w", self.RadioGroup_1_StringVar_Callback) # >>>>>>insert any user code below this comment for section "top_of_init" self.labelD = {} # index=(row,col): value=Label object row = 0 col = 0 for (lum, lum_p05, h, r, g, b, cstr, name) in h_sorted_colorL: lab = Label(self.LabelFrame_1, text=" ", width="3", padx=0, pady=0, font=("times", "6", "normal")) lab.grid(row=row, column=col) self.labelD[(row, col)] = lab lab.configure(background=cstr, relief="raised") lab.bind("<Enter>", self.label_enter) lab.bind("<Leave>", self.label_leave) lab.bind("<ButtonRelease-1>", self.ColorPickLabel_LeftClick) col += 1 if col >= COL_COUNT: col = 0 row += 1 self.tw = None self.named_selectionT = lum_sorted_colorL[-1] # set selection to white self.named_label = None
class Titre(Frame): def __init__(self, boss, item): Frame.__init__(self, boss) self.configure() # attributs self.root = boss.master.master self.item = item # construction du corps self.label = Label(self, **KW_TITRE) self.canvas = Canvas(self, height=MARGE_HAUTE_SALLE, **KW_CANVAS) # ajout widget à la base self.root.th.add_widget("titre", self.label) self.root.th.add_widget("canvas", self.canvas) self.root.th.add_widget("frame", self) def display(self): if self.item == "afficher la salle": # cas particulier de la salle self.canvas.pack() elif self.item == "first": pass else: # cas général self.label.configure(text=self.item.upper()) self.label.pack(**PAD_TITRE) self.pack() def hide(self): self.pack_forget()
def select_image(): #gets the gui pannel for the image global panelA #gets the path of the user image through windows file explorer path = filedialog.askopenfilename() #if the path isint empty if len(path) > 0: #read in image from path image = cv2.imread(path) #convert the colour of the image to a format that can be displayed by pythons pillow library image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) #preps the user image for predicition prepImage = prep_image(image) #predicts the digit in the user image prediction = predict_image(prepImage) #tempdisplay for pridiction print(prediction) #formats the image for display in the gui image = Image.fromarray(image) #reformats the image to a photoimage image = ImageTk.PhotoImage(image) #if panelA dosent exist initilise it if panelA is None: #panel will store our original image panelA = Label(image=image) panelA.image = image panelA.pack(side="left", padx=10, pady=10) # else update the image panel with new image else: # update the pannels panelA.configure(image=image) panelA.image = image
def __configure_UI(self): self.initial_var = StringVar() self.initial_var.set(self.Constants.names[0]) self.from_menu = OptionMenu(self, self.initial_var, *self.Constants.names) self.from_menu.grid(row=0, column=0, sticky=self.Constants.left) self.final_var = StringVar() self.final_var.set(self.Constants.names[1]) self.to_menu = OptionMenu(self, self.final_var, *self.Constants.names) self.to_menu.grid(row=0, column=2, sticky=self.Constants.left) separator_label = Label(self) separator_label.configure(text=self.Constants.separator_text) separator_label.grid(row=1, column=1, sticky=self.Constants.center) self.__result_label = Label(self) self.__result_label.configure(text="0") self.__result_label.grid(row=1, column=2, sticky=self.Constants.left) self.__convert_button = Button(self) self.__convert_button.configure(text=self.Constants.convert_text) self.__convert_button.grid(row=2, column=2, sticky=self.Constants.center) self.__convert_button.bind(self.Constants.event, self.__did_tap_convert) vcmd = (self.register(self.__checkNumberOnly), '%d', '%P') self.__currency_input = Entry(self, validate="key", validatecommand=vcmd) self.__currency_input.grid(row=1, column=0, sticky=self.Constants.center)
def doPopup(self, Type="Undefined", Text="Empty"): toplevel = Toplevel() # set minimum size toplevel.minsize(200, 10) # configure weight and amount of columns and rows self.configureEvenWeight(toplevel, 3, 3) toplevel.focus_force() def selfDestroy(_event=None): toplevel.destroy() def setKeybinds(component): component.bind("<Key>", selfDestroy) def getPopupMessage(Type="Undefined", Text="Empty"): if type == "Lost": return "You lost." + "\n" + "Please try again!" elif Type == "Draw": return "Its a draw!" + "\n" + "Please try again!" elif Type == "Win": return "Congratulations!" + "\n" + "{0} won!".format( Text).capitalize() elif Type == "specialWin": return "Congratulations, you won against the not yet unbeatable ai." + "\n" + "That technique won't work again!".capitalize( ) return "Something went wrong." + "\n" + "Please contact the developer about this problem." setKeybinds(toplevel) label1 = Label(toplevel) label1.grid(row=1, column=1, sticky=NSEW) if Type == "Undefined" and Text == "Empty": message = "Something went wrong." + "\n" + "Please contact the developer about this problem." else: message = getPopupMessage(Type, Text) label1.configure(text=message)
class Location_Tracker: def __init__(self, App): self.window = App self.window.title("Phone number Tracker") self.window.geometry("500x400") self.window.configure(bg="#3f5efb") self.window.resizable(False, False) Label(App, text="Enter a phone number",fg="white", font=("Times", 20), bg="#3f5efb").place(x=150, y=30) self.phone_number = Entry(App, width=16, font=("Arial", 15), relief="flat") self.track_button = Button(App, text="Track Country", bg="#22c1c3", relief="sunken") self.country_label = Label(App,fg="white", font=("Times", 20), bg="#3f5efb") self.phone_number.place(x=170, y=120) self.track_button.place(x=200, y=200) self.country_label.place(x=100, y=280) self.track_button.bind("<Button-1>", self.Track_location) def Track_location(self, event): phone_number = self.phone_number.get() country = "Country is Unknown" if phone_number: tracked = pycountry.countries.get(alpha_2=phone_country(phone_number)) print(tracked) if tracked: country = tracked.official_name self.country_label.configure(text=country)
class ResultPage(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.controller.title('Test') self.controller.geometry('600x600') chooseButton = Button(self, text='Back',command=lambda: self.controller.show_frame("ImagePage"), fg='RED',font=('Arial', 12)) chooseButton.pack(side="top", fill="x", pady=10) segmentButton = Button(self, text='Segment', command=self.segment) segmentButton.pack(side="top", fill="x", pady=10) self.predictedLabel = Label(self,font=('Arial', 12),text='Predicted label is') self.predictedLabel.pack(side="top", padx=20) # Set the artboard to put in the Grad-CAM. def render(self): print("Drawing figures with label {}".format(self.controller.label)) self.controller.geometry('600x600') self.predictedLabel.configure(text='Predicted label is {}'.format(self.controller.label)) self.attention1=Image.open('image/attention.jpg') self.attention=ImageTk.PhotoImage(self.attention1) self.heatmapLabel=Label(self,image=self.attention) self.heatmapLabel.pack() def segment(self): frame = self.controller.show_frame("SegmentPage")
def __configure_UI(self): self.listOne = StringVar(self) self.listOne.set(self.Constants.Currencies[0]) self.dropCurrencyFrom = OptionMenu(self, self.listOne, *self.Constants.Currencies) self.dropCurrencyFrom.grid(row = 0, column = 0, sticky = self.Constants.left) self.listTwo = StringVar(self) self.listTwo.set(self.Constants.Currencies[1]) self.dropCurrencyTo = OptionMenu(self, self.listTwo, *self.Constants.Currencies) self.dropCurrencyTo.grid(row = 0, column = 2, sticky = self.Constants.left) separator_label = Label(self) separator_label.configure(text = self.Constants.separator_text) separator_label.grid(row = 1, column = 1, sticky = self.Constants.center) self.__result_label = Label(self) self.__result_label.configure(text = "0") self.__result_label.grid(row = 1, column = 2, sticky = self.Constants.left) self.__convert_button = Button(self) self.__convert_button.configure(text = self.Constants.convert_text) self.__convert_button.grid(row = 2, column = 2, sticky = self.Constants.center) self.__convert_button.bind(self.Constants.event, self.__did_tap_convert) vcmd = (self.register(self.__checkNumberOnly), '%d', '%P') self.__currency_input = Entry(self, validate = "key", validatecommand = vcmd) self.__currency_input.grid(row = 1, column = 0, sticky = self.Constants.center)
class Channel(Frame): """ Stuff a channel tracks: - The track number - Recording - Active - Muted - Sticky - Non-empty """ def __init__(self, parent, trackNumber): Frame.__init__(self, parent, relief = RAISED, borderwidth = 3, background = 'black') self.channel = trackNumber self.record = False self.nonEmpty = False self.active = False self.sticky = False self.label = Label(self) self.label.pack() self.__updateStatus() self.configure(relief = RAISED) def __updateStatus(self): # First and last characters are brackets for the active track. # Second character is 'R' for recording, 'P' for playing and ' ' for # empty. Third character is '*' for sticky, ' ' if not. self.label.configure(text = '%d: %s%s%s%s' % ( self.channel, self.active and '[' or ' ', self.record and 'R' or self.nonEmpty and 'P' or ' ', self.sticky and '*' or ' ', self.active and ']' or ' ' )) def changeStatus(self, status): self.nonEmpty = status & NONEMPTY self.record = status & RECORD self.sticky = status & STICKY self.active = status & ACTIVE print('changing status of %d, nonempty = %s, record = %s, ' 'sticky = %s, active = %s' % (self.channel, self.nonEmpty, self.record, self.sticky, self.active)) self.__updateStatus()
class AddManually(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.place(relx=0.0, rely=0.0, relheight=0.62, relwidth=0.72) self.configure(relief=GROOVE) self.configure(borderwidth="2") self.configure(relief=GROOVE) self.configure(width=125) self.label_top = Label(self) self.label_top.place(relx=0.4, rely=0.03, height=21, width=112) self.label_top.configure(text="Add items manually") self.name = Entry(self, fg='grey') self.name.place(relx=0.05, rely=0.31, relheight=0.08, relwidth=0.29) self.name.insert(0, "Input name here") self.name.bind('<Button-1>', lambda event: greytext(self.name)) self.link = Entry(self, fg='grey') self.link.place(relx=0.65, rely=0.31, relheight=0.08, relwidth=0.29) self.link.insert(0, "Input link here") self.link.bind('<Button-1>', lambda event: greytext(self.link)) self.add_btn = Button(self, command=self.send_data) self.add_btn.place(relx=0.42, rely=0.44, height=34, width=100) self.add_btn.configure(text="Add item") self.back = Button(self, command=lambda: controller.show_frame('Main')) self.back.place(relx=0.42, rely=0.64, height=34, width=100) self.back.configure(text="Go back") name_label = Label(self) name_label.place(relx=0.05, rely=0.22, height=21, width=38) name_label.configure(text="Name") link_label = Label(self) link_label.place(relx=0.65, rely=0.22, height=21, width=28) link_label.configure(text="Link") def send_data(self): if self.link.cget('fg') == 'grey' or self.name.cget('fg') == 'grey': return link = self.link.get() if link.strip() != '': name = self.name.get() self.controller.add_item(link, name) print("Item added")
class ControlWidget(Frame): '''Control widget class.''' def __init__(self, parent, handler): '''Initialization method.''' Frame.__init__(self, parent) button_frame = Frame(self) button_frame.pack(side=TOP) self.deal_button = Button(button_frame, text="Deal", command=lambda: handler("deal")) self.deal_button.pack(side=LEFT, padx=5, pady=5) self.quit_button = Button(button_frame, text="Quit", command=lambda: handler("quit")) self.quit_button.pack(side=RIGHT, padx=5, pady=5) self.exchange_button = Button(button_frame, text="Exchange", command=lambda: handler("exchange")) self.exchange_button.pack(side=RIGHT, padx=5, pady=5) self.show_button = Button(button_frame, text="Show", command=lambda: handler("show")) self.show_button.pack(side=RIGHT, padx=5, pady=5) label_frame = Frame(self) label_frame.pack(side=BOTTOM) self.status_label = Label(label_frame, relief=SUNKEN) self.set_status_text("No text to show") self.status_label.pack(side=TOP, padx=5, pady=5) def set_status_text(self, text): '''Sets the text of the status label.''' self.status_label.configure(text=text)
class PreferenceRanking(ttk.Frame): """Allows a DM to be selected and displays that DMs state ranking.""" def __init__(self, master, conflict, dm, idx): """Initialize a PreferenceRanking widget.""" ttk.Frame.__init__(self, master, borderwidth=2) self.conflict = conflict self.dm = dm self.dmIdx = idx self.dmText = StringVar(value=dm.name + ': ') self.dmLabel = Label(self, textvariable=self.dmText) self.dmLabel.grid(row=0, column=0, sticky=NSEW) if len(conflict.feasibles) < 1000: self.prefRankText = StringVar(value=str(dm.perceivedRanking)) else: self.prefRankText = StringVar(value="Too Many States") self.prefRank = ttk.Label(self, textvariable=self.prefRankText, relief="sunken", width=40) self.prefRank.grid(row=1, column=0, sticky=NSEW) self.selectBtn = ttk.Button(self, text="Edit", command=self.selectCmd) self.selectBtn.grid(row=0, column=1, rowspan=2, sticky=NSEW) self.columnconfigure(0, weight=1) def selectCmd(self, *args): """Propagate a selection event up to the parent widget.""" self.event_generate('<<DMselect>>', x=self.dmIdx) def deselect(self, *args): """Change the widget to the deselected state.""" self.configure(relief='flat') self.dmLabel.configure(bg="SystemButtonFace") def select(self, *args): """Change the widget to the selected state.""" self.configure(relief='raised') self.dmLabel.configure(bg="green")
class GUI: """A simple GUI for the PLD heater""" def __init__(self, master): self.PLD_port = "COM5" self.PLD_address = 5 self.PLD = None self.pyrometer_port = "COM10" self.pyrometer = None self.active_plot = 1 self.start_time = None self.label_updater = Thread() self.pyrometer_pld_communication = Thread() self.icon_left = PhotoImage(file="Button_left.png") self.icon_right = PhotoImage(file="Button_right.png") self.window_frame = Frame(master, bd=2, relief=GROOVE) self.sensor_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.parameter_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.graph_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.connect_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.log_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.plot_frame = Frame(self.window_frame, bd=2, relief=GROOVE) self.oven_temperature_label = Label(self.sensor_frame, text="Oven temperature: °C") self.external_temperature_label = Label(self.sensor_frame, text="Sample temperature: °C") self.working_setpoint_label = Label(self.sensor_frame, text="Working setpoint: °C") self.working_output_label = Label(self.sensor_frame, text="Working ouput %") self.power_output_label = Label(self.parameter_frame, text="Power output %") self.power_output_entry = Entry(self.parameter_frame) self.power_output_setter_button = Button(self.parameter_frame, text="Set power output [%]", command=self.set_target_output_power, state=DISABLED) self.setpoint_label = Label(self.parameter_frame, text="Setpoint: °C") self.setpoint_entry = Entry(self.parameter_frame) self.setpoint_setter_button = Button(self.parameter_frame, text="Set target setpoint [°C]", command=self.set_target_setpoint, state=DISABLED) self.mode_label = Label(self.parameter_frame, text="Manual control mode") self.mode_switcher_button = Button(self.parameter_frame, text="Switch mode", command=self.switch_mode, state=DISABLED) self.external_sensor_mode_label = Label(self.parameter_frame, text="External sensor mode off") self.external_sensor_mode_button = Button(self.parameter_frame, text="Enable external sensor mode", command=self.enable_external_sensor_temperature, state=DISABLED) self.hold_temperature_button = Button(self.parameter_frame, text="Hold temperature", command=self.hold_temperature, state=DISABLED) self.PLD_com_port_entry = Entry(self.connect_frame) self.PLD_com_port_label = Label(self.connect_frame, text="PLD COM Port") self.PLD_slave_address_entry = Entry(self.connect_frame) self.PLD_salve_address_label = Label(self.connect_frame, text="PLD slave Address (Default 1)") self.PLD_connect_button = Button(self.connect_frame, text="Connect PLD", command=self.connect_pld) self.pyrometer_com_port_entry = Entry(self.connect_frame) self.pyrometer_com_port_label = Label(self.connect_frame, text="Pyrometer COM Port") self.pyrometer_connect_button = Button(self.connect_frame, text="Connect Pyrometer", command=self.connect_pyrometer) self.start_label_updater_button = Button(self.connect_frame, text="Start", command=self.start_label_updater, state=DISABLED) self.log_label = Label(self.log_frame, text="Temperature Log") self.log_text = Text(self.log_frame) self.switch_plot_left_button = Button(self.plot_frame, command=self.switch_plot_left, image=self.icon_left) self.switch_plot_right_button = Button(self.plot_frame, command=self.switch_plot_right, image=self.icon_right) self.plot_label = Label(self.plot_frame, text="Oven temperature") self.pyrometer_plot_frame = Frame(self.plot_frame) self.oven_temperature_plot_frame = Frame(self.plot_frame) self.power_ouput_plot_frame = Frame(self.plot_frame) self.pyrometer_plot = Plot(self.pyrometer_plot_frame, "Time [min]", "T\n\n°C", 350) self.power_ouput_plot = Plot(self.power_ouput_plot_frame, "Time [min]", "P\n\n%", 350) self.oven_temperature_plot = Plot(self.oven_temperature_plot_frame, "Time [min]", "T\n\n°C", 350) self.place_widgets() def place_widgets(self): """Place each widgets""" self.window_frame.place(x=10, y=10, height=415, width=1010) self.connect_frame.place(height=105, width=630, x=10, y=10) self.pyrometer_com_port_label.place(height=25, width=200, x=10, y=10) self.pyrometer_com_port_entry.place(height=25, width=200, x=215, y=10) self.pyrometer_connect_button.place(height=25, width=200, x=420, y=10) self.PLD_com_port_label.place(height=25, width=200, x=10, y=40) self.PLD_com_port_entry.place(height=25, width=200, x=215, y=40) self.PLD_connect_button.place(height=25, width=200, x=420, y=40) self.PLD_salve_address_label.place(height=25, width=200, x=10, y=70) self.PLD_slave_address_entry.place(height=25, width=200, x=215, y=70) self.start_label_updater_button.place(height=25, width=200, x=420, y=70) self.parameter_frame.place(height=135, width=630, x=10, y=125) self.setpoint_label.place(height=25, width=200, x=10, y=10) self.setpoint_entry.place(height=25, width=200, x=215, y=10) self.setpoint_setter_button.place(height=25, width=200, x=420, y=10) self.power_output_label.place(height=25, width=200, x=10, y=40) self.power_output_entry.place(height=25, width=200, x=215, y=40) self.power_output_setter_button.place(height=25, width=200, x=420, y=40) self.mode_switcher_button.place(height=25, width=405, x=215, y=70) self.mode_label.place(height=25, width=200, x=10, y=70) self.external_sensor_mode_label.place(height=25, width=200, x=10, y=100) self.external_sensor_mode_button.place(height=25, width=200, x=215, y=100) self.hold_temperature_button.place(height=25, width=200, x=420, y=100) self.sensor_frame.place(height=135, width=220, x=10, y=270) self.oven_temperature_label.place(height=25, width=200, x=10, y=10) self.external_temperature_label.place(height=25, width=200, x=10, y=40) self.working_setpoint_label.place(height=25, width=200, x=10, y=70) self.working_output_label.place(height=25, width=200, x=10, y=100) self.log_frame.place(height=135, width=400, x=240, y=270) self.log_text.place(height=115, width=380, x=10, y=10) self.plot_frame.place(x=640, y=10, width=360, height=395) self.switch_plot_left_button.place(x=5, y=5, height=30, width=30) self.switch_plot_right_button.place(x=325, y=5, height=30, width=30) self.plot_label.place(x=35, y=5, height=25, width=295) self.pyrometer_plot_frame.place(x=5, y=40, width=350, height=350) self.oven_temperature_plot_frame.place(x=5, y=40, width=350, height=350) self.power_ouput_plot_frame.place(x=5, y=40, width=350, height=350) self.pyrometer_plot.place(x=0, y=0, width=350, height=350) self.oven_temperature_plot.place(x=0, y=00, width=350, height=350) self.power_ouput_plot.place(x=0, y=0, width=350, height=350) self.oven_temperature_plot_frame.lift() def start_label_updater(self): """Read values from instrument objects every second, display them, plot them and write in a logfile""" self.start_time = datetime.now() def update_labels(): while True: pyrometer_temperature = "---" oven_temperature = "---" working_output = "---" working_setpoint = "---" runtime = (datetime.now() - self.start_time).seconds / 60.0 if self.PLD is not None: oven_temperature = self.PLD.oven_temp.get() self.oven_temperature_plot.add_datapoint(runtime, oven_temperature) self.oven_temperature_label.configure(text="Oven temperature: %s °C" % oven_temperature) working_output = self.PLD.working_output.get() self.power_ouput_plot.add_datapoint(runtime, working_output) self.working_output_label.configure(text="Working output: %s %%" % working_output) working_setpoint = self.PLD.working_setpoint.get() self.working_setpoint_label.configure(text="Working setpoint: %s °C" % working_setpoint) if self.pyrometer is not None: pyrometer_temperature = self.pyrometer.temperature.get() self.pyrometer_plot.add_datapoint(runtime, pyrometer_temperature) self.external_temperature_label.configure(text="Sample temperature %s °C" % pyrometer_temperature) logstring = "Time: " + strftime("%X") \ + ("Oven temperature: %s °C" % oven_temperature).ljust(28, " ") \ + ("Power Output %s %%" % working_output).ljust(28, " ")\ + ("Working Setpoint: %s °C" % working_setpoint).ljust(28, " ")\ + ("Pyrometer temperature: %s °C" % pyrometer_temperature).ljust(28, " ") \ + "\n" printstring = "Time: " + strftime("%X") \ + ("Oven temperature: %s °C" % oven_temperature).ljust(28, " ") \ + ("Pyrometer temperature: %s °C" % pyrometer_temperature).ljust(28, " ")\ + "\n" self.log_text.insert(END, printstring) sleep(0.5) self.label_updater._target = update_labels self.label_updater.start() if self.PLD is not None and self.pyrometer is not None: self.start_pyrometer_pld_communication() if self.PLD is not None: self.mode_switcher_button.configure(state=NORMAL) self.power_output_setter_button.configure(state=NORMAL) self.PLD.switch_to_manual_mode() self.mode_label.configure(text="Manual operation mode") self.power_output_setter_button.configure(state=NORMAL) def connect_pld(self): """Connect to the PLD Eurotherm controller, start in manual mode""" if self.PLD_com_port_entry.get() != "": self.PLD_port = self.PLD_com_port_entry.get() if self.PLD_slave_address_entry.get() != "": self.PLD_address = int(self.PLD_slave_address_entry.get()) self.PLD = PLD(self.PLD_port, self.PLD_address) try: self.PLD.switch_to_manual_mode() except IOError: sleep(0.5) self.PLD.switch_to_manual_mode() self.PLD.start_oven_temperature_listener() self.PLD.start_working_output_listener() self.PLD.start_working_setpoint_listener() self.PLD.start_serial_io_handler() self.start_label_updater_button.configure(state=NORMAL) def connect_pyrometer(self): """Connect to the pyrometer""" if self.pyrometer_com_port_entry.get() != "": self.pyrometer_port = self.pyrometer_com_port_entry.get() self.pyrometer = Pyrometer(self.pyrometer_port) self.pyrometer.start_temperature_listener() self.start_label_updater_button.configure(state=NORMAL) self.external_sensor_mode_button.configure(state=NORMAL) def start_pyrometer_pld_communication(self): """Start supplying the PLD with the pyrometer temperature as external sensor temperature""" def talk(): while True: self.PLD.external_sensor_temperature.put(self.pyrometer.temperature) sleep(1) self.pyrometer_pld_communication._target = talk self.pyrometer_pld_communication.start() def set_target_setpoint(self): """Write the target setpoint in the entry widget to the instrument""" self.PLD.target_setpoint = float(self.setpoint_entry.get()) self.setpoint_label.configure(text="Setpoint %s °C" % self.PLD.target_setpoint) self.PLD.write_target_setpoint(self.PLD.target_setpoint) def set_target_output_power(self): """Write the target ouput power in the entry to the instrument""" self.PLD.power_output = float(self.power_output_entry.get()) self.power_output_label.configure(text="Power ouput %s%%" % self.PLD.power_output) self.PLD.write_manual_output_power(self.PLD.power_output) def switch_mode(self): """Switch the instrument between manual and automatic mode""" if not self.PLD.operation_mode: self.PLD.switch_to_manual_mode() self.PLD.operation_mode = 1 self.mode_label.configure(text="Manual operation mode") self.power_output_setter_button.configure(state=NORMAL) self.setpoint_setter_button.configure(state=DISABLED) elif self.PLD.operation_mode: self.PLD.switch_to_automatic_mode() self.PLD.operation_mode = 0 self.mode_label.configure(text="Automatic operation mode") self.setpoint_setter_button.configure(state=NORMAL) self.power_output_setter_button.configure(state=DISABLED) def enable_external_sensor_temperature(self): """Enabele using an external temperarture sensor for the PLD""" self.PLD.set_external_sensor_temperature_mode() self.hold_temperature_button.configure(state=NORMAL) def hold_temperature(self): """Switch the PLD to manual mode and hold the current power output""" self.setpoint_setter_button.configure(state=DISABLED) self.power_output_setter_button.configure(state=NORMAL) self.PLD.hold_current_temperature() def switch_plot_left(self): """Switch the displayed plot""" if self.active_plot: self.active_plot -= 1 self.show_plot() def switch_plot_right(self): """Switch the displayed plot""" if self.active_plot < 2: self.active_plot += 1 self.show_plot() def show_plot(self): """Switch the displayed plot""" if self.active_plot == 0: self.pyrometer_plot_frame.lift() self.plot_label.configure(text="Pyrometer temperature") if self.active_plot == 1: self.oven_temperature_plot_frame.lift() self.plot_label.configure(text="Oven temperature") if self.active_plot == 2: self.power_ouput_plot_frame.lift() self.plot_label.configure(text="Power Output")
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("EGUANA") self.style = ttk.Style() self.style.theme_use("alt") self.photoName = "eguana.gif" self.frame = Frame(self, relief=FLAT, borderwidth=10,bg='#FADC46') self.frame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) self.setupMenuBar() self.setupTopBar() def setupMenuBar(self): self.menubar = EguanaMenu(self.parent,self) self.parent.config(menu=self.menubar) def setupTopBar(self): self.openButton3D = Button(self.frame,text="Select Directory for 3D EMA",relief=RAISED,command=self.askDirectory) self.openButton3D.grid(row=0,column=0, sticky=N+S+E+W,padx=2,pady =2) self.openButton2D = Button(self.frame,text="Select Directory for 2D EMA",relief=RAISED,command=self.askDirectory); self.openButton2D.grid(row=2,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p1Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p1Button.grid(row=0,column=1, sticky=N+S+E+W,padx=2,pady =2) self.p2Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p2Button.grid(row=0,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p3Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p3Button.grid(row=1,column=0, sticky=N+S+E+W,padx=2,pady =2) self.p4Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p4Button.grid(row=1,column=2, sticky=N+S+E+W,padx=2,pady =2) self.p5Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p5Button.grid(row=2,column=0, sticky=N+S+E+W,padx=2,pady =2) self.p6Button = Button(self.frame,text="Placeholder",relief=RAISED) self.p6Button.grid(row=2,column=1, sticky=N+S+E+W,padx=2,pady =2) self.openButton3D.bind('<Motion>',self.cursorPosition) self.openButton2D.bind('<Motion>',self.cursorPosition) self.photo = PhotoImage(file="eguana.gif") self.photo = self.photo.subsample(2); self.photo_label = Label(self.frame,image=self.photo,borderwidth=0,highlightthickness=0) self.photo_label.configure(bg='#FADC46') self.photo_label.grid(row=1,column=1, sticky=N+S+E+W,padx=2,pady =2) self.photo_label.image = self.photo self.frame.columnconfigure(0, weight=1) self.frame.columnconfigure(1, weight=1) self.frame.columnconfigure(2, weight=1) self.frame.rowconfigure(0, weight=1) self.frame.rowconfigure(1, weight=1) self.frame.rowconfigure(2, weight=1) def askDirectory(self): dirStr = filedialog.askdirectory() if len(dirStr): self.openButton3D.destroy() self.openButton2D.destroy() self.p1Button.destroy() self.p2Button.destroy() self.p3Button.destroy() self.p4Button.destroy() self.p5Button.destroy() self.p6Button.destroy() self.menubar.entryconfigure('Filter', state = 'active') self.photo_label.destroy() dirStr = 'Input Path : '+dirStr self.frame.grid_forget() self.infoFrame = Frame(self.frame, relief=FLAT, bg='#FADC46') self.infoFrame.grid(row=0,column=0,columnspan=3, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel = Label(self.infoFrame, text="No project currently selected",relief=FLAT) self.directoryLabel.grid(row=0,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel.config(text=dirStr) self.outputDirButton = Button(self.infoFrame,text="No output directory selected. Click to select an output directory ",relief=RAISED,fg='red',command=self.askOutputDirectory) self.outputDirButton.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton = Button(self.infoFrame,text="No filter selected. Click to select a filter",relief=RAISED,fg='red',command=self.selectFilter) self.filterButton.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.trialLabel = Label(self.infoFrame,text="Trial Number",relief=FLAT,justify=RIGHT,anchor=E) self.trialLabel.grid(row=3,column=0, sticky=N+S+E+W,padx=2,pady =2) vcmd = (self.master.register(self.validate),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') self.trialEntry = Entry(self.infoFrame,validate = 'key', validatecommand = vcmd) self.trialEntry.grid(row=3,column=1, sticky=N+S+E+W,padx=2,pady =2) self.infoFrame.columnconfigure(0, weight=1) self.infoFrame.columnconfigure(1, weight=1) self.infoFrame.rowconfigure(0, weight=1) self.infoFrame.rowconfigure(1, weight=1) self.infoFrame.rowconfigure(2, weight=1) self.infoFrame.rowconfigure(3, weight=1) self.showPlotTools() def validate(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name): if len(value_if_allowed)==0 : return True if text in '0123456789.-+ ': try: float(value_if_allowed) return True except ValueError: return False else: return False def askOutputDirectory(self): dirStr = filedialog.askdirectory() if len(dirStr): dirStr = 'Output Path : '+dirStr self.outputDirButton.destroy() self.outputDirLabel = Label(self.infoFrame, relief=FLAT) self.outputDirLabel.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.outputDirLabel.config(text=dirStr) def showPlotTools(self): f2= Frame(self.frame, relief=FLAT,bg='#FADC46') f2.grid(row=1,column=0,rowspan=2,columnspan=3,sticky=N+S+E+W,padx=10,pady =10) b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1)) b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5) b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2)) b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5) b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3)) b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5) b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4)) b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5) b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5)) b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5) b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6)) b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5) f2.columnconfigure(0, weight=1) f2.columnconfigure(1, weight=1) f2.columnconfigure(2, weight=1) f2.rowconfigure(0, weight=1) f2.rowconfigure(1, weight=1) def plotButtonPressed(self,number): trialNum = self.trialEntry.get() try: trialNum = float(trialNum) if trialNum < 16 and trialNum > 0: self.plotFigure(number) return True else: messagebox.showerror( "Trial Number Error", "The trial number is out of range" ) return False except ValueError: messagebox.showerror( "Trial Number Error", "Error with the trial number" ) return False def plotFigure(self,number): m = CoilNumDialog(self.frame) if m.isSet(): print(m.getValues()) def selectFilter(self): self.top = FilterPopup(self); def speech3DButtonPressed(self): self.menubar.filterSelected(0) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : speech3D") else: self.filterLabel = Label(self.infoFrame, text="Filter : speech3D",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def speech2DButtonPressed(self): self.menubar.filterSelected(1) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : speech2D") else: self.filterLabel = Label(self.infoFrame, text="Filter : speech2D ",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def swallow3DButtonPressed(self): self.menubar.filterSelected(2) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : swallow3D") else: self.filterLabel = Label(self.infoFrame, text="Filter : swallow3D ",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def swallow2DButtonPressed(self): self.menubar.filterSelected(3) self.top.destroy() if hasattr(self, 'filterLabel'): self.filterLabel.config(text="Filter : swallow2D") else: self.filterLabel = Label(self.infoFrame, text="Filter : swallow2D ",relief=FLAT) self.filterLabel.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton.destroy() def changeImage(self): self.photo = PhotoImage(file=self.photoName) self.photo = self.photo.subsample(2); self.photo_label.image = self.photo self.photo_label.config(image=self.photo) def cursorPosition(self,event): if event.widget == self.openButton3D: if self.photoName == "eguana2.gif": self.photoName = "eguana.gif" self.changeImage() elif event.widget == self.openButton2D: if self.photoName == "eguana.gif": self.photoName = "eguana2.gif" self.changeImage()
class TimerFrame(Frame): # tkinter widgets timer_control_btn = current_time_lbl = copyright_lbl = remaining_time_frame = None section_title_lbl = elapsed_time_lbl = remaining_time_lbl = reset_timer_btn = None inverting_parts = [] ui_colors = [LIGHT, DARK] # timer logic _actual_section = 0 section_remaining = EXAM_SECTIONS[_actual_section][1] timer_id = None def __init__(self, master=None, cnf={}, **kw): super().__init__(master, cnf, **kw) self.COPYRIGHT_FONT = Font(master, family='Helvetica', size=28) self.LABELS_FONT = Font(master, family='Helvetica', size=50) self.SECTION_FONT = Font(master, family='Helvetica', size=76) self.TIME_FONT = Font(master, family='Helvetica', size=130, weight=BOLD) self.setup_ui() self.bind_keyboard() self._update_current_time() def setup_ui(self): """ Basic setup GUI labels and buttons. """ self.pack(fill=BOTH, expand=True, padx=10, pady=10) self.grid_columnconfigure(1, weight=1) self.grid_rowconfigure(1, weight=1) self.timer_control_btn = Button(self, command=self.start_timer, text='START!', font=self.LABELS_FONT) self.timer_control_btn.grid(row=2, column=1, sticky=S) self.reset_timer_btn = Button( self, command=self.reset_timer, text='VYNULOVAT!', font=self.COPYRIGHT_FONT ) self.reset_timer_btn.grid(row=2, column=2, sticky=S + E) self.current_time_lbl = Label(self, font=self.LABELS_FONT) self.current_time_lbl.grid(row=2, column=0, sticky=W + S) self.copyright_lbl = Label(self, text="Josef Kolář © 2016", font=self.COPYRIGHT_FONT) self.copyright_lbl.grid(column=2, row=0, sticky=N + E) self.section_title_lbl = Label(self, font=self.SECTION_FONT) self.section_title_lbl.grid(column=1, row=0, sticky=N) self.elapsed_time_lbl = Label(self, text='0:00', font=self.LABELS_FONT) self.elapsed_time_lbl.grid(column=0, row=0, sticky=N + W) self.remaining_time_frame = Frame(self) self.remaining_time_frame.grid(column=1, row=1) self.remaining_time_lbl = Label( self.remaining_time_frame, text=format_delta(EXAM_SECTIONS[0][1]), font=self.TIME_FONT ) self.remaining_time_lbl.pack() self.inverting_parts.extend(( self.current_time_lbl, self.copyright_lbl, self.section_title_lbl, self.remaining_time_lbl, self.timer_control_btn, self.elapsed_time_lbl, self.reset_timer_btn )) self.refresh_section() def _update_current_time(self): """ Update the timer of current time and set the timing for next second. """ self.current_time_lbl.configure(text=time.strftime('%H:%M:%S')) self.master.after(1000, self._update_current_time) def _invert_ui(self): """ Invert colors in the GUI including font colors and backgrounds. """ self.ui_colors.reverse() bg, fg = self.ui_colors self.master.configure(bg=bg) self.configure(bg=bg) for part in self.inverting_parts: part['background'] = bg part['foreground'] = fg def start_timer(self): """ Start the main timer and timer updating. """ self.timer_control_btn.configure(text='STOP!', command=self.stop_timer) self.timer_id = self.master.after(1000, self.update_timer) def update_timer(self): """ Update the timer time and check the next section. """ self.section_remaining -= timedelta(seconds=1) if self.section_remaining.total_seconds() == 0: self.actual_section += 1 self._invert_ui() elif self.section_remaining.total_seconds() < 5: self._invert_ui() self.remaining_time_lbl.configure(text=format_delta(self.section_remaining)) self.elapsed_time_lbl.configure( text=format_delta(EXAM_SECTIONS[self.actual_section][1] - self.section_remaining) ) if self.section_remaining.total_seconds() > 0: self.timer_id = self.master.after(1000, self.update_timer) def stop_timer(self): """ Stop the main timer. """ if self.timer_id: self.master.after_cancel(self.timer_id) self.timer_control_btn.configure(text='START!', command=self.start_timer) def reset_timer(self): """ Ask for resetting the main timer and may reset the main timer. :return: """ if askyesno('Jste si jisti?', 'Opravdu chcete zastavit a vynulovat čítání?', default=NO): self.stop_timer() self.actual_section = 0 @property def actual_section(self): """ Return actual section index. """ return self._actual_section @actual_section.setter def actual_section(self, new): """ Set the new section index and refresh section state. """ self._actual_section = new self.refresh_section() def refresh_section(self): """ Refresh labels and main timer state. """ section_title, section_length = EXAM_SECTIONS[self.actual_section] self.section_title_lbl.configure(text=section_title) self.section_remaining = copy(section_length) self.remaining_time_lbl.configure(text=format_delta(self.section_remaining)) self.elapsed_time_lbl.configure( text=format_delta(EXAM_SECTIONS[self.actual_section][1] - self.section_remaining) ) def bind_keyboard(self): """ Bind shortcuts to the keyboard. """ self.master.bind('<space>', lambda *args, **kwargs: self.timer_control_btn.invoke()) self.master.bind('<Delete>', lambda *args, **kwargs: self.reset_timer_btn.invoke())
class MultipleRunGUI: """GUI for batch and SxS modes for displaying the stats.""" def __init__(self, *, multiple_runner_class, input_spec, left_name, right_name): """Sets up windows and the instance of RunMultipleTimes that will do the actual work.""" #: The input_spec is an iterable of #: :py:class:`farg.core.read_input_spec.SpecificationForOneRun`. self.input_spec = input_spec #: Class responsible for the actual running multiple times. self.multiple_runner_class = multiple_runner_class #: Main window self.mw = mw = Tk() #: Statistics thus far, grouped by input. self.stats = AllStats(left_name=left_name, right_name=right_name) #: Are we in the process of quitting? self.quitting = False self.status_label = Label( mw, text='Not Started', font=('Times', 20), foreground='#000000') self.status_label_text = self.status_label.cget('text') self.status_label.pack(side=TOP, expand=True, fill=X) #: Has a run started? Used to ensure single run. self.run_started = False details_frame = Frame(mw) details_frame.pack(side=TOP) #: listbox on left listing inputs. frame = Frame(details_frame) scrollbar = Scrollbar(frame, orient=VERTICAL) listbox = Listbox( frame, yscrollcommand=scrollbar.set, height=25, width=70, selectmode=SINGLE) scrollbar.config(command=listbox.yview) scrollbar.pack(side=RIGHT, fill=Y) listbox.pack(side=LEFT, fill=BOTH, expand=1) listbox.bind('<ButtonRelease-1>', self.SelectForDisplay, '+') frame.pack(side=LEFT) self.listbox = listbox #: Canvas on right for details self.canvas = Canvas( details_frame, width=kCanvasWidth, height=kCanvasHeight, background='#FFFFFF') self.canvas.pack(side=LEFT) #: which input are we displaying the details of? self.display_details_for = None #: Thread used for running self.thread = None self.mw.bind('<KeyPress-q>', lambda e: self.Quit()) self.mw.bind('<KeyPress-r>', lambda e: self.KickOffRun()) self.Refresher() self.mw.after(1000, self.KickOffRun) def SelectForDisplay(self, _event): """Event-handler called when an input was selected for detailed display.""" selected = self.listbox.curselection() if not selected: selected = ['0'] self.display_details_for = self.listbox.get(selected[0]) def Quit(self): """Called when the user has indicated that the application should Quit. Waits for any ongoing run to finish, and then destroys windows. """ self.quitting = True if self.thread: self.thread.join() self.mw.quit() def Refresher(self): """Repeatedly refreshes the display.""" self.UpdateDisplay() self.mw.after(100, self.Refresher) def KickOffRun(self): """Start run if it has not already started.""" if self.run_started: return self.run_started = True self.thread = self.multiple_runner_class( input_spec=self.input_spec, gui=self) self.thread.start() def UpdateDisplay(self): """Displays the Stats.""" current_selection = self.listbox.curselection() self.listbox.delete(0, END) self.canvas.delete('all') inputs = self.stats.input_order self.status_label.configure(text=self.status_label_text) if not inputs: return for idx, input_string in enumerate(inputs): if input_string == self.display_details_for: self.listbox.insert(END, '%s <---' % input_string) else: self.listbox.insert(END, input_string) codelet_count_comparison, success_comparison = self.stats.IsRightBetter( input_string) color = kDisplayColorDict[(codelet_count_comparison, success_comparison)] self.listbox.itemconfigure(idx, background=color) if self.display_details_for: self.DisplayDetails() if current_selection: self.listbox.selection_set(current_selection[0]) def DisplayDetails(self): """Show detailed statistics of one input. Details are shown for whatever input is present in self.display_details_for. """ self.canvas.create_text(2, 2, text=self.display_details_for, anchor=NW) # Display left side self.DisplayOneSideStats( y=kBaseYOffset, # Confused by * is pylint: disable=E1123,C6010 label=self.stats.left_name, stats=self.stats.GetLeftStatsFor(self.display_details_for)) self.DisplayOneSideStats( y=kExptYOffset, # Confused by * is pylint: disable=E1123,C6010 label=self.stats.right_name, stats=self.stats.GetRightStatsFor(self.display_details_for)) self.DisplayInferenceStats( self.stats, self.display_details_for, y=kInferenceStatsYOffset) def DisplayOneSideStats(self, *, y, label, stats): """Display stats for one of the to sides for one input. y: Y-offset where to display. label: Name of the side. Will probably be one of "previous", "current", "base", or "expt". stats: Statistics for this run. This is a :py:class:`farg.core.run_stats.RunStats` object. """ self.canvas.create_text(10, y, anchor=NW, text=label) self.CreatePieChart(kPieChartXOffset, y + 20, stats) self.CreateHistogram(kHistogramXOffset, y + 20, stats) self.DisplayBasicStats(kBasicStatsXOffset, y + 20, stats) def CreatePieChart(self, x_offset, y_offset, stats): """Create PieChart. Args: x_offset: X-offset for Pie. y_offset: Y-offset for Pie. stats: Stats to display. Instance of :py:class:`~farg.core.run_stats.RunStats`. """ stats_per_state = stats.stats_per_state state_to_counts = dict((x, len(y.codelet_counts)) for x, y in stats_per_state.items()) total_runs = sum(state_to_counts.values()) if total_runs == 0: return start = 0 for state, count in state_to_counts.items(): extent = 359.9 * count / total_runs color = StateToColor(state) self.canvas.create_arc( x_offset, y_offset, x_offset + kPieChartDiameter, y_offset + kPieChartDiameter, start=start, extent=extent, fill=color) start += extent self.canvas.create_text( x_offset + kPieChartDiameter / 2, y_offset + kPieChartDiameter + 5, anchor=N, text='%d Runs' % total_runs) def CreateHistogram(self, x_offset, y_offset, stats): """Create histogram of codelet run times. Args: x_offset: X-offset for Pie. y_offset: Y-offset for Pie. stats: Stats to display. Instance of :py:class:`~farg.core.run_stats.RunStats`. """ all_runs = [] for state, stats_for_state in stats.stats_per_state.items(): all_runs.extend((state, x_offset) for x_offset in stats_for_state.codelet_counts) all_runs = sorted( (x_offset for x_offset in all_runs if x_offset[1] > 0), key=lambda x_offset: x_offset[1]) count = len(all_runs) if count == 0: return delta_x = kHistogramWidth / count max_codelet_count = max(x_offset[1] for x_offset in all_runs) for idx, run in enumerate(all_runs): color = StateToColor(run[0]) y_end = y_offset + kHistogramHeight - kHistogramHeight * run[ 1] / max_codelet_count this_x = x_offset + delta_x * idx self.canvas.create_line( this_x, y_end, this_x, y_offset + kHistogramHeight, fill=color) self.canvas.create_text( x_offset + kHistogramWidth / 2, y_offset + kHistogramHeight + 10, anchor=N, text='Max codelets: %d' % max_codelet_count) def DisplayBasicStats(self, x_offset, y_offset, stats): """Display basic stats (mean run time, success rate, etc.) for one side. Args: x_offset: X-offset for Pie. y_offset: Y-offset for Pie. stats: Stats to display. Instance of :py:class:`~farg.core.run_stats.RunStats`. """ successful_completion_stats = stats.stats_per_state[b'SuccessfulCompletion'] total_runs = sum( len(x_offset.codelet_counts) for x_offset in stats.stats_per_state.values()) if total_runs == 0: return percentage = '%3.2f%%' % ( 100 * len(successful_completion_stats.codelet_counts) / total_runs) self.canvas.create_text( x_offset, y_offset, anchor=NW, text='Success: %s' % percentage) codelet_counts = successful_completion_stats.codelet_counts if codelet_counts: mean_codelet_count = Mean(codelet_counts) median_codelet_count = Median(codelet_counts) self.canvas.create_text( x_offset, y_offset + 15, anchor=NW, text='Mean: %3.2f' % mean_codelet_count) self.canvas.create_text( x_offset, y_offset + 30, anchor=NW, text='Median: %3.2f' % median_codelet_count) def DisplayInferenceStats(self, stats, for_input, y): """Display inference stats: Is right hand side better than left? Args: stats: Instance of :py:class:`~farg.core.run_stats.AllStats`. for_input: What input string are we comparing the two sides? y: Y-offset of top of this display. """ codelet_stats, success_stats = stats.GetComparitiveStats(for_input) if not codelet_stats or not success_stats: return self.canvas.create_text( 10, y, anchor=NW, text='means: (%3.2f, %3.2f), variance: (%3.2f, %3.2f)' % (codelet_stats['left_mean'], codelet_stats['right_mean'], codelet_stats['left_variance'], codelet_stats['right_variance'])) self.canvas.create_text( 10, y + 20, anchor=NW, text='Counts: (%d, %d), k=%d, t=%3.2f, %s' % (codelet_stats['n1'], codelet_stats['n2'], codelet_stats['df'], codelet_stats['t'], codelet_stats['descriptor'])) self.canvas.create_text( 10, y + 40, anchor=NW, text='means: (%3.2f, %3.2f), variance: (%3.2f, %3.2f)' % (success_stats['left_mean'], success_stats['right_mean'], success_stats['left_variance'], success_stats['right_variance'])) self.canvas.create_text( 10, y + 60, anchor=NW, text='Counts: (%d, %d), k=%d, t=%3.2f, %s' % (success_stats['n1'], success_stats['n2'], success_stats['df'], success_stats['t'], success_stats['descriptor']))
class App(object): def __init__(self): #настройка окружения self.pathtoapp = path2program.abspath(".") self.lst = [x for x in listdir(".") if ".prg" in x] #получаем список файлов с расширением prg if len(self.lst)==0: print("No prg file found in directory") input() _exit(0) self.currentfileindex = 0 #устанавливаем индекс текущего файла #настройка графики self.window = Tk() self.window.title("PRG Viewer by Novicov: "+self.pathtoapp) w = 850 h = 500 self.window.minsize(width=w-100,height=h-100) self.window.maxsize(width=w,height=h) #иконка _lst = sys_argv[0].split('\\') self.window.iconbitmap('\\'.join(_lst[:-1])+'\\PRGViewer-logo.ico') #ПАНЕЛИ # self.leftframe = Frame(self.window, bg="blue", width=int(w*0.667),height=h) self.leftframe = Frame(self.window, bg="grey", width=int(w*0.667),height=h) # self.bottomleftframe = Frame(self.leftframe, bg="red", width=w//4, height=int(h*0.2)) self.bottomleftframe = Frame(self.leftframe, bg="grey", width=w//4, height=int(h*0.2)) # self.rightframe = Frame(self.window, bg="yellow",width=int(w*0.333),height=h) self.rightframe = Frame(self.window, bg="dark grey",width=int(w*0.333),height=h) #canvas self.set_canvas( self.leftframe, bg="dark green", width=int(w*0.667),height=int(h*0.8)) # self.set_canvas( self.leftframe, bg="light green", width=100,height=100) #кнопки self.nextButton = Button(self.bottomleftframe,text="Next",width=10) self.prevButton = Button(self.bottomleftframe,text="Prev",width=10) #Список фильтров self.Filter = PRGListBox(self.rightframe,width=w-500) #Выбор файла платы self.infoText = StringVar() self.infoText.set("Current file: "+self.lst[self.currentfileindex]) self.info = Label(self.rightframe,text=self.infoText.get()) self.listFilesText = StringVar() self.listFilesText.set("\n".join(["Files: "]+self.lst)) self.listfiles = Label(self.rightframe,text=self.listFilesText.get(),anchor="w",justify=LEFT) self.helpText = Label(self.rightframe, text="Use Next/Prev (Pg Down/Up) buttons for change file\n"+ "Use Up,Down,Right,Left buttons for move field\n"+ "Select row in ListBox for change vision mode\n"+ "Use +/- (p/m) buttons for scaling of field",anchor="n",justify=LEFT) def set_path_and_current(self, filename): ''' эта функция обрабатывает полный путь до файла ''' try: _lst = filename.split('\\') self.path = '\\'.join(_lst[:-2]) chdir('\\'.join(_lst[:-1])) print(listdir(".")) self.lst = [x for x in listdir(".") if ".prg" in x] self.currentfileindex = self.lst.index(_lst[-1]) self.infoText.set("Current file: "+self.lst[self.currentfileindex]) self.info.configure(text=self.infoText.get()) self.listFilesText.set("\n".join(self.lst)) self.listfiles.configure(text=self.listFilesText.get()) self.canvas.configure(self.lst[self.currentfileindex]) self.canvas.setdefault(reper=True) #рисуем self.canvas.paint() #здесь мы создаем группу gr = list() for item in self.canvas.field: print(item[2][2]) if not (item[2][2] in gr):#выделяем уникальные данные gr.append(item[2][2]) self.Filter.lst.delete(2,END) for item in gr: self.Filter.lst.insert(END,item) except IOError: self.infoText.set("Error") self.info.configure(text=self.infoText.get()) def set_canvas(self,master=None,height=500,width=500,bg="grey" ): if master==None: master=self.window self.canvas = prgCanvas(master,height=height,width=width,bg=bg) def nextprev(self,direction): self.currentfileindex+=1 if abs(direction)==direction else -1 if self.currentfileindex<0: self.currentfileindex = len(self.lst)-1 elif self.currentfileindex>len(self.lst)-1: self.currentfileindex = 0 self.canvas.setdefault(reper=True) self.infoText.set("Current file: "+self.lst[self.currentfileindex]) self.info.configure(text=self.infoText.get()) self.canvas.configure(self.lst[self.currentfileindex]) #рисуем self.canvas.paint() #здесь мы создаем группу gr = list() for item in self.canvas.field: print(item[2][2]) if not (item[2][2] in gr):#выделяем уникальные данные gr.append(item[2][2]) self.Filter.lst.delete(2,END) for item in gr: self.Filter.lst.insert(END,item) def _changemashtab(self,event,dm): self.canvas.mashtab*=dm self.canvas.genfield() def filter_selection(self): name = self.Filter.lst.get(self.Filter.lst.curselection()) if name == "Hide All": print("Hide All") self.canvas.flagDescription = False self.canvas.filter = None self.canvas.genfield() elif name =="Show All": print("Show All") self.canvas.flagDescription = True self.canvas.filter = None self.canvas.genfield() else: print("Other filter"+name) self.canvas.flagDescription = True #устанавливаем фильтр self.canvas.configure(filter=lambda x: x==name) #перерисовываем self.canvas.paint() def configure(self): self.window.bind("<Key-Right>",lambda event:self.canvas.move(10,0)) self.window.bind("<Key-Left>",lambda event:self.canvas.move(-10,0)) self.window.bind("<Key-Down>",lambda event:self.canvas.move(0,10)) self.window.bind("<Key-Up>",lambda event:self.canvas.move(0,-10)) self.window.bind("<Key-plus>",lambda event:self._changemashtab(event,1.1)) self.window.bind("p",lambda event:self._changemashtab(event,1.1)) self.window.bind("<Key-minus>",lambda event:self._changemashtab(event,0.9)) self.window.bind("m",lambda event:self._changemashtab(event,0.9)) self.Filter.lst.bind("<<ListboxSelect>>", lambda event: self.filter_selection()) self.Filter.bind("<Leave>",lambda event: self.window.focus_force()) self.nextButton.configure(command=lambda:self.nextprev(1)) self.prevButton.configure(command=lambda:self.nextprev(-1)) self.window.bind("<Key-Prior>",lambda event:self.nextprev(-1)) #Page Up self.window.bind("<Key-Next>",lambda event:self.nextprev(1)) #Page Down def startloop(self): self.leftframe.pack (side=LEFT,expand="y",fill="both") # self.leftframe.pack () print("leftframe") self.canvas.pack (expand="y",fill="both") self.canvas.canvas.pack () self.canvas.configure(file=self.lst[self.currentfileindex]) self.canvas.paint() self.bottomleftframe.pack() self.nextButton.pack (side=RIGHT) self.prevButton.pack (side=LEFT) self.rightframe.pack(side=RIGHT,expand="y",fill="y") # self.rightframe.pack() print("rightframe") self.info.pack (side=TOP,fill=X,expand=Y) self.listfiles.pack (side=TOP,fill=BOTH,expand=Y) self.Filter.pack (side=TOP, fill=BOTH, expand=Y) self.helpText.pack (side=BOTTOM) self.window.mainloop()
class MainWin(Tk): def __init__(self, client): Tk.__init__(self) self.client = client self.programPanel = ProgramPanel(client) self.programPanel.grid(row = 0, column = 0, sticky = NSEW) self.frame = Frame(self) self.frame.grid(row = 0, column = 0, sticky = NSEW) nextRow = Counter() # Create the menu. menu = Frame(self.frame) addButton = Menubutton(menu, text = 'Add') addButton.pack() menu.grid(row = nextRow(), column = 0, sticky = W) # Create the program panel. self.program = ProgramWidget(self.frame, client) self.program.grid(row = nextRow(), column = 0, columnspan = 2, sticky = W) label = Label(self.frame, text = 'AWB') label.grid(row = nextRow(), column = 0) self.recordMode = Button(self.frame, text = 'P', command = self.toggleRecord) modeRow = nextRow() self.recordMode.grid(row = modeRow, column = 0, sticky = W) self.status = Label(self.frame, text = 'Idle') self.status.grid(row = modeRow, column = 1) self.channels = [] self.channelFrame = Frame(self.frame) self.channelFrame.grid(row = nextRow(), columnspan = 2) self.bind('q', self.terminate) self.bind('f', self.foo) self.bind('r', self.toggleRecord) self.bind('k', self.toggleSticky) self.bind('.', self.nextSection) self.bind(',', self.prevSection) self.bind('<space>', self.togglePause) self.bind('K', self.clearAllState) self.protocol('WM_DELETE_WINDOW', self.destroy) self.bind('<F1>', lambda evt: self.frame.tkraise()) self.bind('<F2>', lambda evt: self.programPanel.tkraise()) for i in range(0, 8): # Bind number key. self.bind(str(i), lambda evt, channel = i: self.toggleChannel(channel) ) # Create channel channel = Channel(self.channelFrame, i) self.channels.append(channel) channel.pack(side = LEFT) client.addChannelSubscriber( i, lambda ch, status, channel = channel: channel.changeStatus(status) ) def foo(self, event): print('got foo') def terminate(self, event): self.destroy() def toggleRecord(self, event): self.client.recordEnabled = not self.client.recordEnabled self.recordMode.configure(text = self.client.recordEnabled and 'R' or 'P' ) def togglePause(self, event): self.client.togglePause() if self.client.paused: self.status.configure(text = 'Paused') else: self.status.configure(text = 'Playing') def clearAllState(self, event): self.client.clearAllState() self.status.configure(text = 'Idle') for channel in self.channels: channel.changeStatus(0) def toggleChannel(self, channel): # using "channel" as program self.client.activate(channel) if self.client.recording.get(channel): self.client.endRecord(channel) elif self.client.recordEnabled: self.client.startRecord(channel) self.status.configure(text = 'Recording on %s' % channel) def __getActiveChannel(self): # Move this to awb_client for i, ch in enumerate(self.channels): if ch.active: return i def toggleSticky(self, event): channel = self.__getActiveChannel() self.client.toggleChannelSticky(channel) def nextSection(self, event): self.client.nextOrNewSection() def prevSection(self, event): self.client.prevSection()
class Tabblet(): def __init__(self): self.tkvar = tkinter.Tk() with open("options.json") as j: joptions = json.load(j) self.tkvar.wm_title("Tabblet") self.tkvar.iconbitmap('resources\\tabbleto.ico') self.screenwidth = self.tkvar.winfo_screenwidth() self.screenheight = self.tkvar.winfo_screenheight() self.windowwidth = int(joptions['width']) self.windowheight = int(joptions['height']) self.windowx = (self.screenwidth-self.windowwidth) / 2 self.windowy = ((self.screenheight-self.windowheight) / 2) - 27 self.geometrystring = '%dx%d+%d+%d' % (self.windowwidth, self.windowheight, self.windowx, self.windowy) self.tkvar.geometry(self.geometrystring) self.image_resetwindow = PhotoImage(file="resources\\resetwindow.gif") self.button_resetwindow = Button(self.tkvar, command= lambda: self.tkvar.geometry(self.geometrystring)) self.button_resetwindow.configure(relief="flat", image=self.image_resetwindow) self.button_resetwindow.pack(expand=False,anchor="ne") self.tkvar.bind('<Configure>', lambda event: self.button_resetwindow.place(x=self.tkvar.winfo_width()-20, y=0)) self.tkvar.bind('<B1-Motion>', self.dragmotion) self.tkvar.bind('<ButtonPress-1>', lambda event: self.mousestate(True)) self.tkvar.bind('<ButtonRelease-1>', lambda event: self.mousestate(False)) self.velocityx = 0 self.velocityy = 0 self.mousepositionsx = [2] self.mousepositionsy = [2] self.ismousepressed = False self.labelvelocityind = Label(self.tkvar, text='•') velocitythread = threading.Thread(target=self.velocitymanager) velocitythread.daemon = True velocitythread.start() self.tkvar.mainloop() def dragmotion(self, event): #print(event.x, event.y) self.mousepositionsx.append(event.x) self.mousepositionsy.append(event.y) self.mousepositionsx = self.mousepositionsx[-20:] self.mousepositionsy = self.mousepositionsy[-20:] print(event.x, event.y) def mousestate(self, state): self.ismousepressed = state def velocitymanager(self): while True: if not self.ismousepressed: try: self.velocityx = (sum(self.mousepositionsx)/len(self.mousepositionsx)) - self.mousepositionsx[-1] self.velocityy = (sum(self.mousepositionsy)/len(self.mousepositionsy)) - self.mousepositionsy[-1] except: self.velocityx = 0 self.velocityy = 0 self.velocityx = int(self.velocityx * 0.9) self.velocityy = int(self.velocityy * 0.9) #print(self.velocityx, self.velocityy, self.ismousepressed) if abs(self.velocityx) < 2: self.velocityx = 0 if abs(self.velocityy) < 2: self.velocityy = 0 time.sleep(0.0165) #60 fps baby self.labelvelocityind.configure(text="•") self.labelvelocityind.place(x=512+self.velocityx, y=288+self.velocityy) self.mousepositionsx = self.mousepositionsx[1:] self.mousepositionsy = self.mousepositionsy[1:]
class BackupGuiTk(Frame): """ The main widget of the robobackup GUI made with tkinter. """ def __init__(self, method=None, master=None): self.method = method self.picframe = Frame.__init__(self, master) self.master.title("Robobackup") self.image = PhotoImage() self.image["file"] = os.path.join(os.path.dirname(\ os.path.relpath(__file__)), "resources", "ASK.png") self.piclabel = Label(self.picframe, image=self.image) self.piclabel.grid(row=0, column=0, columnspan=4, rowspan=6) self.clocklabel = Label(self.picframe, text=_("Elapsed time:")) self.clocklabel.grid(row=0, column=4, sticky="NSEW") self.clock = Label(self.picframe, text="") self.clock.grid(row=1, column=4, sticky="NSEW") self.start = Button(self.picframe, text=_("Start Backup"), command=self.__clk) self.start.grid(row=3, column=4, sticky="NSEW") self.errorlabel = Label(self.picframe) self.errorlabel.grid(row=4, column=4, sticky="NSEW") self.close = Button(self.picframe, text=_("Close"), command=self.__cls) self.close.grid(row=5, column=4, sticky="NSEW") self.loglabel = Label(self.picframe, text=_("Log:"), justify="left") self.loglabel.grid(row=6, column=0, columnspan=5, sticky="NSEW") self.text = Text(self.picframe) self.text.grid(row=7, column=0, rowspan=6, columnspan=5, sticky="NSEW") self.timeout = False self.starttime = -1 def __clk(self): """ This method starts the backup. It is a slot which is connected to the signal "click" of the button "btnStart". """ self.start.config(state="disabled") self.close.config(state="disabled") self.clock_tick() try: self.method() except: if __debug__: logbook.exception("") self.set_backup_failure() messagebox.showinfo(_("Critical"), _("Robobackup " \ "failed. Contact your admin.")) finally: self.timeout = True self.close.config(state="normal") def __cls(self): """ This method is used to close the GUI. """ self.master.destroy() def clock_tick(self): """ This is used to count the seconds the backup method runs. """ if not self.timeout: self.starttime = int(time.time() * 1000) milliseconds = int(time.time() * 1000) - self.starttime seconds, milliseconds = divmod(milliseconds, 1000) minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) digitalclock = "{hh:02d}:{mm:02d}:{ss:02d}".format(hh=hours, \ mm=minutes, ss=seconds) self.clock.configure(text=digitalclock) if not self.timeout: self.master.after(1000, self.clock_tick) def update(self): """ This method will be called, if logs are changing. """ color = logbook.get_severity() self.set_log(logbook.get_string()) if color is Severity.green: self.set_backup_success() elif color is Severity.orange: self.set_backup_check() elif color is Severity.red: self.set_backup_failure() else: raise RuntimeError(_("Color does not match an action.")) def set_backup_success(self): """ Set everything green. """ self.errorlabel.configure(text=_("Success")) self.errorlabel["bg"] = "green" self.image["file"] = os.path.join(os.path.dirname(\ os.path.relpath(__file__)), "resources", "SUCCESS.png") def set_backup_check(self): """ Set everything orange. """ self.errorlabel.configure(text=_("Check backup")) self.errorlabel["bg"] = "orange" self.image["file"] = os.path.join(os.path.dirname(\ os.path.relpath(__file__)), "resources", "CHECK.png") def set_backup_failure(self): """ Set everything red. """ self.errorlabel.configure(text=_("Failure")) self.errorlabel["bg"] = "red" self.image["file"] = os.path.join(os.path.dirname(\ os.path.relpath(__file__)), "resources", "FAIL.png") def set_log(self, log): """ Write text to the GUI. """ self.text.delete("1.0", END) self.text.insert(END, log)
class dodgygame: def __init__(self): tkvar = Tk() tkvar.resizable(0,0) tkvar.wm_title('Dodgy') tkvar.iconbitmap('Excl.ico') arenasize = 40 self.xpos = int((arenasize-1)/2) self.ypos = int((arenasize-1)/2) self.data = ['#'*arenasize, '#'*arenasize] for x in range(arenasize-2): self.data[1:1] = ['#' + '.'*(arenasize-2) + '#'] self.labelframe = Frame(tkvar) self.labelframe.grid(row=1, column=0, columnspan=100) #Allows me to center the gui units self.datalabel = Label(tkvar, text='\n'.join(self.data), font=('Terminal', 10)) self.datalabel.grid(row=0, column=0, columnspan=100) self.stepslabel = Label(self.labelframe, text='0', font=('Consolas', 10)) self.stepslabel.grid(row=0, column=0) self.collectlabel = Label(self.labelframe, text='0', font=('Consolas', 10), bg="#ccc") self.collectlabel.grid(row=0, column=1) self.bomblabel = Label(self.labelframe, text='0', font=('Consolas', 10)) self.bomblabel.grid(row=0, column=2) self.phantlabel = Label(self.labelframe, text='0',font=('Consolas', 10), bg="#ccc") self.phantlabel.grid(row=0, column=3) self.poslabel = Label(self.labelframe, text=str(self.xpos) + " " + str(self.ypos), font=('Consolas', 10)) self.poslabel.grid(row=0, column=4) self.helplabel = Label(tkvar, text="Press H for help ->", font=('Consolas', 8)) self.helplabel.grid(row=2, column=0, columnspan=100) self.consolelabel = Label(tkvar, text="Welcome", font=("Terminal", 8), width=arenasize, height=4) self.consolelabeldata = [] self.consolelabel.configure(anchor="nw", justify="left") self.consolelabel.grid(row=3, column=0) tkvar.bind('w', lambda data=self.data: mfresh(ymove=-1)) tkvar.bind('<Up>', lambda data=self.data: mfresh(ymove=-1)) tkvar.bind('s', lambda data=self.data: mfresh(ymove=1)) tkvar.bind('<Down>', lambda data=self.data: mfresh(ymove=1)) tkvar.bind('a', lambda data=self.data: mfresh(xmove=-1)) tkvar.bind('<Left>', lambda data=self.data: mfresh(xmove=-1)) tkvar.bind('d', lambda data=self.data: mfresh(xmove=1)) tkvar.bind('<Right>', lambda data=self.data: mfresh(xmove=1)) #tkvar.bind('c', lambda data=self.data: spawncandy()) tkvar.bind('j', lambda data=self.data: spawnbomb()) tkvar.bind('z', lambda data=self.data: spawnbomb()) tkvar.bind('k', lambda data=self.data: spawnphantom()) tkvar.bind('x', lambda data=self.data: spawnphantom()) tkvar.bind('r', lambda data=self.data: restart()) tkvar.bind('h', lambda data=self.data: helpreel()) tkvar.bind('<Control-w>', quit) self.candylist = [] self.enemylist = [] self.bomblist = [] self.phantomlist = [] self.goldcandylist = [] self.entlist = [] self.symbols = {'char':'H', 'wall':'#', 'floor':' '} self.stepstaken = 0 self.isdeath = False self.candyspawnrate = 4 self.collections = 0 self.enemyspawnrate = 50 self.enemyspawnmindist = 9 self.enemydocollide = False self.bombs = 0 self.bombcost = 4 self.phantomcost = 60 self.goldcandyflashrate = 8 self.goldcandyspawnrate = 40 self.goldcandyspawnrand = 4 self.helplabelindex = -1 self.helplabeltexts = [ "<WASD>=Movement <J>=Bomb <K>=Phantom <R>=Restart ->", "<UDLR>=Movement <Z>=Bomb <X>=Phantom <R>=Restart ->", "<LMB>=Movement <RMB>=Bomb <MMB>=Phantom/Restart ->", self.symbols['char'] + " = You ->", enemy.symbol + " = Exclamator ->", candy.symbol + " = Candy ->", bomb.symbol + " = Bomb ->", "Avoid the Exclamators ->", "Collect candy to earn bombs ->", "Drop bombs to snare Exclamators ->", "Deploy phantoms to distract Exclamators ->", "Phantoms have a minimum cost of " + str(self.phantomcost) + " ->", "But deploying phantom will consume all candy ->", "More candy consumed = longer phantom lifespan ->", "Enjoy •"] def mfresh(xmove=0, ymove=0): if not self.isdeath: #print(self.xpos, self.ypos, "==> ", end="") hasmoved = False if xmove != 0: if (self.xpos > 1 or xmove > 0) and (self.xpos < (arenasize -2) or xmove < 0): self.xpos += xmove if self.phantomlist != []: ph = self.phantomlist[0] ph.x -= xmove if ph.x < 1: ph.x = 1 if ph.x > (arenasize-2): ph.x = arenasize-2 hasmoved = True if ymove != 0: if (self.ypos > 1 or ymove > 0) and (self.ypos < (arenasize -2) or ymove < 0): self.ypos += ymove if self.phantomlist != []: ph = self.phantomlist[0] ph.y -= ymove if ph.y < 1: ph.y = 1 if ph.y > (arenasize-2): ph.y = arenasize-2 hasmoved = True if hasmoved: if self.phantomlist != []: ph = self.phantomlist[0] ph.lifespan -= 1 if ph.lifespan <= 0: self.phantomlist.remove(ph) self.entlist.remove(ph) del ph #print(self.xpos, self.ypos, '|', self.stepstaken) for candies in self.candylist: if candies.x == self.xpos and candies.y == self.ypos: #print('Collection') collect(1) self.candylist.remove(candies) self.entlist.remove(candies) del candies for goldcandies in self.goldcandylist: if goldcandies.x == self.xpos and goldcandies.y == self.ypos: tempvar = '[ ' + goldcandy.symbol + ' ] Got gold' print(tempvar) printr(tempvar) collect(5) self.goldcandylist.remove(goldcandies) self.entlist.remove(goldcandies) for enemies in self.enemylist: if enemies.x == self.xpos and enemies.y == self.ypos: tempvar = '[ ' + self.symbols['char'] + ' ] Death' print(tempvar) printr(tempvar) self.isdeath = True self.datalabel.configure(fg='Red') if not self.isdeath: if hasmoved: self.stepstaken += 1 if self.stepstaken % self.candyspawnrate == 0: spawncandy() goldchance = random.randint(self.stepstaken-self.goldcandyspawnrand, self.stepstaken+self.goldcandyspawnrand) #print(goldchance) if goldchance % self.goldcandyspawnrate == 0: spawngoldcandy() if self.stepstaken % self.enemyspawnrate == 0: spawnenemy() for x in range(self.stepstaken // 200): spawnenemy() for en in self.enemylist: oldx = en.x oldy = en.y if self.phantomlist == []: en.approach(self.xpos, self.ypos) else: ph = self.phantomlist[0] en.approach(ph.x, ph.y) if self.enemydocollide: for otheren in self.enemylist: if en != otheren: if en.x == otheren.x and en.y == otheren.y: tempvar = '[ '+enemy.symbol+' ] Enemy collision at '+str(en.x)+' '+str(en.y) print(tempvar) printr(tempvar) en.x = oldx en.y = oldy #print(dist(en.x, en.y, self.xpos, self.ypos)) if en.x < 1: en.x = 1 if en.x > (arenasize-2): en.x = arenasize-2 if en.y < 1: en.y = 1 if en.y > (arenasize-2): en.y = arenasize-2 mfresh() for goldcandies in self.goldcandylist: goldcandies.tick(self.goldcandyflashrate) if goldcandies.lifespan <= 0: self.goldcandylist.remove(goldcandies) self.entlist.remove(goldcandies) del goldcandies for bombs in self.bomblist: for enemies in self.enemylist: if enemies.x == bombs.x and enemies.y == bombs.y: self.bomblist.remove(bombs) self.enemylist.remove(enemies) self.entlist.remove(bombs) self.entlist.remove(enemies) tempvar = '[ ' + bomb.symbol + ' ] Bang' print(tempvar) printr(tempvar) mfresh() self.data = [self.symbols['wall']*arenasize, self.symbols['wall']*arenasize] for x in range(arenasize-2): self.data[1:1] = [self.symbols['wall'] + self.symbols['floor']*(arenasize-2) + self.symbols['wall']] for ycoord in range(len(self.data)): yl = self.data[ycoord] if ycoord == self.ypos and not self.isdeath: #print(ycoord) yl = yl[:self.xpos] + self.symbols['char'] + yl[self.xpos+1:] #print(yl) self.entlist.sort(key=lambda p: p.x) for entities in self.entlist: if entities.y == ycoord: yl = yl[:entities.x] + entities.symbol + yl[entities.x+1:] self.data[ycoord] = yl self.datalabel.configure(text='\n'.join(self.data)) self.stepslabel.configure(text="%04d"%(self.stepstaken) + " steps") self.collectlabel.configure(text="%03d"%(self.collections) + " candy") self.bomblabel.configure(text="%02d"%(self.bombs) + " bombs") self.poslabel.configure(text="%02d"%(self.xpos) + " " + "%02d"%(self.ypos)) if self.collections >= self.phantomcost: self.phantlabel.configure(text='1 phantom') else: self.phantlabel.configure(text='0 phantom') def printr(info): self.consolelabeldata.append(str(info)) self.consolelabeldata = self.consolelabeldata[-4:] self.consolelabel.configure(text='\n'.join(self.consolelabeldata)) def translatemouse(event, middlemouse=False): event.x -= 9 event.y -= 9 #485 event.x /= 8 event.y /= 12 #spawncandy(round(event.x), round(event.y)) #print(event.x, event.y) xdif = event.x - self.xpos ydif = event.y - self.ypos if abs(xdif) >= 0.5 or abs(ydif) >= 0.5: if abs(xdif) >= abs(ydif): xdif /= abs(xdif) xdif = int(xdif) mfresh(xmove= xdif) else: ydif /= abs(ydif) ydif = int(ydif) mfresh(ymove= ydif) def middlemouse(): if self.isdeath: restart() else: spawnphantom() tkvar.bind('<Button-1>', translatemouse) tkvar.bind('<Button-2>', lambda data=self.data: middlemouse()) tkvar.bind('<Button-3>', lambda data=self.data: spawnbomb()) def helpreel(): self.helplabelindex += 1 if self.helplabelindex > (len(self.helplabeltexts) - 1): self.helplabelindex = 0 self.helplabel.configure(text=self.helplabeltexts[self.helplabelindex]) def collect(score): for x in range(score): self.collections += 1 if self.collections % self.bombcost == 0: self.bombs += 1 def spawnbomb(): goodtogo = True for bombs in self.bomblist: if bombs.x == self.xpos and bombs.y == self.ypos: goodtogo = False if goodtogo: if self.bombs > 0: self.bombs -= 1 newbomb = bomb(self.xpos, self.ypos) self.bomblist.append(newbomb) self.entlist.append(newbomb) mfresh() def spawnphantom(): goodtogo = True if self.collections < self.phantomcost: tempvar='[ ' + self.symbols['char'] + ' ] Not enough Candy. ' + str(self.collections) + '/' + str(self.phantomcost) + '. -' + str(self.phantomcost-self.collections) print(tempvar) printr(tempvar) goodtogo = False if self.phantomlist != []: goodtogo = False if goodtogo: life = 15 self.collections = 0 life += round(self.collections / 3) tempvar = '[ ' + self.symbols['char'] + ' ] New phantom with ' + str(life) + ' life' print(tempvar) printr(tempvar) newphantom = phantom(self.xpos, self.ypos, life) self.phantomlist.append(newphantom) self.entlist.append(newphantom) mfresh() def spawncandy(forcex=None, forcey=None): goodtogo = True if forcex == None or forcey == None: newx = random.randint(1, arenasize-2) newy = random.randint(1, arenasize-2) else: newx = forcex newy = forcey if self.xpos == newx and self.ypos == newy: goodtogo = False if goodtogo: for candies in self.candylist: if candies.x == newx and candies.y == newy: goodtogo = False if goodtogo: tempvar = '[ ' + candy.symbol + ' ] New candy at ' + str(newx)+' '+str(newy) print(tempvar) printr(tempvar) newcan = candy(newx, newy) self.candylist.append(newcan) self.entlist.append(newcan) mfresh() def spawngoldcandy(forcex=None, forcey=None): goodtogo = True if forcex == None or forcey == None: newx = random.randint(1, arenasize-2) newy = random.randint(1, arenasize-2) spawntries = 0 while (dist(self.xpos, self.ypos, newx, newy) < self.enemyspawnmindist): newx = random.randint(1, arenasize-2) newy = random.randint(1, arenasize-2) spawntries += 1 #print('Rerolling from', newx, newy) if spawntries == 20: #print('Could not spawn enemy') goodtogo = False break else: newx = forcex newy = forcey if goodtogo: for entity in self.entlist: if entity.x == newx and entity.y == newy: goodtogo = False if goodtogo: lifespan= dist(self.xpos, self.ypos, newx, newy) lifespan *= 2 tempvar = '[ ' + goldcandy.symbol + ' ] New gold candy' print(tempvar) printr(tempvar) newcan = goldcandy(newx, newy, lifespan) self.goldcandylist.append(newcan) self.entlist.append(newcan) mfresh() def spawnenemy(): newx = random.randint(1, arenasize-2) newy = random.randint(1, arenasize-2) goodtogo = True spawntries = 0 while (dist(self.xpos, self.ypos, newx, newy) < self.enemyspawnmindist): newx = random.randint(1, arenasize-2) newy = random.randint(1, arenasize-2) spawntries += 1 #print('Rerolling from', newx, newy) if spawntries == 10: print('Could not spawn enemy') goodtogo = False break if goodtogo: for ens in self.enemylist: if ens.x == newx and ens.y == newy: goodtogo = False if goodtogo: tempvar = '[ ' + enemy.symbol + ' ] New enemy at '+str(newx)+' '+str(newy) print(tempvar) printr(tempvar) newen = enemy(newx, newy, 1) self.enemylist.append(newen) self.entlist.append(newen) mfresh() def restart(): tempvar = 'Resetting game.' print(tempvar) printr(tempvar) self.consolelabeldata = [] self.consolelabel.configure(text='') self.xpos = int((arenasize-1)/2) self.ypos = int((arenasize-1)/2) while self.entlist != []: del self.entlist[0] self.candylist = [] self.enemylist = [] self.bomblist = [] self.phantomlist = [] self.entlist = [] self.stepstaken = 0 self.collections = 0 self.bombs = 0 self.isdeath = False spawncandy() self.datalabel.configure(fg='Black') mfresh() def dist(xa, ya, xb, yb): #distance formula result = (xa - xb) **2 result += (ya - yb) ** 2 result = result ** 0.5 result = int(result) return result mfresh() spawncandy() tkvar.mainloop()
class EguanaGUI(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() # if not EguanaInit.eguana_root_dir_exists(): # EguanaInit.create_eguana_root_dir() def initUI(self): self.parent.title("EGUANA") self.style = ttk.Style() self.style.theme_use("alt") self.photoName = "eguana.gif" self.frame = Frame(self, relief=FLAT, borderwidth=10,bg='#FADC46') self.frame.pack(fill=BOTH, expand=True) self.pack(fill=BOTH, expand=True) self.setupMenuBar() self.setupTopBar() def setupMenuBar(self): self.menubar = EguanaMenu(self.parent,self) self.parent.config(menu=self.menubar) def setupTopBar(self): self.supportedDevices = [] for fileName in [name for name in os.listdir('./machineConfig') if os.path.isfile('./machineConfig/' + name) and not name == 'eguanaMachineConfig.py' and name.endswith('.py')]: # try:{ components = fileName.split('.') fileName = components[0] className = fileName[0].upper() + fileName[1:] try: module = __import__("machineConfig."+fileName,fromlist=["machineConfig."]) classVar = getattr(module,className) except: continue self.supportedDevices.append(classVar()) # except: # pass self.selectMachineFrame = Frame(self.frame,relief=FLAT,bg='#FADC46') self.selectMachineFrame.pack(fill=BOTH,expand=True) self.setupSelectMachineButtons() def setupSelectMachineButtons(self): numDevices = len(self.supportedDevices) numColumns = 3 numRows = math.ceil((numDevices+1)/3) self.photo = PhotoImage(file="eguana.gif") self.photo = self.photo.subsample(2); self.photo_label = Label(self.selectMachineFrame,image=self.photo,borderwidth=0,highlightthickness=0) self.photo_label.configure(bg='#FADC46') self.photo_label.grid(row=int(numRows/2),column=1, sticky=N+S+E+W,padx=2,pady =2) self.photo_label.image = self.photo index = 0 for i in range(numRows): for j in range(numColumns): if not(j == 1 and i == int(numRows/2)) and (index < numDevices): device = self.supportedDevices[index] b = Button(self.selectMachineFrame,text=device.name,relief=RAISED, command=lambda device=device :self.machineButtonPressed(device)) b.grid(row=i,column=j, sticky=N+S+E+W,padx=2,pady =2) index += 1 for i in range(numRows): self.selectMachineFrame.rowconfigure(i,weight=1) for i in range(numColumns): self.selectMachineFrame.columnconfigure(i,weight=1) def machineButtonPressed(self,inputDevice): dirStr = filedialog.askdirectory() if len(dirStr) and inputDevice.isDirectoryValid(dirStr): inputDevice.setDirPath(dirStr) EguanaModel().machine = inputDevice self.selectMachineFrame.destroy() self.menubar.inputSelected() self.photo_label.destroy() dirStr = 'Input Path : '+dirStr self.selectPlotFrame = Frame(self.frame, relief=FLAT,bg='#FADC46') self.selectPlotFrame.pack(fill=BOTH,expand=True) self.selectPlotFrame.rowconfigure(0,weight=1) self.selectPlotFrame.rowconfigure(1,weight=2) self.selectPlotFrame.columnconfigure(0,weight=1) self.infoFrame = Frame(self.selectPlotFrame, relief=FLAT, bg='#FADC46') self.infoFrame.grid(row=0,column=0, sticky=N+S+E+W,padx=2,pady =2) self.machineNameLabel = Label(self.infoFrame, text=inputDevice.name,relief=FLAT) self.machineNameLabel.grid(row=0,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel = Label(self.infoFrame, text="No project currently selected",relief=FLAT) self.directoryLabel.grid(row=1,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.directoryLabel.config(text=dirStr) self.outputDirButton = Button(self.infoFrame,text="No output directory selected. Click to select an output directory ",relief=RAISED,fg='red',command=self.askOutputDirectory) self.outputDirButton.grid(row=2,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.filterButton = Button(self.infoFrame,text="No filter selected. Click to select a filter",relief=RAISED,fg='red',command=self.selectFilter) self.filterButton.grid(row=3,column=0,columnspan=2, sticky=N+S+E+W,padx=2,pady =2) self.trialLabel = Label(self.infoFrame,text="Trial Number",relief=FLAT,justify=RIGHT,anchor=E) self.trialLabel.grid(row=4,column=0, sticky=N+S+E+W,padx=2,pady =2) vcmd = (self.master.register(self.validate),'%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') self.trialEntry = Entry(self.infoFrame,validate = 'key', validatecommand = vcmd) self.trialEntry.grid(row=4,column=1, sticky=N+S+E+W,padx=2,pady =2) self.infoFrame.columnconfigure(0, weight=1) self.infoFrame.columnconfigure(1, weight=1) self.infoFrame.rowconfigure(0, weight=1) self.infoFrame.rowconfigure(1, weight=10) self.infoFrame.rowconfigure(2, weight=10) self.infoFrame.rowconfigure(3, weight=10) self.infoFrame.rowconfigure(4, weight=10) self.showPlotTools() def validate(self, action, index, value_if_allowed, prior_value, text, validation_type, trigger_type, widget_name): if len(value_if_allowed)==0 : return True if text in '0123456789.-+ ': try: float(value_if_allowed) return True except ValueError: return False else: return False def askOutputDirectory(self): dirStr = filedialog.askdirectory() if len(dirStr): dirStr = 'Output Path : '+dirStr self.outputDirButton.config(text=dirStr) def showPlotTools(self): f2= Frame(self.selectPlotFrame, relief=FLAT,bg='#FADC46') f2.grid(row=1,column=0,sticky=N+S+E+W,padx=10,pady =10) b1 = Button(f2,text='3D K',relief=RAISED,command= lambda:self.plotButtonPressed(1)) b1.grid(row=0, column=0,sticky=N+S+E+W,padx=5,pady =5) b2 = Button(f2,text='3D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(2)) b2.grid(row=0, column=1,sticky=N+S+E+W,padx=5,pady =5) b3 = Button(f2,text='3D DP',relief=RAISED,command=lambda:self.plotButtonPressed(3)) b3.grid(row=0, column=2,sticky=N+S+E+W,padx=5,pady =5) b4 = Button(f2,text='2D K',relief=RAISED,command=lambda:self.plotButtonPressed(4)) b4.grid(row=1, column=0,sticky=N+S+E+W,padx=5,pady =5) b5 = Button(f2,text='2D Dist',relief=RAISED,command=lambda:self.plotButtonPressed(5)) b5.grid(row=1, column=1,sticky=N+S+E+W,padx=5,pady =5) b6 = Button(f2,text='2D DP',relief=RAISED,command=lambda:self.plotButtonPressed(6)) b6.grid(row=1, column=2,sticky=N+S+E+W,padx=5,pady =5) b1.config(state=EguanaModel().machine.plot3DKButtonState) b2.config(state=EguanaModel().machine.plot3DDstButtonState) b3.config(state=EguanaModel().machine.plot3DDpButtonState) b4.config(state=EguanaModel().machine.plot2DKButtonState) b5.config(state=EguanaModel().machine.plot2DDstButtonState) b6.config(state=EguanaModel().machine.plot2DDpButtonState) f2.columnconfigure(0, weight=1) f2.columnconfigure(1, weight=1) f2.columnconfigure(2, weight=1) f2.rowconfigure(0, weight=1) f2.rowconfigure(1, weight=1) def plotButtonPressed(self,number): trialNum = self.trialEntry.get() try: trialNum = int(trialNum) print(EguanaModel().machine.ifTrialExists(trialNum)) if EguanaModel().machine.ifTrialExists(trialNum): self.plotFigure(number) return True else: messagebox.showerror( "Trial Number Error", "The trial doesn't exist" ) return False except ValueError: messagebox.showerror( "Trial Number Error", "Error with the trial number" ) return False def plotFigure(self,number): m = CoilNumDialog(self.frame) if m.isSet(): print(m.getValues()) EguanaModel().machine.getDataForTrialNumber(number) def selectFilter(self): ffPopup = FilterFunctionPopup(self) if ffPopup.selectedFilter is not None: EguanaModel().filterFunction = ffPopup.selectedFilter ftPopup = FilterTypePopup(self,ffPopup.selectedFilter) if (ftPopup.selectedHeadFilterType is not None) and (ftPopup.selectedHeadFilterType is not None): self.menubar.setSelectedFilters(ffPopup.selectedFilter,ftPopup.selectedHeadFilterType,ftPopup.selectedJawFilterType) EguanaModel().filterTypeHead = ftPopup.selectedHeadFilterType EguanaModel().filterTypeJaw = ftPopup.selectedJawFilterType EguanaModel().filterFunction = ffPopup.selectedFilter buttonText = '{} - Jaw Filter : {} - Head Filter {}'.format(ffPopup.selectedFilter.name,ftPopup.selectedJawFilterType.name, ftPopup.selectedHeadFilterType.name) self.filterButton.config(text=buttonText) def updateSelectedFilters(self,ffName,ftHeadName,ftJawName): buttonText = '{} - Jaw Filter : {} - Head Filter {}'.format(ffName,ftHeadName,ftJawName) self.filterButton.config(text=buttonText) def changeImage(self): self.photo = PhotoImage(file=self.photoName) self.photo = self.photo.subsample(2); self.photo_label.image = self.photo self.photo_label.config(image=self.photo) def cursorPosition(self,event): if event.widget == self.openButton3D: if self.photoName == "eguana2.gif": self.photoName = "eguana.gif" self.changeImage() elif event.widget == self.openButton2D: if self.photoName == "eguana.gif": self.photoName = "eguana2.gif" self.changeImage()
class Main(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.db_set = False self.configure(relief=GROOVE) self.configure(borderwidth="2") # Manual link adding self.manual_btn = Button(self) self.manual_btn.place(relx=0.07, rely=0.81, height=45, width=130) self.manual_btn.configure(activebackground="#d9d9d9") self.manual_btn.configure(highlightbackground="#d9d9d9") self.manual_btn.configure(pady="0") self.manual_btn.configure(text="Add manually") self.manual_btn.configure(width=130) self.file_btn = Button(self) self.file_btn.place(relx=0.67, rely=0.81, height=45, width=150) self.file_btn.configure(activebackground="#d9d9d9") self.file_btn.configure(highlightbackground="#d9d9d9") self.file_btn.configure(pady="0") self.file_btn.configure(text="Add from file") self.label = Label(self) self.label.place(relx=0.08, rely=0.0, height=61, width=484) self.label.configure(text="Create new playlists and add content to them") self.label.configure(width=485) self.listbox = Listbox(self) self.listbox.place(relx=0.38, rely=0.22, relheight=0.31, relwidth=0.17) self.listbox.configure(background="white") self.listbox.configure(disabledforeground="#a3a3a3") self.listbox.configure(foreground="#000000") self.listbox.configure(selectmode=SINGLE) self.listbox.configure(width=105) for name, value in config.configparser.items('Playlists'): if os.path.isdir(value): self.listbox.insert('end', name) else: config.remove_value('Playlists', name) self.listbox.bind('<<ListboxSelect>>', self.onselect) self.label_name = Label(self) self.label_name.place(relx=0.7, rely=0.22, height=31, width=84) self.label_name.configure(foreground="#000000") self.label_name.configure(text="Name") self.label_name.configure(width=85) self.entry = Entry(self) self.entry.place(relx=0.63, rely=0.31, relheight=0.08, relwidth=0.29) self.entry.configure(background="white") self.entry.configure(foreground="#000000") self.entry.configure(insertbackground="black") self.entry.configure(takefocus="0") self.entry.configure(width=175) self.change_name = Button(self) self.change_name.place(relx=0.7, rely=0.42, height=34, width=97) self.change_name.configure(activebackground="#d9d9d9") self.change_name.configure(highlightbackground="#d9d9d9") self.change_name.configure(highlightcolor="black") self.change_name.configure(pady="0") self.change_name.configure(text="Rename") self.change_name.configure(width=100) self.new_playlist = Button(self, command=self.new_database) self.new_playlist.place(relx=0.08, rely=0.28, height=54, width=107) self.new_playlist.configure(activebackground="#d9d9d9") self.new_playlist.configure(highlightbackground="#d9d9d9") self.new_playlist.configure(highlightcolor="black") self.new_playlist.configure(pady="0") self.new_playlist.configure(text="Create new playlist") self.new_playlist.configure(width=105) self.db_name = Entry(self) self.db_name.place(relx=0.07, rely=0.44, relheight=0.08, relwidth=0.22) self.db_name.configure(fg='grey') self.db_name.configure(width=135) self.db_name.insert(0, "Input database name here") self.db_name.bind('<Button-1>', lambda event: greytext(self.db_name)) def onselect(self, event): w = event.widget index = int(w.curselection()[0]) value = w.get(index) set_database(config.configparser.get('Playlists', value)) if not database.check_integrity(): messagebox.showwarning('Integrity check failed', 'You might be missing some entries in your list') if not self.db_set: self.manual_btn.configure(command=lambda: self.controller.show_frame('AddManually')) self.file_btn.configure(command=lambda: self.controller.show_frame('ReadFromFile')) self.db_set = True def new_database(self): name = self.db_name.get() names = config.configparser.options('Playlists') print(name, names) if name.strip() == '' or self.db_name.cget('fg') == 'grey': messagebox.showerror('Invalid name', "Please input a valid name for the database") return if name in names: messagebox.showerror('Name already in use', "Please select another name") return path = '../playlists/%s/' % name if set_database(path, create=True) is False: return config.set_value('Playlists', name, path) self.listbox.insert('end', name)
class ReadFromFile(Frame): def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.link_first = True self.items = [] self.place(relx=0.0, rely=0.0, relheight=0.62, relwidth=0.72) self.configure(relief=GROOVE) self.configure(borderwidth="2") label_top = Label(self) label_top.place(relx=0.42, rely=0.03, height=21, width=105) label_top.configure(text="Select a file to read") self.file_select = Button(self, command=self.fopen) self.file_select.place(relx=0.43, rely=0.14, height=34, width=97) self.file_select.configure(text="Select file") self.back = Button(self, command=lambda: controller.show_frame('Main')) self.back.place(relx=0.8, rely=0.87, height=34, width=97) self.back.configure(text="Go back") self.delimeter = Entry(self) self.delimeter.place(relx=0.02, rely=0.11, relheight=0.06, relwidth=0.21) self.delimeter.insert(0, ' -<>- ') label_delim = Label(self) label_delim.place(relx=0.02, rely=0.03, height=21, width=57) label_delim.configure(text="Delimeter") self.switch_label = Label(self) self.switch_label.place(relx=0.73, rely=0.31, height=21, width=38) self.switch_label.configure(text="Link") self.switch_label2 = Label(self) self.switch_label2.place(relx=0.9, rely=0.31, height=21, width=38) self.switch_label2.configure(text="Name") self.change_order = Button(self, command=self.switch_order) self.change_order.place(relx=0.82, rely=0.31, height=24, width=32) self.change_order.configure(text="<->") name_or_link = Label(self) name_or_link.place(relx=0.75, rely=0.19, height=21, width=97) name_or_link.configure(text="Name or link first") self.items_text = Text(self) self.items_text.place(relx=0.02, rely=0.5, relheight=0.46, relwidth=0.76) self.items_text.configure(wrap=tk.WORD) label_items = Label(self) label_items.place(relx=0.35, rely=0.42, height=21, width=35) label_items.configure(text="Items") self.commit_btn = Button(self, command=self.commit) self.commit_btn.place(relx=0.83, rely=0.64, height=34, width=67) self.commit_btn.configure(text="Commit") self.Label12 = Label(self) self.Label12.place(relx=0.02, rely=0.19, height=21, width=88) self.Label12.configure(text="Link formatting (optional)") self.link_part1 = Entry(self, fg='grey') self.link_part1.place(relx=0.02, rely=0.28, relheight=0.06, relwidth=0.37) self.link_part1.insert(0, "Start of the link here") self.link_part1.bind('<Button-1>', lambda event: greytext(self.link_part1)) self.link_part2 = Entry(self, fg='grey') self.link_part2.place(relx=0.02, rely=0.36, relheight=0.06, relwidth=0.37) self.link_part2.insert(0, "End of the link here") self.link_part2.bind('<Button-1>', lambda event: greytext(self.link_part2)) def fopen(self): filename = askopenfilename() if filename == '': return self.items.clear() self.items_text.delete(1.0, 'end') with open(filename, encoding='utf-8-sig') as f: lines = f.read().splitlines() delim = self.delimeter.get() for line in lines: try: link, name = line.split(delim, 1) if not self.link_first: name, link = link, name if '{DELETED} ' in name[:13]: continue s, e = self.get_link_formatting() link = s + link + e self.items += [(link, name)] self.items_text.insert('end', ("name: " + name + "\nlink: " + link + '\n\n')) except ValueError: print("Something went wrong: ", line) def get_link_formatting(self): link1, link2 = self.link_part1, self.link_part2 start = '' end = '' if link1.cget('fg') != 'grey': start = link1.get() if link2.cget('fg') != 'grey': end = link2.get() return start, end def switch_order(self): s1, s2 = self.switch_label, self.switch_label2 text1, text2 = s1.cget('text'), s2.cget('text') s1.configure(text=text2) s2.configure(text=text1) self.link_first = not self.link_first def commit(self): for item in self.items: self.controller.add_item(item[0], item[1]) print('Items added')
def __init__(self, parent, controller): Frame.__init__(self, parent) self.controller = controller self.link_first = True self.items = [] self.place(relx=0.0, rely=0.0, relheight=0.62, relwidth=0.72) self.configure(relief=GROOVE) self.configure(borderwidth="2") label_top = Label(self) label_top.place(relx=0.42, rely=0.03, height=21, width=105) label_top.configure(text="Select a file to read") self.file_select = Button(self, command=self.fopen) self.file_select.place(relx=0.43, rely=0.14, height=34, width=97) self.file_select.configure(text="Select file") self.back = Button(self, command=lambda: controller.show_frame('Main')) self.back.place(relx=0.8, rely=0.87, height=34, width=97) self.back.configure(text="Go back") self.delimeter = Entry(self) self.delimeter.place(relx=0.02, rely=0.11, relheight=0.06, relwidth=0.21) self.delimeter.insert(0, ' -<>- ') label_delim = Label(self) label_delim.place(relx=0.02, rely=0.03, height=21, width=57) label_delim.configure(text="Delimeter") self.switch_label = Label(self) self.switch_label.place(relx=0.73, rely=0.31, height=21, width=38) self.switch_label.configure(text="Link") self.switch_label2 = Label(self) self.switch_label2.place(relx=0.9, rely=0.31, height=21, width=38) self.switch_label2.configure(text="Name") self.change_order = Button(self, command=self.switch_order) self.change_order.place(relx=0.82, rely=0.31, height=24, width=32) self.change_order.configure(text="<->") name_or_link = Label(self) name_or_link.place(relx=0.75, rely=0.19, height=21, width=97) name_or_link.configure(text="Name or link first") self.items_text = Text(self) self.items_text.place(relx=0.02, rely=0.5, relheight=0.46, relwidth=0.76) self.items_text.configure(wrap=tk.WORD) label_items = Label(self) label_items.place(relx=0.35, rely=0.42, height=21, width=35) label_items.configure(text="Items") self.commit_btn = Button(self, command=self.commit) self.commit_btn.place(relx=0.83, rely=0.64, height=34, width=67) self.commit_btn.configure(text="Commit") self.Label12 = Label(self) self.Label12.place(relx=0.02, rely=0.19, height=21, width=88) self.Label12.configure(text="Link formatting (optional)") self.link_part1 = Entry(self, fg='grey') self.link_part1.place(relx=0.02, rely=0.28, relheight=0.06, relwidth=0.37) self.link_part1.insert(0, "Start of the link here") self.link_part1.bind('<Button-1>', lambda event: greytext(self.link_part1)) self.link_part2 = Entry(self, fg='grey') self.link_part2.place(relx=0.02, rely=0.36, relheight=0.06, relwidth=0.37) self.link_part2.insert(0, "End of the link here") self.link_part2.bind('<Button-1>', lambda event: greytext(self.link_part2))