def create_spinbox(self): P0, widget_dims, board_dims = self.board.get_geometry() x, y = P0 width, height = widget_dims board_width, board_height = board_dims x, y = x / board_width, y / board_height width, height = width / board_width, height / board_height box = Spinbox(self.board) box.place(relx=x, rely=y, relheight=height, relwidth=width, anchor="nw") self.board.delete("line") items = [item for item in box.keys() if len(item) > 2] box.bind("<Enter>", lambda event: self.get_widget_info(box)) box.bind("<Leave>", lambda event: self.focus_out()) box.bind("<Button-3>", lambda event: self.modify(box, items)) self.manager.switch(box, items)
delete_dup = IntVar() approachVar = IntVar() multiprocessingVar = IntVar() thresholdVar = IntVar() lbl_dir = Label(root, text='Directory') lbl_dir.place(x=20, y=30, width=120, height=25) lbl_path = Entry(root, textvariable=folder_path) lbl_path.place(x=150, y=30, width=120, height=25) button_browse = Button(text="Browse", command=browse_button) button_browse.place(x=280, y=30, width=120, height=25) lbl_thresh = Label(root, text='Threshold') lbl_thresh.place(x=20, y=60, width=120, height=25) Spinbox_thresh = Spinbox(root, from_=0, to=100) Spinbox_thresh.place(x=150, y=60, width=120, height=25) lbl_approach = Label(root, text='Calc Approach') lbl_approach.place(x=20, y=90, width=120, height=25) R1 = Radiobutton(root, text="Hamming", variable=approachVar, value=1) R1.place(x=150, y=90, width=90, height=25) R2 = Radiobutton(root, text="SSIM Index", variable=approachVar, value=2) R2.place(x=260, y=90, width=110, height=25) lbl_deldup = Label(root, text='Delete Duplicate') lbl_deldup.place(x=20, y=120, width=120, height=25) Rb1 = Radiobutton(root, text="Yes", variable=delete_dup, value=1) Rb1.place(x=150, y=120, width=50, height=25) Rb2 = Radiobutton(root, text="No", variable=delete_dup, value=2) Rb2.place(x=210, y=120, width=50, height=25)
class Interface: """ GUI class """ def __init__(self, master): # colour swatches self.gray1 = "#f6f6f6" self.gray2 = "#eaeaea" self.gray3 = "#d9d9d9" # key parameters self.running = False self.sect_width = 360 self.rb_choice = StringVar() self.dob1_val = StringVar() self.dob2_val = StringVar() self.df_records = StringVar() master.geometry("800x600+200+200") master.title("Red Snapper") master.resizable(False, False) master.configure(background=self.gray1) # LEFT SECTION LAYER # -------------------------------------------------------------------- self.sect_left = Frame(master) self.sect_left.place(x=15, y=15, width=self.sect_width, height=570) self.sect_left.config(relief=RIDGE) self.sect_left.config(background=self.gray2) # RIGHT SECTION LAYER # -------------------------------------------------------------------- self.sect_right = Frame(master) self.sect_right.place(x=-15, y=200, width=self.sect_width, height=385) self.sect_right.place(relx=1.0, anchor="ne") self.sect_right.config(relief=RIDGE) self.sect_right.config(background=self.gray2) # Sliders layer self.layer_sliders = Frame(self.sect_left) self.layer_sliders.place(y=0, width=self.sect_width, height=320) self.layer_sliders.config(**self.layer_props(self.gray2)) self.lab_sliders = Label(self.layer_sliders) self.lab_sliders.config(**self.title_props("Parameters")) self.lab_sliders.pack() # DOB layer self.layer_dob = Frame(self.sect_left) self.layer_dob.place(y=320, width=self.sect_width, height=80) self.layer_dob.config(**self.layer_props(self.gray2)) self.lab_dob = Label(self.layer_dob) self.lab_dob.config(**self.title_props("Birthdays range")) self.lab_dob.pack() # Export layer self.layer_export = Frame(self.sect_left) self.layer_export.place(y=400, width=self.sect_width, height=80) self.layer_export.config(**self.layer_props(self.gray2)) self.lab_export = Label(self.layer_export) self.lab_export.config(**self.title_props("Export format")) self.lab_export.pack() # Run layer self.layer_run = Frame(self.sect_left) self.layer_run.place(y=480, width=self.sect_width, height=100) self.layer_run.config(**self.layer_props(self.gray2)) self.lab_run = Label(self.layer_run) self.lab_run.config(**self.title_props("Run")) self.lab_run.pack() # About layer self.layer_about = Frame(self.sect_right) self.layer_about.place(width=self.sect_width, height=385) self.layer_about.config(**self.layer_props(self.gray2)) self.lab_about = Label(self.layer_about) self.lab_about.config(**self.title_props("About Red Snapper")) self.lab_about.pack() # sliders self.sli_wom = Scale(self.layer_sliders, from_=0, to=100) self.sli_wom.config(**self.sli_props()) self.sli_wom.config(label="Percentage of women in dataset.") self.sli_wom.pack(padx=20, pady=10) self.sli_wom.set(50) self.sli_nam = Scale(self.layer_sliders, from_=0, to=100) self.sli_nam.config(**self.sli_props()) self.sli_nam.config(label="Percentage of people with double name") self.sli_nam.pack(padx=20, pady=0) self.sli_nam.set(25) self.sli_sur = Scale(self.layer_sliders, from_=0, to=100) self.sli_sur.config(**self.sli_props()) self.sli_sur.config(label="Percentage of people with double surname") self.sli_sur.pack(padx=20, pady=10) self.sli_sur.set(15) # DOB Layer - From Date self.dob1_val.set("1945") self.lab_dob1 = Label(self.layer_dob, text="From date") self.lab_dob1.config(**self.label_props()) self.lab_dob1.pack(side=LEFT, padx=5) self.box_dob1 = Spinbox(self.layer_dob) self.box_dob1.config(from_=1945, to=1996, textvariable=self.dob1_val) self.box_dob1.config(**self.date_props()) self.box_dob1.pack(side=LEFT) # DOB Layer - To Date self.dob2_val.set("1997") self.lab_dob2 = Label(self.layer_dob, text="To date") self.lab_dob2.config(**self.label_props()) self.lab_dob2.pack(side=LEFT, padx=17) self.box_dob2 = Spinbox(self.layer_dob) self.box_dob2.config(from_=1946, to=1997, textvariable=self.dob2_val) self.box_dob2.config(**self.date_props()) self.box_dob2.pack(side=LEFT) # Export layer - JSON / CSV radio buttons self.rb_choice.set("CSV") self.rb1 = Radiobutton(self.layer_export, text="Save as CSV", variable=self.rb_choice, value="CSV") self.rb1.config(**self.radio_props()) self.rb1.place(y=35, x=50) self.rb2 = Radiobutton(self.layer_export, text="Save as JSON", variable=self.rb_choice, value="JSON") self.rb2.config(**self.radio_props()) self.rb2.place(y=35, x=200) # Run layer - no of records spinbox self.df_records.set("100") self.box_gen = Spinbox(self.layer_run) self.box_gen.config(from_=1, to=999999, textvariable=self.df_records) self.box_gen.config(increment=1000, width=19) self.box_gen.place(x=70, y=53) self.lab_gen = Label(self.layer_run, text="Number of records") self.lab_gen.config(**self.label_props()) self.lab_gen.place(x=70, y=30) # Run layer - generate button self.btn_run = ttk.Button(self.layer_run) self.btn_run.place(x=225, y=35, height=40) self.btn_run_reset() # header & logo section self.sect_logo = Frame(master) self.sect_logo.place(x=-15, y=30, width=350, height=120) self.sect_logo.place(relx=1.0, anchor="ne") self.logo = PhotoImage(file="./redsnapper/interface/logo.png") self.lab_logo = Label(self.sect_logo, image=self.logo) self.lab_logo.config(background=self.gray1) self.lab_logo.pack() # About box_about = Text(self.layer_about) box_about.config(**self.text_props()) box_about.pack(pady=10, padx=10) txt = """This program allows generating thousands of rows filled with pseudo-random data. """ \ + """\nThe generated records (like name, """ \ + """ surname, date of birth, e-mail address) can be used to provide sample data to: - test query performance of your database - practice data operations with BI tools.""" \ + """ \nThe application uses 4 processes to generate data simultaneously. """ \ + """ It takes about 25 seconds to create 1 million rows of data.\n""" box_about.insert(END, txt) # styling wrapped into functions for reusability def sli_props(self): """ bundle popular attributes of TK control so they can be reused :return: dict of bundled props """ return { "length": 300, "orient": HORIZONTAL, "sliderrelief": FLAT, "showvalue": 1, "resolution": 1, "sliderlength": 25, "tickinterval": 100, "font": ("Arial", 8), "activebackground": "#333333", "background": "#666666", "troughcolor": "#d0d4d2", "foreground": "#eeeeee", "highlightthickness": 8, "highlightcolor": "#ffffff", "highlightbackground": self.gray3, "borderwidth": 1 } @staticmethod def layer_props(bgcolor): """ bundle popular attributes of TK control so they can be reused :return: dict of bundled props """ return {"relief": RIDGE, "background": bgcolor} def title_props(self, title): """ bundle popular attributes of TK control so they can be reused :return: dict of bundled props """ return { "text": title, "background": self.gray3, "width": self.sect_width, "borderwidth": 1, "relief": RIDGE } def radio_props(self): """ bundle popular attributes of TK control so they can be reused :return: dict of bundled props """ return { "background": self.gray2, "activebackground": self.gray2, } def date_props(self): """ bundle popular attributes of TK control so they can be reused :return: dict of bundled props """ return { "width": 8, "increment": 1, "font": ("Arial", 8), "background": "#666666", "buttonbackground": "#666666", "foreground": "#eeeeee", "highlightthickness": 8, "highlightcolor": "#ffffff", "highlightbackground": self.gray2, "borderwidth": 1 } def label_props(self): """ bundle popular attributes of TK control so they can be reused :return: dict of bundled props """ return { "background": self.gray2, "highlightcolor": "#ffffff", "highlightbackground": self.gray2, "borderwidth": 1 } def text_props(self): """ bundle popular attributes of TK control so they can be reused :return: dict of bundled props """ return { "font": ("Arial", 11), "background": self.gray1, "foreground": "#212121", "highlightthickness": 8, "highlightbackground": self.gray1, "highlightcolor": self.gray1, "borderwidth": 0, "wrap": "word", "spacing1": 11, "spacing2": 7, } def produce_props(self): """ produce dict of key GUI parameters selected by user :return: no return parameters """ rows = int(self.box_gen.get()) props = { "pgender": self.sli_wom.get(), "pdname": self.sli_nam.get(), "pdsurname": self.sli_sur.get(), "dob1": self.box_dob1.get(), "dob2": self.box_dob2.get(), } dataset = Dataset().run_workload(rows, **props) exp_format = self.rb_choice.get() if exp_format == "CSV": Export().to_csv(dataset) else: Export().to_json(dataset) self.btn_run_reset() return def btn_run_reset(self): """ abort button (when generating) :return: no return parameters """ self.running = False self.btn_run.config(text="Generate", command=self.btn_run_start) return def btn_run_start(self): """ handle the run button :return: no return parameters """ self.running = True newthread = threading.Thread(target=self.produce_props) newthread.start() self.btn_run.config(text="Abort", command=self.btn_run_reset) return
class Window(Frame): def __init__(self, master=None): Frame.__init__(self, master) self.master = master self.inventory_region = tuple(config_dict["positions"]["inventory_region"]) self.tabs_positions= config_dict["positions"]["tabs_positions"] self.number_of_tabs= IntVar() self.number_of_tabs.set(config_dict["vars"]["number_of_tabs"]) self.player_position= config_dict["positions"]["player_position"] trash_list = os.listdir("trash\\") try: trash_list.remove("Thumbs.db") #~remove Thumbs.db except: pass self.trash_dir_list= trash_list self.trash_remove_list=config_dict["lists"]["trash_remove_list"] self.init_window() def init_window(self): self.master.title("Metin2 Trash remover") self.pack(fill=BOTH, expand=1) self.quit_button = Button(self, text="Quit", command=self.client_exit) self.quit_button.place(x=0, y=0) self.window_coord_button= Button(self, text="Set inventory area", command=self.get_inv_region) self.window_coord_button.place(x=39, y=88) self.number_of_tabs_spinbox= Spinbox(self, from_=1, to=5, width=3, textvariable=self.number_of_tabs) self.number_of_tabs_spinbox.place(x=21, y=52) self.get_tabs_positions_button= Button(self, text="Set Tabs positions", command=self.get_tabs_position) self.get_tabs_positions_button.place(x=64, y=49) self.set_player_positions_button= Button(self, text="Set player position", command=self.get_player_position) self.set_player_positions_button.place(x=41, y=127) self.run_button= Button(self,text="Run", command=self.destroy_trash_items) self.run_button.place(x=78, y=201) self.trash_button= Button(self,text="Items to delete", command=self.selector_popup) self.trash_button.place(x=49, y=163) def selector_popup(self): win = Toplevel(self.master) win.wm_title("Trash selector") j=0 i=0 for item in self.trash_dir_list: pilImage = PILimage.open(f"trash\\{item}") phoImage = ImageTk.PhotoImage(pilImage) if item in self.trash_remove_list: #i had a problem using the expression lambda: self.update_trash_list(item), the problem was that #lambda references the memory location of the variable item (i suppose). so we need to bind the item value to a parameter of the lambda. cb = Checkbutton(win, image = phoImage, command=lambda x = item: self.update_trash_list(x)) cb.select() cb.select() else: cb = Checkbutton(win, image = phoImage, command=lambda x = item: self.update_trash_list(x)) #we need to keep a reference of the image, otherwise python garbage collector will make the pictures transparent cb.image = phoImage cb.grid(row= j, column=i) i=i+1 #with this, each time we pack "x" items, we add one to the row variable if ( i%6 == 5): j=j+1 i=0 def update_trash_list(self, item): if item in self.trash_remove_list: self.trash_remove_list.remove(item) else: self.trash_remove_list.append(item) def client_exit(self): exit() def get_inv_region(self): with ThreadPoolExecutor(max_workers=1) as executor: region= executor.submit(get_window_region) self.inventory_region=region.result() def get_tabs_position(self): if self.number_of_tabs is not None: with ThreadPoolExecutor(max_workers=1) as executor: tabs_func = executor.submit(get_positions, self.number_of_tabs.get()) self.tabs_positions= tabs_func.result() else: messagebox.showerror("Error", "Change the number of tabs to a valid value") def get_player_position(self): with ThreadPoolExecutor(max_workers=1) as executor: pos_func= executor.submit(get_positions, 1) #get_positions expects the number of positions to fetch from the clicks self.player_position=pos_func.result() def destroy_trash_items(self): if self.number_of_tabs is not None and self.inventory_region is not None and self.player_position is not None: with ThreadPoolExecutor(max_workers=5) as executor: remove_func= executor.submit(remove_trash,self.trash_remove_list, self.inventory_region, self.tabs_positions, self.number_of_tabs.get(), self.player_position) remove_func.done() #after we run the main function we update the config values with the current positions with open('config.json', 'w') as configfile: config_dict['positions']['inventory_region'] = self.inventory_region config_dict['positions']['tabs_positions'] = self.tabs_positions config_dict['positions']['player_position'] = self.player_position config_dict['lists']['trash_remove_list'] = self.trash_remove_list config_dict["vars"]["number_of_tabs"] = self.number_of_tabs.get() json.dump(config_dict, configfile) else: messagebox.showerror("Error", "Inventory, tabs and player positions are required")
class NewCustomStretchWindow(Toplevel): def __init__(self, master=None): super().__init__(master=master) self.set_basic() self.set_widgets() def set_basic(self): self.minsize(300, 200) self.maxsize(300, 200) self.title("Rozciąganie") self.protocol("WM_DELETE_WINDOW", lambda: self.cancel()) def set_widgets(self): self.p1 = StringVar(self, value=np.amin(self.master.image.cv2Image)) self.p2 = StringVar(self, value=np.amax(self.master.image.cv2Image)) self.q1 = StringVar(self, value="0") self.q2 = StringVar(self, value="255") self.p1Entry = Spinbox(self, justify='center', font=("Helvetica", 15), from_=0, to=255, textvariable=self.p1) self.p2Entry = Spinbox(self, justify='center', font=("Helvetica", 15), from_=0, to=255, textvariable=self.p2) self.q1Entry = Spinbox(self, justify='center', font=("Helvetica", 15), from_=0, to=255, textvariable=self.q1) self.q2Entry = Spinbox(self, justify='center', font=("Helvetica", 15), from_=0, to=255, textvariable=self.q2) self.saveButton = Button(self, image=saveIcon, command=self.update_image) self.cancelButton = Button(self, image=closeIcon, command=self.cancel) self.place_widgets() def update_image(self): p1, p2, q1, q2 = self.getValues() if p1 is None: messagebox.showerror( "Błąd", "Wprowadź poprawne przedziały w postaci liczb całkowitych <0;255>" ) self.lift() self.focus_set() return else: self.master.image.stretch(p1, p2, q1, q2) self.master.manager.new_state(self.master.image.cv2Image) self.master.update_visible_image() self.master.update_child_windows() self.destroy() def place_widgets(self): Label(self, text="p1: ", font=("Helvetica", 15)).place(x=10, y=20) Label(self, text="p2: ", font=("Helvetica", 15)).place(x=130, y=20) Label(self, text="q1: ", font=("Helvetica", 15)).place(x=10, y=105) Label(self, text="q2: ", font=("Helvetica", 15)).place(x=130, y=105) self.p1Entry.place(width=80, height=50, x=50, y=10) self.p2Entry.place(width=80, height=50, x=170, y=10) self.q1Entry.place(width=80, height=50, x=50, y=90) self.q2Entry.place(width=80, height=50, x=170, y=90) self.saveButton.place(width=40, height=40, x=70, y=155) self.cancelButton.place(width=40, height=40, x=190, y=155) def cancel(self): self.destroy() def getValues(self): try: values = [ int(val.get()) for val in [self.p1, self.p2, self.q1, self.q2] ] except ValueError: return None return values[0], values[1], values[2], values[3]
class Settings(Frame): def __init__(self, master, widget, items, modifying=False): super().__init__(master, bg="#435661") self.widget = widget self.modifying = modifying self.record = {} self.index = 0 self.spin_relx = None self.spin_rely = None self.spin_relw = None self.spin_relh = None self.label_arguments = None self.entry_arguments = None self.listbox = None self.entry_name = None self.set_layout() self.set_bindings() self.set_listbox(items) self.set_spinboxes() def set_layout(self): # self-explanatory Label(self, background='#435661', text='relx:', foreground='#defffc') \ .place(relx=0.145, rely=0.0125, relwidth=0.1625, relheight=0.025, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='rely:') \ .place(relx=0.6845, rely=0.0135, relwidth=0.155, relheight=0.0225, anchor='nw') Label(self, background='#435661', text='relwidth:', foreground='#defffc') \ .place(relx=0.044, rely=0.089, relwidth=0.37, relheight=0.02125, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='relheight:') \ .place(relx=0.667, rely=0.0875, relwidth=0.195, relheight=0.02375, anchor='nw') self.spin_relx = Spinbox(self, readonlybackground='#defffc', highlightthickness=0, foreground='#435661', from_=0, command=self.mod_relx, to_=1, increment=0.001, justify='center') self.spin_relx.place(relx=0.085, rely=0.0425, relwidth=0.295, relheight=0.03375, anchor='nw') self.spin_rely = Spinbox(self, readonlybackground='#defffc', foreground='#435661', justify='center', highlightthickness=0, command=self.mod_rely, from_=0, to_=1, increment=0.001) self.spin_rely.place(relx=0.6135, rely=0.0425, relwidth=0.3005, relheight=0.03375, anchor='nw') self.spin_relw = Spinbox(self, readonlybackground='#defffc', foreground='#435661', justify='center', highlightthickness=0, command=self.mod_relwidth, from_=0, to_=1, increment=0.001) self.spin_relw.place(relx=0.084, rely=0.1175, relwidth=0.295, relheight=0.035, anchor='nw') self.spin_relh = Spinbox(self, readonlybackground='#defffc', foreground='#435661', justify='center', highlightthickness=0, command=self.mod_relheight, from_=0, to_=1, increment=0.001) self.spin_relh.place(relx=0.6115, rely=0.1177, relwidth=0.304, relheight=0.035, anchor='nw') self.label_arguments = Label(self, background='#557282', foreground='#defffc') self.label_arguments.place(relx=0.086, rely=0.1832, relwidth=0.8305, relheight=0.06125, anchor='nw') self.entry_arguments = Entry(self, background='#defffc', foreground='#435661', justify='center') self.entry_arguments.place(relx=0.22, rely=0.2625, relwidth=0.545, relheight=0.04375, anchor='nw') self.listbox = Listbox(self, background='#557282', foreground='#defffc', borderwidth=0) self.listbox.place(relx=0.085, rely=0.3275, relwidth=0.83, relheight=0.4062, anchor='nw') myButton(self, command=lambda *a: self.set_value(), text='OK') \ .place(relx=0.8245, rely=0.2672, relwidth=0.13, relheight=0.0355, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='Name:', anchor='w') \ .place(relx=0.083, rely=0.766, relwidth=0.1205, relheight=0.035, anchor='nw') self.entry_name = Entry(self, background='#defffc', foreground='#435661', justify='center') self.entry_name.place(relx=0.245, rely=0.7662, relwidth=0.5225, relheight=0.035, anchor='nw') self.entry_name.bind("<Return>", lambda *a: self.confirm()) myButton(self, command=lambda *a: self.confirm(), text='CONFIRM') \ .place(relx=0.201, rely=0.8575, relwidth=0.6155, relheight=0.0825, anchor='nw') def set_bindings(self): # self-explanatory self.entry_arguments.bind("<Return>", lambda *a: self.set_value()) self.listbox.bind("<ButtonRelease-1>", lambda *a: self.listbox_clicked()) self.master.root.bind("<Left>", lambda event: self.pressed_left_right(-1)) self.master.root.bind("<Right>", lambda event: self.pressed_left_right(1)) self.master.root.bind("<Up>", lambda event: self.pressed_up_down(-1)) self.master.root.bind("<Down>", lambda event: self.pressed_up_down(1)) def set_spinboxes(self): # self-explanatory self.spin_relx.delete(0, "end") self.spin_rely.delete(0, "end") self.spin_relw.delete(0, "end") self.spin_relh.delete(0, "end") self.spin_relx.insert("end", self.widget.place_info()["relx"]) self.spin_rely.insert("end", self.widget.place_info()["rely"]) self.spin_relw.insert("end", self.widget.place_info()["relwidth"]) self.spin_relh.insert("end", self.widget.place_info()["relheight"]) self.spin_relx.configure(state="readonly") self.spin_rely.configure(state="readonly") self.spin_relw.configure(state="readonly") self.spin_relh.configure(state="readonly") def mod_relx(self): # Changes widget's relx parameter accordingly value = float(self.spin_relx.get()) self.widget.place_configure(relx=value) def mod_rely(self): # Changes widget's rely parameter accordingly value = float(self.spin_rely.get()) self.widget.place_configure(rely=value) def mod_relwidth(self): # Changes widget's relwidth parameter accordingly value = float(self.spin_relw.get()) self.widget.place_configure(relwidth=value) def mod_relheight(self): # Changes widget's relheight parameter accordingly value = float(self.spin_relh.get()) self.widget.place_configure(relheight=value) def pressed_left_right(self, factor): value = float(self.spin_relx.get()) self.spin_relx.configure(state="normal") self.spin_relx.delete(0, "end") self.spin_relx.insert("end", value + factor * 0.001) self.spin_relx.configure(state="readonly") self.widget.place_configure(relx=value + factor * 0.001) def pressed_up_down(self, factor): value = float(self.spin_rely.get()) self.spin_rely.configure(state="normal") self.spin_rely.delete(0, "end") self.spin_rely.insert("end", value + factor * 0.001) self.spin_rely.configure(state="readonly") self.widget.place_configure(rely=value + factor * 0.001) def set_listbox(self, items): for item in items: self.listbox.insert("end", item) self.record[item] = self.widget.cget(item) def listbox_clicked(self): # Changes entry_arguments's text and label_arguments's text, sets focus on entry_name self.index = self.listbox.curselection()[0] parameter = list(self.record.keys())[self.index] value = self.record[parameter] self.entry_arguments.delete(0, "end") self.entry_arguments.insert("end", value) self.label_arguments.configure(text=f"{parameter} = {value}") self.entry_arguments.focus_set() def set_value(self): # Sets entry_arguments's value as widget's argument, it needs to be evaluated first to avoid errors parameter = list(self.record.keys())[self.index] value = self.entry_arguments.get() try: evaluated_value = eval(value) self.record[parameter] = evaluated_value except: evaluated_value = value self.record[parameter] = f"{evaluated_value}" self.widget.configure({parameter: evaluated_value}) self.label_arguments.configure(text=f"{parameter} = {value}") def confirm(self): # Checks if entry_name isn't empty or already used and then sends it to the master.Writer # After that it quits with .destroy() name = self.entry_name.get().replace(" ", "") if not self.modifying: if name and name not in self.master.record_of_names: self.master.record_of_names[name] = self.widget widget_cls = self.widget.winfo_class() self.master.writer.define_widget(name, widget_cls, self.widget.place_info()) self.master.writer.begin_configure(name) for key, value in self.record.items(): if value: self.master.writer.write_configure( name, key, f"'{value}'") self.master.writer.end_configure(name) self.master.root.unbind("<Down>") self.master.root.unbind("<Up>") self.master.root.unbind("<Left>") self.master.root.unbind("<Right>") self.destroy() else: widget_cls = self.widget.winfo_class() try: self.master.writer.define_widget(name, widget_cls, self.widget.place_info(), True) self.master.writer.begin_configure(name) except KeyError: self.entry_name.delete(0, "end") self.entry_name.insert("end", "NOME SBAGLIATO") return None for key, value in self.record.items(): if value: self.master.writer.write_configure(name, key, f"'{value}'") self.master.writer.end_configure(name) self.master.root.unbind("<Down>") self.master.root.unbind("<Up>") self.master.root.unbind("<Left>") self.master.root.unbind("<Right>") self.destroy()
class NewMorphWindow(Toplevel): def __init__(self, master=None): super().__init__(master=master) self.set_basic() self.set_widgets() def set_basic(self): self.minsize(500, 300) self.maxsize(500, 300) self.title("Operacje morfologiczne") self.protocol("WM_DELETE_WINDOW", lambda: self.cancel()) self.operations = [ "EROZJA", "DYLACJA", "OTWARCIE", "ZAMKNIĘCIE", "SZKIELETYZACJA" ] self.shapes = ["KWADRAT", "ROMB"] self.handleBorder = { "Bez zmian (isolated)": 0, "Odbicie lustrzane (reflect)": 1, "Powielenie skrajnego piksela (replicate)": 2 } def set_widgets(self): self.operationChoice = StringVar(self, self.operations[0]) self.shape = StringVar(self, value=self.shapes[0]) self.size = StringVar(self, value="3") self.borderType = StringVar(self, list(self.handleBorder.keys())[0]) self.operationChoice.trace("w", self.update_preview) self.shape.trace("w", self.update_preview) self.borderType.trace("w", self.update_preview) self.operationList = OptionMenu(self, self.operationChoice) self.shapeList = OptionMenu(self, self.shape) self.sizeSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=3, to=9999, textvariable=self.size, command=self.update_preview, state='readonly', increment=2) self.borderList = OptionMenu(self, self.borderType) for oper in self.operations: self.operationList['menu'].add_command( label=oper, command=lambda v=oper: self.operationChoice.set(v)) for sh in self.shapes: self.shapeList['menu'].add_command( label=sh, command=lambda v=sh: self.shape.set(v)) for border in self.handleBorder: self.borderList['menu'].add_command( label=border, command=lambda v=border: self.borderType.set(v)) self.saveButton = Button(self, image=saveIcon, command=self.update_image) self.cancelButton = Button(self, image=closeIcon, command=self.cancel) self.update_preview() self.place_widgets() def update_image(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.image.morph_operations( self.operationChoice.get(), self.shape.get(), int(self.size.get()), self.handleBorder[self.borderType.get()]) self.master.image.copy = copy.deepcopy(self.master.image.cv2Image) self.master.manager.new_state(self.master.image.cv2Image) self.master.update_visible_image() self.master.update_child_windows() self.destroy() def update_preview(self, *args): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.image.morph_operations( self.operationChoice.get(), self.shape.get(), int(self.size.get()), self.handleBorder[self.borderType.get()]) self.master.update_visible_image() self.master.update_child_windows() def place_widgets(self): Label(self, text="Operacja:", font=("Helvetica", 15)).place(x=25, y=25) Label(self, text="Kształt i rozmiar:", font=("Helvetica", 15)).place(x=25, y=85) Label(self, text="Piksele skrajne:", font=("Helvetica", 15)).place(x=25, y=145) self.operationList.place(width=250, height=50, x=225, y=20) self.shapeList.place(width=100, height=50, x=225, y=80) self.sizeSpin.place(width=100, height=50, x=375, y=80) self.borderList.place(width=250, height=50, x=225, y=140) self.saveButton.place(width=40, height=40, x=200, y=255) self.cancelButton.place(width=40, height=40, x=260, y=255) def cancel(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.update_visible_image() self.master.image.fill_histogram() self.master.update_child_windows() self.destroy()
shut_label = Label(tab4, text="seconds.", font=cust_font1, bg="#1B1B19", fg="#ffffff") shut_label.place(x=430, y=310, width=100, height=30) Entrynum = Entry(tab4, textvariable=MobNum, font=cust_font) Entrynum.insert(0, "+91") Entrynum.place(x=350, y=70, width=300, height=30) Entrymsg = Text(tab4, font=cust_font) Entrymsg.place(x=350, y=120, width=300, height=120) hours = Spinbox(tab4, textvariable=hour, font=cust_font, from_=0, to=23) hours.place(x=350, y=260, width=70, height=30) mins = Spinbox(tab4, textvariable=minutes, font=cust_font, from_=0, to=59) mins.place(x=500, y=260, width=70, height=30) sleep = IntVar() def shut_timer(): sh_time = sleep.get() if sh_time == 0: try: pywhatkit.cancelShutdown() messagebox.showinfo("Shutdown Timer", "Shutdown timer is not fixed")
fill="#000") v = [] for f in vo: v += [vec4(f.X, f.Y, f.Z, f.M)] for f in faces: f.drawFace() reset = Button(root, text="Reset", command=reset) reset.place(x=windowX + 100, y=20) lx = Spinbox(root, from_=-1, to=1, increment=0.1, width=3) lx.place(x=windowX + 95, y=250) ly = Spinbox(root, from_=-1, to=1, increment=0.1, width=3) ly.place(x=windowX + 140, y=250) lz = Spinbox(root, from_=-1, to=1, increment=0.1, width=3) lz.place(x=windowX + 185, y=250) def setLight(): canvas.delete("all") canvas.create_rectangle(windowX, 0, windowX + 250, windowY, outline="#000", fill="#000")
class NewPosterizeWindow(Toplevel): def __init__(self, name, master=None): super().__init__(master=master) self.set_basic(name) self.master.image.posterize(2) self.bind('<Configure>', lambda e: self.place_buttons()) def set_basic(self, name): self.overrideredirect(1) self.set_geometry() self.set_spinbox() self.set_save_closeButtons() self.title("Redukcja poziomów szarości {}".format(name)) def set_geometry(self): self.height = 30 parentX = self.master.winfo_rootx() parentY = self.master.winfo_rooty() parentHeight = self.master.winfo_height() parentWidth = self.master.winfo_width() self.geometry( '%dx%d+%d+%d' % (parentWidth, self.height, parentX, parentY + parentHeight + 2)) def set_spinbox(self): self.spinBox = Spinbox(self, command=lambda: self.update_preview(), from_=2, to=255, width=3, font=("Helvetica", 15), justify=LEFT) self.spinBox.place(relx=0.375, relwidth=0.25) self.spinBox.delete(0, "end") self.spinBox.insert(0, 2) def set_save_closeButtons(self): self.saveButton = Button(self, image=saveIcon, command=self.update_image) self.cancelButton = Button(self, image=closeIcon, command=self.cancel) self.saveButton.place(relx=1 - ((2 * self.height) / self.master.winfo_width()), relheight=1) self.cancelButton.place(relx=1 - (self.height / self.master.winfo_width()), relheight=1) def place_buttons(self): self.saveButton.place(relx=1 - ((2 * self.height) / self.master.winfo_width()), relheight=1, width=self.height) self.cancelButton.place(relx=1 - (self.height / self.master.winfo_width()), relheight=1, width=self.height) def update_preview(self): self.master.image.posterize(int(self.spinBox.get())) self.master.update_visible_image() def update_image(self): self.master.update_visible_image() self.master.image.copy = copy.deepcopy(self.master.image.cv2Image) self.master.image.fill_histogram() self.master.update_child_windows() self.master.manager.new_state(self.master.image.cv2Image) self.master.posterizeWindow = None self.destroy() def cancel(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.update_visible_image() self.master.image.fill_histogram() self.master.update_child_windows() self.master.posterizeWindow = None self.destroy()
activeforeground='white') b1.place(x=150, y=185) #volume button def changevolume(): s = '' s = vspin.get() vspin.delete(0, END) if len(s) > 0: ss = int(s) engine.setProperty('volume', float(ss / 100)) vspin = Spinbox(root, bg='black', fg='turquoise2', width=7, from_=0, to=100) vspin.place(x=2, y=290) bv = Button(root, text='Set volume', command=changevolume, bg='black', fg='turquoise2', activeforeground='white', activebackground='black') bv.place(x=2, y=310) #rate button def changerate(): s = '' s = rspin.get() rspin.delete(0, END)
class NewMorphLineWindow(Toplevel): def __init__(self, master=None): super().__init__(master=master) self.set_basic() self.set_widgets() def set_basic(self): self.minsize(600, 400) self.maxsize(600, 400) self.title("Ekstrakcja linii") self.protocol("WM_DELETE_WINDOW", lambda: self.cancel()) self.handleBorder = { "Bez zmian (isolated)": 0, "Odbicie lustrzane (reflect)": 1, "Powielenie skrajnego piksela (replicate)": 2 } def set_widgets(self): self.horizontalSizeW = StringVar(self, value="3") self.horizontalSizeH = StringVar(self, value="1") self.verticalSizeW = StringVar(self, value="3") self.verticalSizeH = StringVar(self, value="1") self.borderType = StringVar(self, list(self.handleBorder.keys())[0]) self.cbVarHorizontal = IntVar(value=1) self.cbVarVertical = IntVar(value=1) self.cbVarOuter = IntVar(value=1) self.cbVarNegate = IntVar(value=0) self.sizeHorizontalWSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.horizontalSizeW, command=self.update_preview, state='readonly', increment=2) self.sizeHorizontalHSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.horizontalSizeH, command=self.update_preview, state='readonly', increment=2) self.sizeVerticalWSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.verticalSizeW, command=self.update_preview, state='readonly', increment=2) self.sizeVerticalHSpin = Spinbox(self, justify='center', font=("Helvetica", 15), from_=1, to=9999, textvariable=self.verticalSizeH, command=self.update_preview, state='readonly', increment=2) self.horizontalSizeW.trace("w", self.update_preview) self.horizontalSizeH.trace("w", self.update_preview) self.verticalSizeW.trace("w", self.update_preview) self.verticalSizeH.trace("w", self.update_preview) self.borderType.trace("w", self.update_preview) self.cbVarHorizontal.trace("w", self.update_preview) self.cbVarVertical.trace("w", self.update_preview) self.cbVarOuter.trace("w", self.update_preview) self.cbVarNegate.trace("w", self.update_preview) self.cbHorizontal = Checkbutton(self, width=0, variable=self.cbVarHorizontal) self.cbVertical = Checkbutton(self, width=0, variable=self.cbVarVertical) self.cbOuterOnly = Checkbutton(self, width=0, variable=self.cbVarOuter) self.cbNegateFirst = Checkbutton(self, width=0, variable=self.cbVarNegate) self.borderList = OptionMenu(self, self.borderType) for border in self.handleBorder: self.borderList['menu'].add_command( label=border, command=lambda v=border: self.borderType.set(v)) self.saveButton = Button(self, image=saveIcon, command=self.update_image) self.cancelButton = Button(self, image=closeIcon, command=self.cancel) self.update_preview() self.place_widgets() def update_image(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.image.morph_line(int(self.horizontalSizeW.get()), int(self.horizontalSizeH.get()), int(self.verticalSizeW.get()), int(self.verticalSizeH.get()), self.cbVarHorizontal.get(), self.cbVarVertical.get(), self.handleBorder[self.borderType.get()], self.cbVarOuter.get(), self.cbVarNegate.get()) self.master.image.copy = copy.deepcopy(self.master.image.cv2Image) self.master.manager.new_state(self.master.image.cv2Image) self.master.update_visible_image() self.master.update_child_windows() self.destroy() def update_preview(self, *args): self.sizeHorizontalWSpin.config(from_=int(self.horizontalSizeH.get()) + 2) self.sizeHorizontalHSpin.config(to=int(self.horizontalSizeW.get()) - 2) self.sizeVerticalWSpin.config(from_=int(self.verticalSizeH.get()) + 2) self.sizeVerticalHSpin.config(to=int(self.verticalSizeW.get()) - 2) self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.image.morph_line(int(self.horizontalSizeW.get()), int(self.horizontalSizeH.get()), int(self.verticalSizeW.get()), int(self.verticalSizeH.get()), self.cbVarHorizontal.get(), self.cbVarVertical.get(), self.handleBorder[self.borderType.get()], self.cbVarOuter.get(), self.cbVarNegate.get()) self.master.update_visible_image() self.master.update_child_windows() def place_widgets(self): Label(self, text="Poziome linie", font=("Helvetica", 15)).place(x=85, y=15) Label(self, text="Pionowe linie", font=("Helvetica", 15)).place(x=395, y=15) self.sizeHorizontalWSpin.place(width=100, height=50, x=150, y=60) self.sizeHorizontalHSpin.place(width=100, height=50, x=150, y=120) self.sizeVerticalWSpin.place(width=100, height=50, x=450, y=60) self.sizeVerticalHSpin.place(width=100, height=50, x=450, y=120) Label(self, text="Min. długość", font=("Helvetica", 15)).place(x=30, y=70) Label(self, text="Min. grubość", font=("Helvetica", 15)).place(x=30, y=130) Label(self, text="Min. długość", font=("Helvetica", 15)).place(x=330, y=70) Label(self, text="Min. grubość", font=("Helvetica", 15)).place(x=330, y=130) Label(self, text="Szukać poziomych?", font=("Helvetica", 9)).place(x=70, y=175) Label(self, text="Szukać pionowych?", font=("Helvetica", 9)).place(x=380, y=175) self.cbHorizontal.place(x=180, y=175) self.cbVertical.place(x=500, y=175) Label(self, text="Szukać tylko zewnętrznych?", font=("Helvetica", 11)).place(x=190, y=225) Label(self, text="Wstępnie zanegować?", font=("Helvetica", 11)).place(x=190, y=255) self.cbOuterOnly.place(x=390, y=225) self.cbNegateFirst.place(x=390, y=255) self.borderList.place(width=200, height=50, x=200, y=300) self.saveButton.place(width=40, height=40, x=220, y=355) self.cancelButton.place(width=40, height=40, x=340, y=355) def cancel(self): self.master.image.cv2Image = copy.deepcopy(self.master.image.copy) self.master.update_visible_image() self.master.image.fill_histogram() self.master.update_child_windows() self.destroy()
(h / image.height)), int(image.height * (h / image.height))), Image.ANTIALIAS) img = ImageTk.PhotoImage(image) mriezkuj(None) load = Button(root, text="Load", command=loading) load.place(x=5, y=5) xo = StringVar() xo.set('') xbut = Spinbox(root, from_=0, to=1000, increment=1, textvariable=xo, width=3) xbut.place(x=5, y=35) yo = StringVar() yo.set('') ybut = Spinbox(root, from_=0, to=1000, increment=1, textvariable=yo, width=3) ybut.place(x=5, y=60) def mriezkuj(*args): global img canvas.delete("all") for ix in range(1, 100): if ix % 10 == 0:
class Frame: root = Tk() global useUppercase, useNumbers, useSymbols, useUNICODE useUppercase = True useNumbers = True useSymbols = True useUNICODE = False def __init__(self): self.root.protocol('WM_DELETE_WINDOW', self.exitProgram) self.root.wm_title("Random Password Generator") self.root.resizable(width=False, height=False) self.root.geometry("535x125") self.btn_generate = Button(self.root, text='Generate', width=10, font=font.Font(size=15), command=self.generatePassword) self.btn_generate.grid(row=0, column=0, rowspan=2, sticky=N + S + E + W) self.lbl_progress = Label(self.root, text='Ready', height=2, width=23, background='black', foreground='yellow', font=font.Font(size=15)) self.lbl_progress.grid(row=0, column=1, sticky=N + S + E + W) self.txt_password = Text(self.root, height=3, width=23, font=font.Font(size=15)) self.txt_password.grid(row=1, column=1, columnspan=2, sticky=N + S + E + W) self.lbl_strength = Label(self.root, height=2, font=font.Font(size=13), text="Strength") self.lbl_strength.place(x=395, y=0) self.spn_strength = Spinbox(self.root, width=5, font=font.Font(size=13), values=(20, 32, 64, 128, 256, 2048)) self.spn_strength.place(x=465, y=9) self.chb_uppercase = Checkbutton(self.root, text="Use Uppercase", width=15, command=self.switchUppercase) self.chb_uppercase.place(x=395, y=35) if useUppercase: self.chb_uppercase.select() self.chb_number = Checkbutton(self.root, text="Use Numbers ", width=15, command=self.switchNumbers) self.chb_number.place(x=395, y=56) if useNumbers: self.chb_number.select() self.chb_symbol = Checkbutton(self.root, text="Use Symbols ", width=15, command=self.switchSymbols) self.chb_symbol.place(x=395, y=77) if useSymbols: self.chb_symbol.select() self.chb_symbol = Checkbutton(self.root, text="Use UNICODE ", width=15, command=self.switchUNICODE) self.chb_symbol.place(x=395, y=98) def generatePassword(self): self.txt_password.delete(1.0, END) chars = string.ascii_lowercase if useUppercase: chars = chars + string.ascii_uppercase if useNumbers: chars = chars + string.digits if useSymbols: chars = chars + string.punctuation if useUNICODE: chars = chars + get_random_unicodes(100) for _ in range(int(self.spn_strength.get())): self.txt_password.insert(INSERT, random.choice(chars)) self.txt_password.tag_add("start", "1.0", END) self.txt_password.tag_config("start", foreground="#228B22", justify="center") self.root.clipboard_clear() self.root.clipboard_append(self.txt_password.get("1.0", END)) self.lbl_progress["text"] = "Copied to clipboard" now = datetime.now() print("Password generated at " + now.strftime(" %d %B %Y - %H:%M:%S:%f")) print("================================\n") print(self.txt_password.get("1.0", END)) print("================================\n\n") self.lbl_progress["text"] = "Generated at [" + now.strftime("%H:%M:%S:%f")[:12] +"]\n"+ "Copied to clipboard" def switchUppercase(self): global useUppercase if useUppercase: useUppercase = False else: useUppercase = True def switchNumbers(self): global useNumbers if useNumbers: useNumbers = False else: useNumbers = True def switchSymbols(self): global useSymbols if useSymbols: useSymbols = False else: useSymbols = True def switchUNICODE(self): global useUNICODE if useUNICODE: self.lbl_progress["text"] = "Ready" useUNICODE = False else: self.lbl_progress["text"] = "Ready (Unicodes are risky)" useUNICODE = True def exitProgram(self): self.root.destroy() def run(self): self.root.mainloop()
class MyGUI(): def __init__(self, root, frame): self.root = root self.root.title("ClockPy") #self.root.resizable(0,0) self.root.maxsize(width=385, height=550) self.root.minsize(width=385, height=550) self.root.iconbitmap("./icons/clock.ico") self.frame = frame # ----------- Function Refresh Clock ----------- def tick(): time_string = time.strftime("%I:%M") time_string2 = time.strftime(":%S") time_day = time.strftime("%a, %d %B") time_m = time.strftime("%p") self.clock.config(text=time_string) self.clock_s.config(text=time_string2) self.clock_d.config(text=time_day) self.clock_m.config(text=time_m) self.clock.after(200, tick) # ----------- Function DataBASE ----------- #Load database db_name = 'database.db' # Operation database query = 'SELECT * FROM color' query_alarm = 'SELECT * FROM alarm' query2 = 'UPDATE color SET hexa=?' query_alarm2 = 'UPDATE alarm SET state=?' query_alarm3 = 'UPDATE alarm SET hours=?, minutes=?, meridiam=?' # Database Consult Update def db_query(query, parameters=(), alarm=None): with sqlite3.connect(db_name) as conn: cursor = conn.cursor() result = cursor.execute(query, parameters) conn.commit() if (parameters == ()): if (alarm == None): for row in result: return row[1] else: for row in result: return row[1:5] hexa_c = db_query(query) self.frame.config(width="385", height="550", bg=hexa_c) # ----------- Function Check Status Alarm ----------- def check_alarm(): self.data_alarm_check = db_query(query_alarm, alarm="Y") time_check_h = time.strftime("%I") time_check_m = time.strftime("%M") time_check_mr = time.strftime("%p") time_check_s = time.strftime("%S") if (self.data_alarm_check[0] < 10): hours_check = "0" + str(self.data_alarm_check[0]) else: hours_check = str(self.data_alarm_check[0]) if (self.data_alarm_check[1] < 10): minutes_check = "0" + str(self.data_alarm_check[1]) else: minutes_check = str(self.data_alarm_check[1]) # Check Alarm and playsound if (self.data_alarm_check[3] == "on"): if (time_check_s == "00"): if (time_check_h == hours_check): if (time_check_m == minutes_check): if (time_check_mr == self.data_alarm_check[2]): playsound("./sound/alarm_sound.mp3") self.root.deiconify() self.root.focus_set() self.root.after(1000, check_alarm) # ----------- Windows Clock Alarm ----------- def windows(): hexa_c = db_query(query) self.main_wn = Toplevel(self.root, takefocus=True, bg=hexa_c) self.main_wn.focus_force() self.main_wn.title("ClockPy Alarm") self.main_wn.geometry("320x158") self.main_wn.resizable(0, 0) self.main_wn.iconbitmap("./icons/clock.ico") self.main_wn.grab_set() self.date_alarm = db_query(query_alarm, alarm="Y") self.img_on = PhotoImage(file="./icons/on.png") self.img_off = PhotoImage(file="./icons/off.png") self.img_menu = PhotoImage(file="./icons/menu.png") self.switch = self.date_alarm[3] def check_state_alarm(): if (self.date_alarm[0] < 10): self.lb_hours.config(text="0" + str(self.date_alarm[0])) else: self.lb_hours.config(text=self.date_alarm[0]) if (self.date_alarm[1] < 10): self.lb_minutes.config(text=":0" + str(self.date_alarm[1])) else: self.lb_minutes.config(text=":" + str(self.date_alarm[1])) self.lb_meridiam.config(text=self.date_alarm[2]) if (self.switch == "on"): self.bt_switch.config(image=self.img_on) else: self.bt_switch.config(image=self.img_off) def change_switch(): if (self.switch == "off"): self.bt_switch.config(image=self.img_on) self.switch = "on" db_query(query_alarm2, ("on", )) else: self.bt_switch.config(image=self.img_off) self.switch = "off" db_query(query_alarm2, ("off", )) self.space_alarm = Frame(self.main_wn, width=300, height=100, bg="white") self.space_alarm.place(x=10, y=20) self.lb_hours = Label(self.space_alarm, font=("Roboto Light", 54), bg="white") self.lb_hours.place(x=10, y=0) self.lb_minutes = Label(self.space_alarm, font=("Roboto Light", 54), bg="white") self.lb_minutes.place(x=90, y=0) self.lb_meridiam = Label(self.space_alarm, font=("Roboto Light", 14), bg="white") self.lb_meridiam.place(x=190, y=15) self.bt_switch = Button(self.space_alarm, activebackground="white", command=lambda: change_switch()) self.bt_switch.config(bg="white", bd=0, highlightthickness=0, relief='flat') self.bt_switch.place(x=245, y=10) self.bt_config_alarm = Button(self.space_alarm, image=self.img_menu, activebackground="white") self.bt_config_alarm.config(bg="white", bd=0, highlightthickness=0, relief='flat', command=lambda: setting_alarm()) self.bt_config_alarm.place(x=250, y=55) check_state_alarm() # ----------- Windows Settings Alarm ----------- def setting_alarm(): self.settings_wn = Toplevel(self.main_wn, bg=hexa_c, takefocus=True) self.settings_wn.focus_force() self.settings_wn.geometry("470x165") self.settings_wn.iconbitmap("./icons/clock.ico") self.settings_wn.grab_set() self.settings_wn.resizable(0, 0) self.settings_wn.title("ClockPy Alarm") self.space_alarm2 = Frame(self.settings_wn, width=450, height=100, bg="white") self.space_alarm2.place(x=10, y=20) self.select_hours = Spinbox(self.space_alarm2, from_=1, to=12, width=2, font=("Roboto Light", 50), bd=0, relief='flat', activebackground="white", textvariable=2, state="readonly") self.select_hours.config(buttondownrelief="flat", readonlybackground="white") self.select_hours.place(x=10, y=5) self.select_minutes = Spinbox(self.space_alarm2, from_=00, to=59, format="%02.0f", width=2, font=("Roboto Light", 50), bd=0, relief='flat', activebackground="white") self.select_minutes.config(buttondownrelief="flat", readonlybackground="white", state="readonly") self.select_minutes.place(x=150, y=5) self.select_meridiam = Spinbox(self.space_alarm2, values=("AM", "PM"), width=3, font=("Roboto Light", 50), bd=0, relief='flat', activebackground="white") self.select_meridiam.config(buttondownrelief="flat", readonlybackground="white", state="readonly") self.select_meridiam.place(x=285, y=5) self.bt_save_sttg = Button(self.settings_wn, text="Save", font=("Roboto Light", 12), bd=0, relief="flat", bg="white", command=lambda: save_sttg()) self.bt_save_sttg.place(x=415, y=125) def save_sttg(): h = self.select_hours.get() m = self.select_minutes.get() md = self.select_meridiam.get() db_query(query_alarm3, ( h, m, md, )) self.date_alarm = db_query(query_alarm, alarm="Y") check_state_alarm() self.settings_wn.destroy() # ----------- Function Change Color ----------- def change_color(): rgb, hexa = askcolor() self.frame.config(bg=hexa) self.clock.config(bg=hexa) self.clock_s.config(bg=hexa) self.clock_m.config(bg=hexa) self.clock_d.config(bg=hexa) self.button1.config(bg=hexa, activebackground=hexa) self.button2.config(bg=hexa, activebackground=hexa) #self.lb.config(bg=hexa) # Update Value color database if (hexa != None): db_query(query2, (hexa, )) # ----------- Clock Configure ----------- # Clock Hours Minutes self.clock = Label(self.frame, font=("Roboto Light", 64), bg=hexa_c, foreground="white") self.clock.place(x=65, y=150) # Clock Seconds self.clock_s = Label(self.frame, font=("Roboto Light", 22), bg=hexa_c, foreground="white") self.clock_s.place(x=272, y=200) # Clock Meridiem self.clock_m = Label(self.frame, font=("Roboto Light", 22), bg=hexa_c, foreground="white") self.clock_m.place(x=272, y=165) # Day Month self.clock_d = Label(self.frame, font=("Roboto Light", 14), bg=hexa_c, foreground="white") self.clock_d.place(x=80, y=240) tick() check_alarm() # ----------- Button Change Color ----------- self.img = PhotoImage(file="./icons/color.png") self.img2 = PhotoImage(file="./icons/alarm.png") # Button Pallete Colors self.button1 = Button(self.frame, image=self.img, activebackground=hexa_c, command=lambda: change_color()) self.button1.config(bg=hexa_c, bd=0, highlightthickness=0, relief='flat') self.button1.place(x=5, y=505) # Button Settings self.button2 = Button(self.frame, image=self.img2, activebackground=hexa_c, command=lambda: windows()) self.button2.config(bg=hexa_c, bd=0, highlightthickness=0, relief='flat') self.button2.place(x=340, y=505) self.frame.pack()
#spinbox def clicked( ): #quando a spinbox mudar de valor o texto que identifica o intervalo de dígitos de entrada muda lblvalue.configure(text='Valor: (0 - ' + digitos[int(base1.get()) - 1] + ')') base1 = Spinbox(window, from_=2, to=62, width=5, bg=bg_box, state='readonly', command=clicked) base1.place(relx=0.4, rely=0.2, anchor=CENTER) base2 = Spinbox(window, from_=2, to=62, width=5, bg=bg_box, state='readonly') base2.place(relx=0.6, rely=0.2, anchor=CENTER) #entry value = Entry(window, width=110, bg=bg_box, justify='center') value.place(relx=0.5, rely=0.5, anchor=CENTER) #buttons def convert( ): #quando o botão de conversão é clicado verifica-se erros de conversão e de limite de dígitos if Converte(value.get(), int(base1.get()), int(base2.get())) == 'Erro': return messagebox.showerror('Erro 1', 'Valor inválido')
bd=0) outline_label1.place(x=370, y=2) outline_label2 = Label(tool_canvas, text="outline size:", bg="#ffb375", relief=RIDGE, bd=0) outline_label2.place(x=370, y=23) outline_scale = Spinbox(tool_canvas, values=[0, 1, 2, 3, 4, 5, 6], width=1, state='readonly', command=_outline_scale) outline_scale.place(x=460, y=23) pallete_outline = Canvas(tool_canvas, bg=outline_colour, width=10, height=10) pallete_outline.bind('<Button-1>', colour_outline) pallete_outline.place(x=470, y=7) pattern_label = Label(tool_canvas, text="colour pattern:", bg="#ffb375", relief=RIDGE, bd=0) pattern_label.place(x=520, y=2) pattern_combobox = ttk.Combobox(tool_canvas, width=15, state='readonly') pattern_combobox.place(x=500, y=23) pattern_combobox.set('snowflakes')
class UI(): def __init__(self, sysTrayIcon=None, vals=None): global RUNNING global ui RUNNING[0] = True ui.append(self) self.tk = Tk() self.vals = vals self.titleFont = Font(root=self.tk, family="Helvetica", size=15) self.labelFont = Font(root=self.tk, family="Helvetica", size=11) self.entryFont = Font(root=self.tk, family="Courier", size=10) self.stringVars = {} self.buildMainWindow() self.tk.focus_force() self.tk.protocol("WM_DELETE_WINDOW", self.hideToTray) try: getNCommit('mvfki', 'gitUpstreamTracker', 'master') except URLError: self.check_start_btn['state'] = DISABLED self.repoInfo_btn['state'] = DISABLED self.tk.geometry('400x550') self._setLabel( self.tk, 'Internet connection error\nPlease check and restart.', x=290, y=540) self.tk.mainloop() # Appearance building vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv def buildMainWindow(self): self.tk.title("gitUpstreamTracker") self.tk.geometry('400x510') centerWindow(self.tk) self.tk["bg"] = COLORs['bg'] self.tk.attributes("-alpha", 0.95) self.addFrame_repoInfo() self.addFrame_senderInfo() self.addFrame_receiverInfo() self.addOperationPanel() def addFrame_repoInfo(self): self.repoInfo_frame = Frame(self.tk, bg=COLORs['bg'], width=360, height=180, relief='groove', highlightbackground=COLORs['frmLine'], highlightthickness=1) self._setTitleLabel(self.repoInfo_frame, "GitHub Repository to Track") # Owner entry self._setLabel(self.repoInfo_frame, "Owner", 55) self.repoInfo_owner_entry = self._setEntry(self.repoInfo_frame, 'owner', 55, self.vals['owner'], setFocus=True) # Repo entry self._setLabel(self.repoInfo_frame, "Repository", 85) self.repoInfo_repo_entry = self._setEntry(self.repoInfo_frame, 'repo', 85, self.vals['repo']) # Branch entry self._setLabel(self.repoInfo_frame, "Branch", 115) self.repoInfo_branch_entry = self._setEntry(self.repoInfo_frame, 'branch', 115, self.vals['branch']) # Button self.repoInfo_btn = Button(self.repoInfo_frame, relief=FLAT, text="Check Commit Number", command=self.openCheckCommitWindow, bg=COLORs['frmLine'], fg=COLORs['txt'], width=18, height=1, font=self.labelFont, activebackground=COLORs['frmLine'], activeforeground=COLORs['txt']) batchBindEvent([ self.repoInfo_frame, self.repoInfo_owner_entry, self.repoInfo_repo_entry, self.repoInfo_branch_entry, self.repoInfo_btn ], effect=bindPressButtonEffect, target=self.repoInfo_btn, root=self.tk) self.repoInfo_btn.place(anchor=N, x=180, y=130) self.repoInfo_frame.pack(pady=20) def addFrame_senderInfo(self): self.senderInfo_frame = Frame(self.tk, bg=COLORs['bg'], width=360, height=75, relief='groove', highlightbackground=COLORs['frmLine'], highlightthickness=1) self.senderInfo_frame.pack(pady=10) self._setTitleLabel(self.senderInfo_frame, "Sender Gmail") # Sender entry self._setLabel(self.senderInfo_frame, "Address", 55) self.senderInfo_entry = self._setEntry(self.senderInfo_frame, 'sender', 55, self.vals['sender']) def addFrame_receiverInfo(self): self.receiverInfo_frame = Frame(self.tk, bg=COLORs['bg'], width=360, height=75, relief='groove', highlightbackground=COLORs['frmLine'], highlightthickness=1) self.receiverInfo_frame.pack(pady=10) self._setTitleLabel(self.receiverInfo_frame, "Receiver Email") self._setLabel(self.receiverInfo_frame, 'Address', 55) self.receiverInfo_entry = self._setEntry(self.receiverInfo_frame, 'receiver', 55, self.vals['receiver']) def addOperationPanel(self): self.OP_frame = Frame(self.tk, bg=COLORs['bg'], width=360, height=35) self.OP_frame.pack() self._setLabel(self.OP_frame, 'Check Every', 25, 90) self.stringVars['hour'] = IntVar() self.stringVars['hour'].set(self.vals['hour']) self.freq_hour_spin = Spinbox(self.OP_frame, from_=0, to=24, textvariable=self.stringVars['hour'], width=2, bg=COLORs['bg'], fg=COLORs['txt'], disabledbackground=COLORs['bg'], disabledforeground=COLORs['dis']) self.freq_hour_spin.place(anchor=SE, y=23, x=120) self._setLabel(self.OP_frame, 'h', 25, 135) self.stringVars['min'] = IntVar() self.stringVars['min'].set(self.vals['min']) self.freq_min_spin = Spinbox(self.OP_frame, from_=1, to=59, textvariable=self.stringVars['min'], width=2, bg=COLORs['bg'], fg=COLORs['txt'], disabledbackground=COLORs['bg'], disabledforeground=COLORs['dis']) self.freq_min_spin.place(anchor=SE, y=23, x=165) self._setLabel(self.OP_frame, 'min', 25, 195) self.check_start_btn = Button(self.OP_frame, relief=FLAT, text='Start', bg=COLORs['frmLine'], fg=COLORs['txt'], width=6, height=1, font=self.labelFont, command=self.startLoop, activebackground=COLORs['frmLine'], activeforeground=COLORs['txt']) batchBindEvent( [self.freq_min_spin, self.freq_hour_spin, self.check_start_btn], effect=bindPressButtonEffect, target=self.check_start_btn, root=self.tk) self.check_start_btn.place(anchor=SE, y=30, x=270) self.check_stop_btn = Button(self.OP_frame, relief=FLAT, text='Stop', bg=COLORs['frmLine'], fg=COLORs['txt'], width=6, height=1, font=self.labelFont, state=DISABLED, activebackground=COLORs['frmLine'], activeforeground=COLORs['txt'], command=self.stopLoop) self.check_stop_btn.place(anchor=SE, y=30, x=350) global PROC if len(PROC) == 1 and PROC[0].is_alive(): self.repoInfo_owner_entry['state'] = DISABLED self.repoInfo_repo_entry['state'] = DISABLED self.repoInfo_branch_entry['state'] = DISABLED self.senderInfo_entry['state'] = DISABLED self.receiverInfo_entry['state'] = DISABLED self.check_start_btn['state'] = DISABLED self.freq_min_spin['state'] = DISABLED self.freq_hour_spin['state'] = DISABLED self.check_stop_btn['state'] = NORMAL elif len(PROC) == 0 and self.entryAllEntered(): self.check_start_btn['state'] = NORMAL self.check_stop_btn['state'] = DISABLED elif len(PROC) == 0 and not self.entryAllEntered(): self.check_start_btn['state'] = DISABLED self.check_stop_btn['state'] = DISABLED else: logger("error", "Process running abnormally when building the window") logger( "error", f"len(PROC)=={len(PROC)}, PROC[0].is_alive()=={str(PROC[0].is_alive())}" ) self.window_hide = Button(self.tk, relief=FLAT, text="Hide to Tray", command=self.hideToTray, bg=COLORs['frmLine'], fg=COLORs['txt'], width=12, height=1, font=self.labelFont, activebackground=COLORs['frmLine'], activeforeground=COLORs['txt']) self.window_hide.place(anchor=N, x=120, y=460) self.window_quit = Button(self.tk, relief=FLAT, text="Quit", command=SYSTRAY[0].shutdown, bg=COLORs['frmLine'], fg=COLORs['txt'], width=12, height=1, font=self.labelFont, activebackground=COLORs['frmLine'], activeforeground=COLORs['txt']) self.window_quit.place(anchor=N, x=280, y=460) # Operating Functions vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv def openCheckCommitWindow(self): owner, repo, branch = (self.stringVars['owner'].get().strip(), self.stringVars['repo'].get().strip(), self.stringVars['branch'].get().strip()) if owner and repo and branch: directCheckUI(owner, repo, branch) def hideToTray(self): global VALs global RUNNING global ui VALs['owner'] = self.stringVars['owner'].get().strip() VALs['repo'] = self.stringVars['repo'].get().strip() VALs['branch'] = self.stringVars['branch'].get().strip() VALs['receiver'] = self.stringVars['receiver'].get().strip() VALs['sender'] = self.stringVars['sender'].get().strip() VALs['hour'] = self.stringVars['hour'].get() VALs['min'] = self.stringVars['min'].get() RUNNING[0] = False self.tk.destroy() del ui[0] def startLoop(self): global PROC logger("info", "Check button pressed") if self.entryAllEntered(): self.check_start_btn['state'] = DISABLED self.repoInfo_owner_entry['state'] = DISABLED self.repoInfo_repo_entry['state'] = DISABLED self.repoInfo_branch_entry['state'] = DISABLED self.senderInfo_entry['state'] = DISABLED self.receiverInfo_entry['state'] = DISABLED self.freq_min_spin['state'] = DISABLED self.freq_hour_spin['state'] = DISABLED intervalSec = self.stringVars['hour'].get() * 60 * 60 + \ self.stringVars['min'].get() * 60 try: getNCommit(self.stringVars['owner'].get().strip(), self.stringVars['repo'].get().strip(), self.stringVars['branch'].get().strip()) logger("info", "Abled to run the process") PROC.append( Process(target=periodicalCatcher, args=(self.stringVars['owner'].get().strip(), self.stringVars['repo'].get().strip(), self.stringVars['sender'].get().strip(), self.stringVars['receiver'].get().strip(), self.stringVars['branch'].get().strip(), intervalSec, LOGS))) PROC[0].start() VALs['owner'] = self.stringVars['owner'].get().strip() VALs['repo'] = self.stringVars['repo'].get().strip() VALs['branch'] = self.stringVars['branch'].get().strip() VALs['receiver'] = self.stringVars['receiver'].get().strip() VALs['sender'] = self.stringVars['sender'].get().strip() VALs['hour'] = self.stringVars['hour'].get() VALs['min'] = self.stringVars['min'].get() sleep(1) self.check_stop_btn['state'] = NORMAL except Exception as e: logger("error", 'Error encountered: ' + str(e)) self.check_stop_btn['state'] = DISABLED self.check_start_btn['state'] = NORMAL self.repoInfo_owner_entry['state'] = NORMAL self.repoInfo_repo_entry['state'] = NORMAL self.repoInfo_branch_entry['state'] = NORMAL self.senderInfo_entry['state'] = NORMAL self.receiverInfo_entry['state'] = NORMAL self.freq_min_spin['state'] = NORMAL self.freq_hour_spin['state'] = NORMAL def stopLoop(self): global PROC self.check_stop_btn['state'] = DISABLED if len(PROC) == 1 and PROC[0].is_alive(): logger("info", "Stopping process normally") PROC[0].terminate() PROC[0].join() del PROC[0] elif len(PROC) == 1 and not PROC[0].is_alive(): logger("warning", "Process is not alive. Stop anyway.") PROC[0].terminate() PROC[0].join() del PROC[0] elif len(PROC) > 1: logger("error", "Unknown number of process running. Stop them all.") for p in PROC: p.terminate() p.join() for i in range(len(PROC)): del PROC[0] sleep(1) self.check_start_btn['state'] = NORMAL self.repoInfo_owner_entry['state'] = NORMAL self.repoInfo_repo_entry['state'] = NORMAL self.repoInfo_branch_entry['state'] = NORMAL self.senderInfo_entry['state'] = NORMAL self.receiverInfo_entry['state'] = NORMAL logger("info", "Successfully stopped") def entryAllEntered(self): allArgs = [ self.stringVars['owner'].get().strip(), self.stringVars['repo'].get().strip(), self.stringVars['sender'].get().strip(), self.stringVars['receiver'].get().strip(), self.stringVars['branch'].get().strip() ] if '' not in allArgs and None not in allArgs: if not GMAIL_REGEX.match(allArgs[2]) or \ not EMAIL_REGEX.match(allArgs[3]): return False else: return True else: return False def entryEntered(self, *args): if self.entryAllEntered(): self.check_start_btn['state'] = NORMAL else: self.check_start_btn['state'] = DISABLED # Theme setting for all kinds of widgets vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv def _setTitleLabel(self, master, text): tl = Label(master, padx=5, text=text, bg=COLORs['bg'], font=self.titleFont, fg=COLORs['txt']) tl.place(anchor=N, x=180, y=-6) def _setLabel(self, master, text, y, x=110): l = Label(master, text=text, bg=COLORs['bg'], font=self.labelFont, fg=COLORs['txt']) l.place(anchor=SE, x=x, y=y) def _setEntry(self, master, varName, y, value=None, setFocus=False): self.stringVars[varName] = StringVar() if value != None: self.stringVars[varName].set(value) self.stringVars[varName].trace("w", self.entryEntered) e = Entry(master, font=self.entryFont, bg=COLORs['bg'], bd=1, fg=COLORs['txt'], textvariable=self.stringVars[varName], highlightcolor=COLORs['frmLine'], selectbackground=COLORs['selBg'], insertbackground=COLORs['txt'], disabledbackground=COLORs['bg'], disabledforeground=COLORs['dis']) e.place(anchor=SW, x=120, y=y, height=22, width=180) if setFocus: e.focus() return e
def init_widgets_show(self): # 登录后的页面显示 self.clear_widgets() self.master.geometry("500x500") Label(text=self.chrome.login_name, font=('Arial', 14)).place(x=20, y=20) print('登录成功') order_message = Button(self.master, text='订单信息爬取', command=self.get_sell_shops) order_message.place(x=20, y=60) detail_image = Button(self.master, text='图片详情爬取', command=self.threed_detail_items) detail_image.place(x=20, y=100) self.delay_time = StringVar() sb = Spinbox(self.master, from_=3, to=10, increment=1, textvariable=self.delay_time, command=self.delay_time.get(), width=5) sb.place(x=120, y=105) quit_account = Button(self.master, text='导出所有图片', command=self.export_image) quit_account.place(x=20, y=140) quit_account = Button(self.master, text='退出账号', command=self.quit_account) quit_account.place(x=280, y=20) # quit_account = Button(self.master, text='暂停', command=self.chrome.time_out) # quit_account.place(x=120, y=140) # # quit_account = Button(self.master, text='开始', command=self.chrome.run_out) # quit_account.place(x=170, y=140) self.amount_page = Label(text='', font=('Arial', 14)) self.amount_page.place(x=200, y=60) self.amount_item = Label(text='', font=('Arial', 14)) self.amount_page.place(x=200, y=100) self.amount_img = Label(text='', font=('Arial', 14)) self.amount_img.place(x=200, y=100) self.var_amount_page = StringVar() self.amount_page = Label(textvariable=self.var_amount_page, font=('Arial', 14)) self.amount_page.place(x=200, y=60) self.var_amount_item = StringVar() self.amount_item = Label(textvariable=self.var_amount_item, font=('Arial', 14)) self.amount_item.place(x=200, y=100) self.var_amount_img = StringVar() self.amount_img = Label(textvariable=self.var_amount_img, font=('Arial', 14)) self.amount_img.place(x=200, y=140)
class Settings_for_frame(Frame): def __init__(self, master, board, tag, board_dims): super().__init__(master, bg="#435661") self.board = board self.board_width, self.board_height = board_dims self.tag = tag self.background = "white" self.record = {} self.index = 0 self.spin_relx = None self.spin_rely = None self.spin_relw = None self.spin_relh = None self.label_arguments = None self.entry_arguments = None self.listbox = None self.entry_name = None self.set_layout() self.set_bindings() self.set_listbox() self.set_spinboxes() def set_layout(self): # self-explanatory Label(self, background='#435661', text='relx:', foreground='#defffc') \ .place(relx=0.145, rely=0.0125, relwidth=0.1625, relheight=0.025, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='rely:') \ .place(relx=0.6845, rely=0.0135, relwidth=0.155, relheight=0.0225, anchor='nw') Label(self, background='#435661', text='relwidth:', foreground='#defffc') \ .place(relx=0.044, rely=0.089, relwidth=0.37, relheight=0.02125, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='relheight:') \ .place(relx=0.667, rely=0.0875, relwidth=0.195, relheight=0.02375, anchor='nw') self.spin_relx = Spinbox(self, readonlybackground='#defffc', highlightthickness=0, foreground='#435661', from_=0, command=self.mod, to_=1, increment=0.001, justify='center') self.spin_relx.place(relx=0.085, rely=0.0425, relwidth=0.295, relheight=0.03375, anchor='nw') self.spin_rely = Spinbox(self, readonlybackground='#defffc', foreground='#435661', justify='center', highlightthickness=0, command=self.mod, from_=0, to_=1, increment=0.001) self.spin_rely.place(relx=0.6135, rely=0.0425, relwidth=0.3005, relheight=0.03375, anchor='nw') self.spin_relw = Spinbox(self, readonlybackground='#defffc', foreground='#435661', justify='center', highlightthickness=0, command=self.mod, from_=0, to_=1, increment=0.001) self.spin_relw.place(relx=0.084, rely=0.1175, relwidth=0.295, relheight=0.035, anchor='nw') self.spin_relh = Spinbox(self, readonlybackground='#defffc', foreground='#435661', justify='center', highlightthickness=0, command=self.mod, from_=0, to_=1, increment=0.001) self.spin_relh.place(relx=0.6115, rely=0.1177, relwidth=0.304, relheight=0.035, anchor='nw') self.label_arguments = Label(self, background='#557282', foreground='#defffc') self.label_arguments.place(relx=0.086, rely=0.1832, relwidth=0.8305, relheight=0.06125, anchor='nw') self.entry_arguments = Entry(self, background='#defffc', foreground='#435661', justify='center') self.entry_arguments.place(relx=0.22, rely=0.2625, relwidth=0.545, relheight=0.04375, anchor='nw') self.listbox = Listbox(self, background='#557282', foreground='#defffc', borderwidth=0) self.listbox.place(relx=0.085, rely=0.3275, relwidth=0.83, relheight=0.4062, anchor='nw') myButton(self, command=lambda *a: self.set_value(), text='OK') \ .place(relx=0.8245, rely=0.2672, relwidth=0.13, relheight=0.0355, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='Name:', anchor='w') \ .place(relx=0.083, rely=0.766, relwidth=0.1205, relheight=0.035, anchor='nw') self.entry_name = Entry(self, background='#defffc', foreground='#435661', justify='center') self.entry_name.place(relx=0.245, rely=0.7662, relwidth=0.5225, relheight=0.035, anchor='nw') myButton(self, command=lambda *a: self.confirm(), text='CONFIRM') \ .place(relx=0.201, rely=0.8575, relwidth=0.6155, relheight=0.0825, anchor='nw') def set_bindings(self): # self-explanatory self.entry_arguments.bind("<Return>", lambda *a: self.set_value()) self.listbox.bind("<ButtonRelease-1>", lambda *a: self.listbox_clicked()) def set_spinboxes(self): # self-explanatory self.spin_relx.delete(0, "end") self.spin_rely.delete(0, "end") self.spin_relw.delete(0, "end") self.spin_relh.delete(0, "end") self.spin_relx.insert("end", self.master.fake_frame_place_info["relx"]) self.spin_rely.insert("end", self.master.fake_frame_place_info["rely"]) self.spin_relw.insert("end", self.master.fake_frame_place_info["relwidth"]) self.spin_relh.insert("end", self.master.fake_frame_place_info["relheight"]) self.spin_relx.configure(state="readonly") self.spin_rely.configure(state="readonly") self.spin_relw.configure(state="readonly") self.spin_relh.configure(state="readonly") def mod(self): relx = float(self.spin_relx.get()) rely = float(self.spin_rely.get()) relw = float(self.spin_relw.get()) relh = float(self.spin_relh.get()) x, y = int(relx * self.board_width), int(rely * self.board_height) width, height = int(relw * self.board_width), int(relh * self.board_height) self.board.delete(self.tag) self.board.create_rectangle(x, y, x + width, y + height, width=0, fill=self.background, tag=self.tag) def set_listbox(self): self.listbox.insert("end", "background") self.record["background"] = self.master.fake_frame_background def listbox_clicked(self): # Changes entry_arguments's text and label_arguments's text, sets focus on entry_name self.index = self.listbox.curselection()[0] parameter = list(self.record.keys())[self.index] value = self.record[parameter] self.entry_arguments.delete(0, "end") self.entry_arguments.insert("end", value) self.label_arguments.configure(text=f"{parameter} = {value}") self.entry_arguments.focus_set() def set_value(self): parameter = list(self.record.keys())[self.index] value = self.entry_arguments.get() try: evaluated_value = eval(value) self.record[parameter] = evaluated_value except: evaluated_value = value self.record[parameter] = f"{evaluated_value}" self.background = evaluated_value self.mod() self.label_arguments.configure(text=f"{parameter} = {value}") def fake_place_info(self): relx = float(self.spin_relx.get()) rely = float(self.spin_rely.get()) relw = float(self.spin_relw.get()) relh = float(self.spin_relh.get()) return { "relx": relx, "rely": rely, "relwidth": relw, "relheight": relh, "anchor": "nw" } def confirm(self): name = self.entry_name.get().replace(" ", "") if name and name not in self.master.record_of_names: self.master.record_of_names[name] = Frame(self.board) widget_cls = "Frame" self.master.writer.define_widget(name, widget_cls, self.fake_place_info()) self.master.writer.begin_configure(name) for key, value in self.record.items(): if value: self.master.writer.write_configure(name, key, f"'{value}'") self.master.writer.end_configure(name) self.destroy()
class MainWindow: def __init__(self) -> None: self.Root = Tk() self.App = Frame(self.Root, padding=(5, 2)) self.UpdatesFrame = LabelFrame(self.App, text='Обновление', borderwidth=2, relief='sunken', padding=(5, 2)) self.upd_enabled = BooleanVar() # Флаг обновлений self.upd_unit = StringVar() # Единица измерения времени self.time_units = {Minutes: 'Минут', Hours: 'Часов', Days: 'Дней', Weeks: 'Недель', Months: 'Месяцев'} self.size_units = {Bytes: 'Байт', KBytes: 'Кбайт', MBytes:'Мбайт', GBytes:'Гбайт', TBytes:'Тбайт'} # Список единиц измерения времени self.maxfsize = StringVar() # Максимальный размер файла self.size_unit = StringVar() # Единица измерения информации self.units_amount1 = StringVar() # Количество единиц self.quar = BooleanVar() # False - удалять, True - карантин self.quar_path = StringVar() # Расположение карантина self.rpt_enabled = BooleanVar() # Флаг отправки отчета self.email = StringVar() # Адрес отправки self.passwd = StringVar() # Пароль исходящего ящика self.rpt_unit = StringVar() # Единица измерения времени self.units_amount2 = StringVar() # Количество единиц self.Upd_Label1 = Label(self.UpdatesFrame, text='Проверять обновления антивирусных баз') self.Upd_Checkbutton1 = Checkbutton(self.UpdatesFrame, variable=self.upd_enabled) self.Upd_Label2 = Label(self.UpdatesFrame, text='Частота проверки: каждые') self.Upd_Spinbox1 = Spinbox(self.UpdatesFrame, textvariable=self.units_amount1, from_=1, to=999999999, width=4) self.Upd_OptionMenu1 = OptionMenu(self.UpdatesFrame, self.upd_unit, *self.time_units.values()) self.Upd_Button1 = Button( self.UpdatesFrame, text='Источники антивирусных сигнатур', command=EntryOptionsWindow('AV_SOURCES', self.Root).main) self.ScanFrame = LabelFrame(self.App, text='Сканирование', borderwidth=2, relief='sunken', padding=(5, 2)) self.Scn_Label1 = Label(self.ScanFrame, text='Максимальный размер файла:') self.Scn_Spinbox1 = Spinbox(self.ScanFrame, textvariable=self.maxfsize, from_=0, to=999999999, width=8) self.Quar_Label = Label(self.ScanFrame, text='При обнаружении угрозы') self.Quar_RadButton1 = Radiobutton(self.ScanFrame, text='Удаление', variable=self.quar, value=False) self.Quar_RadButton2 = Radiobutton(self.ScanFrame, text='Карантин', variable=self.quar, value=True) self.Scn_OptionMenu1 = OptionMenu(self.ScanFrame, self.size_unit, *self.size_units.values()) self.Scn_Edit_Targets = Button(self.ScanFrame, text='Цели сканирования', command=EntryOptionsWindow('SCAN_TARGETS', self.Root, select_path=True).main) self.Scn_Edit_Exceptions = Button(self.ScanFrame, text='Исключения', command=EntryOptionsWindow('SCAN_EXCLUDE', self.Root).main) self.Quar_Button1 = Button(self.ScanFrame, text='Расположение карантина', command=lambda: self.quar_path.set(filedialog.askdirectory())) self.ReportFrame = LabelFrame(self.App, text='Отправка отчета', borderwidth=2, relief='sunken', padding=(5, 2)) self.Rpt_Label1 = Label(self.ReportFrame, text='Отправлять отчеты о сканировании') self.Rpt_Checkbutton1 = Checkbutton(self.ReportFrame, variable=self.rpt_enabled) self.Rpt_Label2 = Label(self.ReportFrame, text='Адрес отправки отчетов:') self.Rpt_Entry1 = Entry(self.ReportFrame, textvariable=self.email, width=32) self.Rpt_Label3 = Label(self.ReportFrame, text='Пароль:') self.Rpt_Entry2 = Entry(self.ReportFrame, textvariable=self.passwd, width=32, show='*') self.Rpt_Label4 = Label(self.ReportFrame, text='Частота:') self.Rpt_Spinbox1 = Spinbox(self.ReportFrame, textvariable=self.units_amount2, from_=1, to=999999999, width=4) self.Rpt_OptionMenu1 = OptionMenu(self.ReportFrame, self.rpt_unit, *self.time_units.values()) self.Rpt_Button1 = Button(self.ReportFrame, text='Получатели', command=EntryOptionsWindow('SEND_TO', self.Root).main) self.Buttons = Frame(self.App, padding=(5, 2)) self.Button1 = Button(self.Buttons, text='Готово', command=self.save_conf) self.Button2 = Button(self.Buttons, text='Отмена', command=self.Root.destroy) def main(self) -> None: self.upd_unit.set(self.time_units[type(UPDATE_FREQ)]) self.units_amount1.set(UPDATE_FREQ.value) self.upd_enabled.set(CHECK_FOR_UPDATES) self.Upd_Checkbutton1.configure(command=( lambda: self.__change_state( self.upd_enabled, self.Upd_Label2, self.Upd_Spinbox1, self.Upd_OptionMenu1, self.Upd_Button1) and self.upd_enabled.set(not self.upd_enabled.get()))) self.Rpt_Checkbutton1.configure(command=( lambda: self.__change_state( self.rpt_enabled, self.Rpt_Label2, self.Rpt_Entry1, self.Rpt_Label3, self.Rpt_Entry2, self.Rpt_Label4, self. Rpt_Spinbox1, self.Rpt_OptionMenu1, self.Rpt_Button1) and self.rpt_enabled.set(not self.rpt_enabled.get()))) self.maxfsize.set(MAX_FILE_SIZE.value) self.size_unit.set(self.size_units[type(MAX_FILE_SIZE)]) self.quar.set(REMOVE_THREATS) self.quar_path.set(QUARANTINE_PATH) self.rpt_enabled.set(SEND_SCAN_REPORTS) self.email.set(SEND_FROM) self.passwd.set(SEND_PASSWD) self.rpt_unit.set(self.time_units[type(SEND_FREQ)]) self.units_amount2.set(SEND_FREQ.value) self.App.pack(fill='both', expand=True) center_win(self.Root, '500x500') self.Root.resizable(False, False) self.Root.title('CobraAV Configuration') self.UpdatesFrame.place(y=0, height=150, width=490) self.__change_state(self.upd_enabled, self.Upd_Label2, self.Upd_Spinbox1, self.Upd_OptionMenu1) self.__change_state(self.rpt_enabled, self.Rpt_Label2, self.Rpt_Entry1, self.Rpt_Label3, self.Rpt_Entry2, self.Rpt_Label4, self.Rpt_Spinbox1, self.Rpt_OptionMenu1, self.Rpt_Button1) self.Upd_Label1.place(relx=.01, rely=.05) # Проверять обновления ? self.Upd_Checkbutton1.place(relx=.8, rely=.05) # Да/Нет self.Upd_Label2.place(relx=.01, rely=.3) # Частота проверки self.Upd_Spinbox1.place(relx=.55, rely=.3, width=60) # Количество self.Upd_OptionMenu1.place(relx=.72, rely=.28) # Единицы измерения self.Upd_Button1.place(relx=.01, rely=.65) # Источники сигнатур self.ScanFrame.place(y=150, height=150, width=490) self.Scn_Label1.place(relx=.01, rely=.05) # Максимальный размер файла self.Scn_Spinbox1.place(relx=.55, rely=.05, width=60) # Количество self.Quar_Label.place(relx=.01, rely=.35) self.Quar_RadButton1.place(relx=.52, rely=.35) # Переключатель на удаление угрозы self.Quar_RadButton2.place(relx=.72, rely=.35) # Переключатель на добавление вкарантина угрозы self.Quar_Button1.place(relx=.56, rely=.65) # Расположение карантина self.Scn_OptionMenu1.place(relx=.72, rely=.014) # Единицы измерения self.Scn_Edit_Targets.place(relx=.01, rely=.65) # Цели сканирования self.Scn_Edit_Exceptions.place(relx=.33, rely=.65) # Исключения self.Rpt_Label1.place(relx=.01, rely=.05) # Отправлять отчеты ? self.Rpt_Checkbutton1.place(relx=.8, rely=.05) # Да/Нет self.ReportFrame.place(y=300, height=150, width=490) self.Rpt_Label2.place(relx=.01, rely=.35) # Адрес отправки отчетов: self.Rpt_Entry1.place(relx=.35, rely=.35) # Ввод адреса отправки отчетов self.Rpt_Label3.place(relx=.01, rely=.50) # Пароль: self.Rpt_Entry2.place(relx=.35, rely=.50) # Ввод пароля: self.Rpt_Label4.place(relx=.01, rely=.75) # Частота отправки self.Rpt_Spinbox1.place(relx=.35, rely=.75, width=60) # Количество self.Rpt_OptionMenu1.place(relx=.52, rely=.72) # Единицы измерения self.Rpt_Button1.place(relx=.72, rely=.74) # Получатели self.Buttons.place(y=450, height=50, width=490) self.Button1.place(relx=.62, rely=.2) # Кнопка "Готово" self.Button2.place(relx=.82, rely=.2) # Кнопка "Отмена" self.Root.mainloop() @staticmethod def __change_state(state: BooleanVar, *args: Widget) -> None: for i in args: i.configure(state=('disabled', 'normal')[state.get()]) def save_conf(self) -> None: size_units = {v: k for k, v in self.size_units.items()} time_units = {v: k for k, v in self.time_units.items()} def wrap_list(a: 'list[str]') -> str: return '[' + ', '.join(f"r'{i}'" for i in a) + ']' def wrap_cls(_unit: Variable, amount: Variable) -> str: unit = _unit.get() if unit in size_units: return size_units[unit].__name__ + f'({amount.get()})' elif unit in time_units: return time_units[unit].__name__ + f'({amount.get()})' else: raise NotImplementedError with open(CONF_PATH, 'w') as f: f.write( f"""from libunits import * CHECK_FOR_UPDATES = {int(self.upd_enabled.get())} # Check for updates UPDATE_FREQ = {wrap_cls(self.upd_unit, self.units_amount1)} # Check interval MAX_FILE_SIZE = {wrap_cls(self.size_unit, self.maxfsize)} # Max file size # Antivirus database sources AV_SOURCES = {wrap_list(AV_SOURCES)} # Antivirus database path DB_PATH = r'{DB_PATH}' # On threat: # 0 - quarantine # 1 - remove REMOVE_THREATS = {int(self.quar.get())} # Directories to scan SCAN_TARGETS = {wrap_list(SCAN_TARGETS)} # Exclude from scanning SCAN_EXCLUDE = {wrap_list(SCAN_EXCLUDE)} # quarantine location QUARANTINE_PATH = r'{self.quar_path.get() or QUARANTINE_PATH}' # Send scan reports SEND_SCAN_REPORTS = {int(self.rpt_enabled.get())} # Scan reports frequency SEND_FREQ = {wrap_cls(self.rpt_unit, self.units_amount2)} # Send from this email SEND_FROM = r'{self.email.get()}' # Sender email password SEND_PASSWD = r'{self.passwd.get()}' # Send to these emails SEND_TO = {wrap_list(SEND_TO)} """) self.Root.destroy()
class Settings_for_root(Frame): def __init__(self, master, board, writer, background, dimensions, transparency): super().__init__(master, bg='#435661') self.master = master self.board = board self.writer = writer self.width = None self.height = None self.xoff = None self.yoff = None self.transparency = None self.entry = None self.current_dim = None self.apply = None self.confirm = None self.set_layout(background, dimensions, transparency) def set_layout(self, background, dimensions, transparency): w, h, x, y = dimensions self.width = Spinbox(self, background='#defffc', foreground='#435661', from_=0, to_=10000, justify='center', highlightthickness=0, increment=1, command=self._apply) self.width.place(relx=0.0725, rely=0.075, relwidth=0.3325, relheight=0.0325, anchor='nw') self.height = Spinbox(self, background='#defffc', foreground='#435661', from_=0, to_=10000, justify='center', highlightthickness=0, increment=1, command=self._apply) self.height.place(relx=0.5825, rely=0.075, relwidth=0.3425, relheight=0.033, anchor='nw') self.xoff = Spinbox(self, background='#defffc', foreground='#435661', from_=0, to_=10000, justify='center', highlightthickness=0, increment=1, command=self._apply) self.xoff.place(relx=0.069, rely=0.186, relwidth=0.333, relheight=0.0325, anchor='nw') self.yoff = Spinbox(self, background='#defffc', foreground='#435661', from_=0, to_=10000, justify='center', highlightthickness=0, increment=1, command=self._apply) self.yoff.place(relx=0.582, rely=0.186, relwidth=0.343, relheight=0.033, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='width') \ .place(relx=0.103, rely=0.048, relwidth=0.27, relheight=0.0275, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='height') \ .place(relx=0.63, rely=0.05, relwidth=0.25, relheight=0.025, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='x offset') \ .place(relx=0.135, rely=0.161, relwidth=0.2025, relheight=0.025, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='y offset') \ .place(relx=0.635, rely=0.16, relwidth=0.23, relheight=0.02625, anchor='nw') self.current_dim = myButton(self, text="Set current root's dimensions", command=lambda *args: self.set_current()) self.current_dim.place(relx=0.175, rely=0.2537, relwidth=0.65, relheight=0.035, anchor='nw') self.transparency = Spinbox(self, background='#defffc', foreground='#435661', from_=0, to_=1, justify='center', highlightthickness=0, increment=0.01, command=self._apply) self.transparency.place(relx=0.3, rely=0.36, relwidth=0.4, relheight=0.03375, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='transparency') \ .place(relx=0.324, rely=0.335, relwidth=0.34, relheight=0.025, anchor='nw') self.entry = Entry(self, borderwidth=0, background='#557282', foreground='#defffc', highlightthickness=0, justify="center") self.entry.place(relx=0.3, rely=0.4725, relwidth=0.4, relheight=0.04625, anchor='nw') Label(self, background='#435661', foreground='#defffc', text='background') \ .place(relx=0.375, rely=0.449, relwidth=0.2525, relheight=0.02375, anchor='nw') self.apply = myButton(self, text="Apply", command=lambda *args: self._apply()) self.apply.place(relx=0.23, rely=0.6075, relwidth=0.54, relheight=0.05125, anchor='nw') self.confirm = myButton(self, text="CONFIRM", command=lambda *args: self._confirm()) self.confirm.place(relx=0.23, rely=0.7762, relwidth=0.54, relheight=0.09125, anchor='nw') self.width.delete(0, "end") self.height.delete(0, "end") self.xoff.delete(0, "end") self.yoff.delete(0, "end") self.width.insert("end", w) self.height.insert("end", h) self.xoff.insert("end", x) self.yoff.insert("end", y) self.transparency.delete(0, "end") self.transparency.insert("end", transparency) self.width.bind("<Return>", lambda *args: self._apply()) self.height.bind("<Return>", lambda *args: self._apply()) self.xoff.bind("<Return>", lambda *args: self._apply()) self.yoff.bind("<Return>", lambda *args: self._apply()) self.transparency.bind("<Return>", lambda *args: self._apply()) self.entry.insert("end", background) def set_current(self): w, h = self.board.winfo_width(), self.board.winfo_height() x, y = self.board.master.winfo_x(), self.board.master.winfo_y() self.width.delete(0, "end") self.height.delete(0, "end") self.xoff.delete(0, "end") self.yoff.delete(0, "end") self.width.insert("end", w) self.height.insert("end", h) self.xoff.insert("end", x) self.yoff.insert("end", y) def _apply(self): self.board.configure(bg=self.entry.get()) w = self.width.get() h = self.height.get() x = self.xoff.get() y = self.yoff.get() self.board.master.geometry(f"{w}x{h}+{x}+{y}") self.board.master.attributes("-alpha", self.transparency.get()) def _confirm(self): self.board.configure(bg=self.entry.get()) self.writer.app_background = self.entry.get() w = self.width.get() h = self.height.get() x = self.xoff.get() y = self.yoff.get() self.board.master.geometry(f"{w}x{h}+{x}+{y}") self.writer.app_geometry = f"{w}x{h}+{x}+{y}" self.writer.app_transparency = self.transparency.get() self.destroy()
class GUI(): def __init__(self): self.root = Tk( className='Программа для удаление подписей из электронных писем') self.root.geometry("1000x600") self.root.wm_resizable(False, False) self.panelFrame = LabelFrame(self.root, height=100, text="") self.panelFrame.pack(side='top', fill='x') self.labelLogin = Label(self.panelFrame, text="Адрес почты: ") self.labelLogin.place(x=10, y=40) self.loginField = Entry(self.panelFrame, width=20) self.loginField.place(x=100, y=40) self.labelPassword = Label(self.panelFrame, text="Пароль: ") self.labelPassword.place(x=280, y=40) self.passwordField = Entry(self.panelFrame, show="*", width=15) self.passwordField.place(x=340, y=40) self.labelLogin = Label( self.panelFrame, text="Порядковый номер письма \nв папке 'входящие': ") self.labelLogin.place(x=490, y=30) self.sb = Spinbox(self.panelFrame, from_=1, to=10000) self.sb.place(x=690, y=40, width=50) self.buttonDeleteSing = Button(self.panelFrame, text="Удалить подпись", command=self._delete_signature) self.buttonDeleteSing.place(x=770, y=15, width=200) self.buttonInfo = Button(self.panelFrame, text="Помощь") self.buttonInfo.place(x=770, y=45, width=200) self.buttonInfo.bind('<ButtonRelease-1>', GUI._show_info) self.textFrame1 = LabelFrame(self.root, width=500, text='Исходный текст письма') self.textFrame1.pack(fill='y', side='left') self.textbox1 = Text(self.textFrame1, font='Arial 12', wrap='word') self.textbox1.pack(side='left', fill='both') self.textbox1.place(width=490) self.textFrame2 = LabelFrame(self.root, width=500, text='Текст без подписи') self.textFrame2.pack(fill='y', side='right') self.textbox2 = Text(self.textFrame2, font='Arial 12', wrap='word') self.textbox2.pack(side='left', fill='both') self.textbox2.place(width=490) def _show_messagebox(self, messageType, message): if messageType == 'error': messagebox.showerror('Ошибка', message) elif messageType == 'warning': messagebox.showwarning('Предупреждение', message) else: messagebox.showinfo('Info', message) def _delete_signature(self): address = self.loginField.get() password = self.passwordField.get() index = int(self.sb.get()) try: original, without_sign = SignatureRemover.delete_signature( address, password, index) except EmailException as e: self._show_messagebox('error', str(e)) return except EmailWarning as e: self._show_messagebox('warning', str(e)) return except ClassifierException as e: self._show_messagebox( 'error', "Ошибка при загрузке классификатора:\n" + str(e)) return self._show_email_lines(original, self.textbox1) self._show_email_lines(without_sign, self.textbox2) del_lines_count = len(original) - len(without_sign) self._show_messagebox('info', "Удалено строк: " + str(del_lines_count)) def _show_info(self): messagebox.showinfo( 'Информация', 'Программа позволяет удалять подпись ' 'из текстов электронных писем папки "Входящие" почтового ящика gmail.\nУдаление ' 'подписи возможно в письмах, содержащих только текст.' '\nДля удаления подписи из письма введите адрес электронной почты, пароль и порядковый номер' ' письма в папке "Входящие", затем нажмите кнопку "Удалить подпись"' ) def _show_email_lines(self, lines, textbox): textbox.delete('1.0', END) all_lines = "\n".join(lines) textbox.insert('1.0', all_lines) def show(self): self.root.mainloop()