def initUI(self): self.parent.title("Checkbutton") self.pack(fill=BOTH, expand=1) self.var = IntVar() cb = Checkbutton(self, text="Show title", variable=self.var, command=self.onClick) cb.select() cb.place(x=50, y=50)
def __init__(self): self.window = Tk() self.window.geometry('500x500') self.window.title('LIBRUSReader') loginLabel = Label(text='Podaj login') passwordLabel = Label(text='Podaj hasło') loginLabel.place(x=10, y=25) passwordLabel.place(x=10, y=50) self.login = StringVar() self.password = StringVar() self.windowMode = BooleanVar() self.consoleReadingMessages = BooleanVar() self.answer = StringVar() loginEntry = Entry(textvariable=self.login, width='30') passwordEntry = Entry(textvariable=self.password, show='*', width='30') loginEntry.place(x=80, y=25) passwordEntry.place(x=80, y=50) checkbox = Checkbutton(self.window, text='Tryb okienkowy', variable=self.windowMode) checkbox.place(x=15, y=125) checkboxOdczyt = Checkbutton( self.window, text= 'Wyświetlanie wiadomości w konsoli (użyteczne przy wyłączeniu trybu okienkowego', variable=self.consoleReadingMessages) checkboxOdczyt.place(x=15, y=150) self.answer = Text(self.window, width='54', height='15') answerLabel = Label( text='Odpowiedź do wiadomości (jeśli puste, nie przesyła)') self.answer.place(x=15, y=215) answerLabel.place(x=15, y=190) runProgram = Button(self.window, text='Uruchom program', width='36', height=' 1', command=self.zapiszDane, bg='grey') runProgram.place(x=16, y=100) self.window.mainloop()
def _init_ui(self): # Label to specify video link lbl_video_url = Label(self, text="Video URL:") lbl_video_url.place(x=20, y=20) # Entry to enter video url entr_video_url = Entry(self, width=50, textvariable=self._video_url) entr_video_url.place(x=100, y=20) # Checkbutton to extract audio cb_extract_audio = Checkbutton(self, var=self._extract_audio, text="Only keep audio") cb_extract_audio.pack() cb_extract_audio.place(x=20, y=60) # Button to browse for location b_folder_choose = Button(self, text="Choose output directory", command=self.ask_directory) b_folder_choose.place(x=150, y=90) # Button to start downloading b_start_download = Button(self, text="Start download", command=self.download) b_start_download.place(x=20, y=90) # Log window to log progress self._logger.place(x=20, y=130)
def create_checkbutton(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 button = Checkbutton(self.board) button.place(relx=x, rely=y, relheight=height, relwidth=width, anchor="nw") self.board.delete("line") items = [item for item in button.keys() if len(item) > 2] button.bind("<Enter>", lambda event: self.get_widget_info(button)) button.bind("<Leave>", lambda event: self.focus_out()) button.bind("<Button-3>", lambda event: self.modify(button, items)) self.manager.switch(button, items)
class Win1: def run(self): # Var set self.choice1 = "No" self.choice2 = None self.donateo = 0 self.donateol = [] # Window set self.win = Tk() self.win.title("Easy USB Backup") self.win.geometry('700x400') self.win.resizable(0, 0) self.win.iconbitmap(path + 'material/a.ico') # Background self.canvas = Canvas(width=700, height=400, highlightthickness=0, borderwidth=0) self.background = PhotoImage(file=path + 'material/b.gif') self.canvas.create_image(0, 0, image=self.background, anchor='nw') # Ico self.ico = PhotoImage(file=path + 'material/c.png') self.canvasIco = Canvas(width=260, height=244, highlightthickness=0, borderwidth=0) self.canvasIco.create_image(0, 0, image=self.ico, anchor='nw') # Label self.l1 = self.canvas.create_text(350, 260, font=('Arial Black', 20)) self.l2 = self.canvas.create_text(520, 365, font=('Arial Black', 17)) # Button functions def b1f(): if self.choice2 == True: self.win.destroy() Log("Content window is closed") self.win2 = Win2() Log("=========Start to run main window=========") self.win2.run() elif self.choice2 == None: messagebox.showwarning("Easy USB Backup", "请先点击软件协议") def b2f(): Log("Start to run agreement window") if self.choice2 != True: self.rule = Toplevel() self.rule.title('Easy USB Backup') self.rule.geometry('500x350') self.rule.resizable(0, 0) self.rule.iconbitmap(path + 'material/a.ico') # Extensions self.ruleBar = Scrollbar(self.rule, orient='vertical', width=20) self.ruleText = Text(self.rule, width=68, yscrollcommand=self.ruleBar.set) with open(path + 'material/d.pyc', encoding='utf-8') as file: ruleContent = file.readlines() for i in ruleContent: self.ruleText.insert('insert', i) del i self.ruleBar.config(command=self.ruleText.yview) self.ruleText.config(state='disabled') def ruleB1f(): if self.choice1 == "No": self.choice1 = "Yes" elif self.choice1 == "Yes": self.choice1 = "No" def ruleB2f(): if self.choice1 == "Yes": Log("Agreement is accessed") self.rule.destroy() messagebox.showinfo("Easy USB Backup", "感谢您对本软件的信赖,祝您使用愉快!") self.choice2 = True elif self.choice1 == "No": messagebox.showerror("Easy USB Backup", "请认真仔细阅读该软件协议!") def ruleB3f(): if self.choice1 == "Yes": Log("Agreement is refused, start to exit") sys.exit() elif self.choice1 == "No": messagebox.showerror("Easy USB Backup", "请认真仔细阅读该软件协议!") self.ruleB1 = Checkbutton(self.rule, text="我已仔细认真阅读以上软件协议", command=ruleB1f) self.ruleB2 = Button(self.rule, text="我同意以上软件协议", command=ruleB2f, relief=GROOVE) self.ruleB3 = Button(self.rule, text="我拒绝以上软件协议", command=ruleB3f, relief=GROOVE) # Display self.ruleText.place(x=0, y=0) self.ruleBar.pack(side='right', fill='y') self.ruleB1.place(x=0, y=320) self.ruleB2.place(x=200, y=318) self.ruleB3.place(x=340, y=318) self.rule.mainloop() def b3f(): if self.choice2 == True: Log("Button update is clicked") web.open( "https://github.com/Skyler-std/program_py/tree/main/USB_copy", new=2, autoraise=True) elif self.choice2 == None: messagebox.showwarning("Easy USB Backup", "请先点击软件协议") def b4f(): if self.choice2 == True: Log("Tip button is clicked") # Tip window self.tip = Toplevel() self.tip.geometry('500x318') self.tip.title("Easy USB Backup") self.tip.iconbitmap(path + 'material/a.ico') self.tip.resizable(0, 0) # Extensions self.tipBar = Scrollbar(self.tip, orient='vertical', width=20) self.tipText = Text(self.tip, width=68, yscrollcommand=self.tipBar.set) with open(path + 'material/e.pyc', encoding='utf-8') as file: tipContent = file.readlines() for i in tipContent: self.tipText.insert('insert', i) self.tipText.config(state='disabled') self.tipBar.config(command=self.tipText.yview) # Display self.tipText.place(x=0, y=0) self.tipBar.pack(side='right', fill='y') self.tip.mainloop() elif self.choice2 == None: messagebox.showwarning("Easy USB Backup", "请先点击软件协议") def b5f(): if self.choice2 == True: Log("Donate button is clicked") self.donateo += 1 self.donateol.append(self.donateo) if len(self.donateol) == 1: def donateThf(): pygame.init() self.icon = pygame.image.load(path + 'material/a.ico') pygame.display.set_icon(self.icon) self.screen = pygame.display.set_mode((399, 399)) pygame.display.set_caption("Easy USB Backup") self.donateImg = pygame.image.load( path + 'material/f.png').convert() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() self.donateol.clear() return self.screen.blit(self.donateImg, (-1, -1)) pygame.display.update() self.donateTh = Thread(target=donateThf, daemon=False) self.donateTh.start() elif self.choice2 == None: messagebox.showwarning("Easy USB Backup", "请先点击软件协议") def b6f(): if self.choice2 == True: Log("Contact button is clicked") # Contact Window self.connect = Toplevel() self.connect.title("Easy USB Backup") self.connect.iconbitmap(path + 'material/a.ico') self.connect.geometry('500x350') self.connect.resizable(0, 0) # Extensions self.connectT = Text(self.connect, width=500, height=350) self.connectT.insert( 'insert', 'QQ:3385213313\nWechat id:wxid-ZhanChiPengFei') self.connectT.config(state='disabled') # Display self.connectT.place(x=0, y=0) self.connect.mainloop() elif self.choice2 == None: messagebox.showwarning("Easy USB Backup", "请先点击软件协议") # Button self.b1 = Button(self.win, font=('Arial Black', 14), width=10, height=1, relief=GROOVE, text='主界面', command=b1f) self.b2 = Button(self.win, font=('Arial Black', 14), width=10, height=1, relief=GROOVE, text='软件协议', command=b2f) self.b3 = Button(self.win, font=('Arial Black', 14), width=10, height=1, relief=GROOVE, text='检查更新', command=b3f) self.b4 = Button(self.win, font=('Arial Black', 14), width=10, height=1, relief=GROOVE, text='注意事项', command=b4f) self.b5 = Button(self.win, font=('Arial Black', 14), width=10, height=1, relief=GROOVE, text='捐赠', command=b5f) self.b6 = Button(self.win, font=('Arial Black', 14), width=10, height=1, relief=GROOVE, text='联系方式', command=b6f) # Loop self.canvas.place(x=0, y=0) self.canvas.insert(self.l1, 1, "Easy USB Backup") self.canvas.insert(self.l2, 1, "您的支持乃作者的最大动力") self.canvasIco.place(x=220, y=0) self.X = 20 self.Y = 290 self.b1.place(x=self.X, y=self.Y) self.b2.place(x=self.X + 170, y=self.Y) self.b3.place(x=self.X + 340, y=self.Y) self.b4.place(x=self.X + 510, y=self.Y) self.b5.place(x=self.X, y=self.Y + 55) self.b6.place(x=self.X + 170, y=self.Y + 55) self.win.mainloop()
def predict_pretrained(self): """ :return: """ p_pt_root = Tk() self.new_window(p_pt_root, "MitoSegNet Navigator - Predict using pretrained model", 500, 330) self.small_menu(p_pt_root) datapath = StringVar(p_pt_root) modelpath = StringVar(p_pt_root) popupvar = StringVar(p_pt_root) batch_var = StringVar(p_pt_root) min_obj_size = StringVar(p_pt_root) min_obj_size.set(0) # open choose directory window def askopendata(): set_datapath = filedialog.askdirectory(parent=p_pt_root, title='Choose a directory') datapath.set(set_datapath) # open choose file window def askopenmodel(): set_modelpath = filedialog.askopenfilename(parent=p_pt_root, title='Choose a file') modelpath.set(set_modelpath) #browse for raw image data text = "Select directory in which 8-bit raw images are stored" self.place_browse(askopendata, text, datapath, 15, 20, None, None, p_pt_root) #browse for pretrained model text = "Select pretrained model file" self.place_browse(askopenmodel, text, modelpath, 15, 90, None, None, p_pt_root) self.place_prediction_text(min_obj_size ,batch_var, popupvar, p_pt_root) ps_filter = StringVar(p_pt_root) ps_filter.set(False) psf_button = Checkbutton(p_pt_root, text="Post-segmentation filtering", variable=ps_filter, onvalue=True, offvalue=False) psf_button.place(bordermode=OUTSIDE, x=15, y=280, height=30, width=200) # start prediction on pretrained model def start_prediction_pretrained(): if datapath.get() != "" and modelpath.get() != "": tile_size = 656 model_path, model_file = os.path.split(modelpath.get()) if batch_var.get() == "One folder": y, x = self.get_image_info(datapath.get(), True, False) else: y, x = self.get_image_info(datapath.get(), True, True) try: x_res = p_pt_root.winfo_screenwidth() y_res = p_pt_root.winfo_screenheight() except: print("Error when trying to retrieve screenwidth and screenheight. ", "Skipping post-segmentation filtering") x_res = 0 y_res = 0 ps_filter.set(False) self.prediction(datapath.get(), datapath.get(), modelpath.get(), model_file, batch_var.get(), popupvar.get(), tile_size, y, x, min_obj_size.get(), ps_filter.get(), x_res, y_res, p_pt_root) else: messagebox.showinfo("Error", "Entries not completed", parent=p_pt_root) self.place_button(p_pt_root, "Start prediction", start_prediction_pretrained, 360, 280, 30, 110)
def cont_data(self, old_window): old_window.destroy() data_root = Tk() self.new_window(data_root, "MitoSegNet Data Augmentation", 450, 600) self.small_menu(data_root) dir_data_path = StringVar(data_root) tkvar = StringVar(data_root) tile_size = IntVar(data_root) tile_number = IntVar(data_root) n_aug = IntVar(data_root) width_shift = DoubleVar(data_root) height_shift = DoubleVar(data_root) shear_range = DoubleVar(data_root) rotation_range = IntVar(data_root) zoom_range = DoubleVar(data_root) brigthness_range = DoubleVar(data_root) tkvar.set('') # set the default option # open choose directory window and adding list of possible tile sizess def askopendir(): set_dir_data_path = filedialog.askdirectory(parent=data_root, title='Choose a directory') dir_data_path.set(set_dir_data_path) pr_list, val_List = self.preprocess.poss_tile_sizes(set_dir_data_path + os.sep + "train" + os.sep + "RawImgs") if set_dir_data_path != "": tkvar.set(list(pr_list)[0]) # set the default option choices = pr_list popupMenu = OptionMenu(data_root, tkvar, *choices) popupMenu.place(bordermode=OUTSIDE, x=30, y=90, height=30, width=300) # on change dropdown value def change_dropdown(*args): tile_inf = tkvar.get() l = (tile_inf.split(" ")) tile_size.set(int(l[3])) tile_number.set(int(l[-1])) #link function to change dropdown (tile size and number) tkvar.trace('w', change_dropdown) text= "Select MitoSegNet Project directory" self.place_browse(askopendir, text, dir_data_path, 20, 10, None, None, data_root) self.place_text(data_root, "Choose the tile size and corresponding tile number", 20, 70, None, None) self.place_text(data_root, "Choose the number of augmentation operations", 20, 130, None, None) self.place_entry(data_root, n_aug, 30, 150, 30, 50) self.place_text(data_root, "Specify augmentation operations", 20, 190, None, None) horizontal_flip = StringVar(data_root) horizontal_flip.set(False) hf_button = Checkbutton(data_root, text="Horizontal flip", variable=horizontal_flip, onvalue=True, offvalue=False) hf_button.place(bordermode=OUTSIDE, x=30, y=210, height=30, width=120) vertical_flip = StringVar(data_root) vertical_flip.set(False) vf_button = Checkbutton(data_root, text="Vertical flip", variable=vertical_flip, onvalue=True, offvalue=False) vf_button.place(bordermode=OUTSIDE, x=150, y=210, height=30, width=120) self.place_text(data_root, "Width shift range", 30, 240, None, None) self.place_text(data_root, "(fraction of total width, if < 1, or pixels if >= 1)", 30, 260, None, None) self.place_entry(data_root, width_shift, 370, 250, 30, 50) self.place_text(data_root, "Height shift range", 30, 280, None, None) self.place_text(data_root, "(fraction of total height, if < 1, or pixels if >= 1)", 30, 300, None, None) self.place_entry(data_root, height_shift, 370, 290, 30, 50) self.place_text(data_root, "Shear range (Shear intensity)", 30, 340, None, None) self.place_entry(data_root, shear_range, 370, 330, 30, 50) self.place_text(data_root, "Rotation range (Degree range for random rotations)", 30, 380, None, None) self.place_entry(data_root, rotation_range, 370, 370, 30, 50) self.place_text(data_root, "Zoom range (Range for random zoom)", 30, 420, None, None) self.place_entry(data_root, zoom_range, 370, 410, 30, 50) self.place_text(data_root, "Brightness range (Range for random brightness change)", 30, 460, None, None) self.place_entry(data_root, brigthness_range, 370, 450, 30, 50) check_weights = StringVar(data_root) check_weights.set(False) Checkbutton(data_root, text="Create weight map", variable=check_weights, onvalue=True, offvalue=False).place(bordermode=OUTSIDE, x=30, y=500, height=30, width=150) # create augmented data def generate_data(): if dir_data_path.get() != "": if int(horizontal_flip.get()) == 1: hf = True else: hf = False if int(vertical_flip.get()) == 1: vf = True else: vf = False self.preprocess.splitImgs(dir_data_path.get(), tile_size.get(), tile_number.get()) final_brigthness_range = (1 - brigthness_range.get(), 1 + brigthness_range.get()) aug = Augment(dir_data_path.get(), shear_range.get(), rotation_range.get(), zoom_range.get(), final_brigthness_range, hf, vf, width_shift.get(), height_shift.get()) if int(check_weights.get()) == 1: wmap=True else: wmap=False aug.start_augmentation(imgnum=n_aug.get(), wmap=wmap, tile_size=tile_size.get()) aug.splitMerge(wmap=wmap) mydata = Create_npy_files(dir_data_path.get()) mydata.create_train_data(wmap, tile_size.get(), tile_size.get()) messagebox.showinfo("Done", "Augmented data successfully generated", parent=data_root) else: messagebox.showinfo("Error", "Entries missing or not correct", parent=data_root) self.place_button(data_root, "Start data augmentation", generate_data, 150, 550, 30, 150)
countTitle = Label(frame1, text="Count:") countTitle.place(x=200, y=100) countTitle.configure(background = "black", foreground="white") countInfo = Label(frame1, text="") countInfo.place(x=200, y=125) countInfo.configure(background = "black", foreground="white") prevBtn= HoverButton(frame1, text="Previous", command=prev_row, padx=2, pady=2) prevBtn.place(x=10,y=65) prevBtn.configure(background = "black", foreground="white") nextBtn = HoverButton(frame1, text="Next", command=next_row, padx=2, pady=2) nextBtn.place(x=85,y=65) skipVar = IntVar() skipBtn = Checkbutton(frame1, text='', variable=skipVar, selectcolor="grey88", background='black') skipBtn.place(x=145,y=65) navTitle = Label(frame1, text="Skip/Hide Standardized Words") navTitle.place(x=180, y=65) navTitle.configure(background = "black", foreground="white") gameDescTitle = Label(frame1, text="Game:") gameDescTitle.place(x=10, y=100) gameDescTitle.configure(background = "black", foreground="white") gameDescInfo = Label(frame1, text="") gameDescInfo.place(x=10, y=130) gameDescInfo.configure(background = "black", foreground="white") gameDescTxt = st.ScrolledText(frame1, undo=True, width=40, height=50, wrap="word", bg = "black", fg = "white") gameDescTxt.place(x=10, y=160) gameDescTxt.insert(1.0, "LOAD A FILE..") # FRAME 2
class Janela: def __init__(self, master=None): #BARRA DE MENUS menubar = Menu(master) master.config(menu=menubar) #MENU OPCOES opmenu = Menu(menubar, tearoff=0) opmenu.add_command(label="Visualizar Atendimentos", command=self.Visualizar) menubar.add_cascade(label="Opções", menu=opmenu) #MENUN SOBRE sobremenu = Menu(menubar, tearoff=0) sobremenu.add_command(label="Sobre", command=self.Sobre) menubar.add_cascade(label="?", menu=sobremenu) #INICIA BANCO DE DADOS self.banco = Banco() self.dia = False #TITULO self.TopFrame = Frame(master, width=largura, height=100, bg=cor_principal, relief="raise") self.TopFrame.pack(side=TOP) #Logo da Meta e Titulo do programa self.logo = PhotoImage(file="icons/logo_.png") self.logo_meta = Label(self.TopFrame, image=self.logo, bg=cor_principal) self.logo_meta.place(x=5, y=5) self.meta = Label(self.TopFrame, text="Controle de Atendimentos", font=fonte_Titulos, fg=cor_contraste, bg=cor_principal) self.meta.place(x=280, y=25) #AMBIENTE DE INFORMACOES 1 self.infosFrame = Frame(master, width=450, height=150, bg=cor_principal, relief="raise") self.infosFrame.place(x=540, y=150) #Data self.date = Label(self.infosFrame, text=data, fg=cor_contraste, bg=cor_principal, font=fonte_Destaques) self.date.place(x=140, y=5) #Quantidade de Atendimentos self.qtd_atendimentos = self.banco.current self.dados = self.banco.dados self.n_atendiLabel = Label(self.infosFrame, text="Atendimentos Realizados", fg=cor_contraste, bg=cor_principal, font=fonte_Textos) self.n_atendiLabel.place(x=15, y=50) self.frame_aux = Frame(self.infosFrame, width=200, height=50, bg=cor_secundaria, relief="raise") self.frame_aux.place(x=15, y=85) self.qtd = Label(self.frame_aux, text=self.qtd_atendimentos, bg=cor_secundaria, fg=cor_destaque, font=fonte_Destaques) self.qtd.place(relx=0.5, rely=0.5, anchor=CENTER) #Quantidade de Atendimentos do Dia self.qtd_h = self.dados.loc[self.dados["Data"] == data].count() self.n_atendiHLabel = Label(self.infosFrame, text="Atendimentos de Hoje", fg=cor_contraste, bg=cor_principal, font=fonte_Textos) self.n_atendiHLabel.place(x=235, y=50) self.frame_auxH = Frame(self.infosFrame, width=200, height=50, bg=cor_secundaria, relief="raise") self.frame_auxH.place(x=235, y=85) self.qtd_hj = Label(self.frame_auxH, text=self.qtd_h[0], bg=cor_secundaria, fg=cor_destaque, font=fonte_Destaques) self.qtd_hj.place(relx=0.5, rely=0.5, anchor=CENTER) #AMBIENTE DE INFORMACOES 2 self.infos_2Frame = Frame(master, width=450, height=225, bg=cor_principal, relief="raise") self.infos_2Frame.place(x=540, y=325) #VISUALIZACAO RAPIDA DE CADASTROS self.dadosCols = tuple(self.banco.dados.columns) self.listagem = ttk.Treeview(self.infos_2Frame, columns=self.dadosCols, show='headings', height=10, selectmode='extended') self.listagem.bind('<Double-1>', self.Mostrar) self.listagem.column("Id", width=25) self.listagem.heading("Id", text="ID") self.listagem.column("Local", width=70) self.listagem.heading("Local", text="Local") self.listagem.column("Solicitante", width=70) self.listagem.heading("Solicitante", text="Solicitante") self.listagem.column("Atendimento", width=70) self.listagem.heading("Atendimento", text="Atendimento") self.listagem.column("Certificado", width=70) self.listagem.heading("Certificado", text="Certificado") self.listagem.column("Meta", width=35) self.listagem.heading("Meta", text="Meta") self.listagem.column("Resolvido", width=35) self.listagem.heading("Resolvido", text="Resolvido") self.listagem.column("Data", width=70) self.listagem.heading("Data", text="Data") self.listagem.pack(side=LEFT) #BARRAS DE ROLAGEM DA VISUALIZACAO self.ysb = ttk.Scrollbar(self.infos_2Frame, orient=VERTICAL, command=self.listagem.yview) self.listagem['yscroll'] = self.ysb.set self.ysb.pack(side=RIGHT, fill=Y) # TEXTOS DOS CABEÇALHO for c in self.dadosCols: self.listagem.heading(c, text=c.title()) # INSRINDO OS ITENS for item in self.dados.loc[self.dados["Data"] == data].values: self.listagem.insert('', 'end', values=tuple(item)) #AMBIENTE DE CADASTRO self.cadastroFrame = Frame(jan, width=450, height=altura - 200, bg=cor_principal, relief="raise") self.cadastroFrame.place(x=40, y=150) #LOCAL self.localLabel = Label(self.cadastroFrame, text="Local: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.localLabel.place(x=xLabels, y=yInicialCadastro) self.localEntry = AutocompleteCombobox(self.cadastroFrame, width=entrysWidth) lista_locais = list(self.banco.dados["Local"].drop_duplicates()) self.localEntry.set_completion_list(lista_locais) self.localEntry.place(x=xEntrys, y=yInicialCadastro) #SOLICITANTE self.solLabel = Label(self.cadastroFrame, text="Solicitante: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.solLabel.place(x=xLabels, y=yInicialCadastro + 70) self.solEntry = AutocompleteCombobox(self.cadastroFrame, width=entrysWidth) self.solEntry.set_completion_list(lista_solicitantes) self.solEntry.place(x=xEntrys, y=yInicialCadastro + 70) #ATENDIMENTO self.atendLabel = Label(self.cadastroFrame, text="Atendimento: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.atendLabel.place(x=xLabels, y=yInicialCadastro + 140) self.atendEntry = AutocompleteCombobox(self.cadastroFrame, width=entrysWidth) self.atendEntry.set_completion_list(lista_atendimentos) self.atendEntry.place(x=xEntrys, y=yInicialCadastro + 140) #CERTIFICADO self.certLabel = Label(self.cadastroFrame, text="Certificado: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.certLabel.place(x=xLabels, y=yInicialCadastro + 210) self.certEntry = AutocompleteCombobox(self.cadastroFrame, width=entrysWidth) self.certEntry.set_completion_list(lista_certificados) self.certEntry.place(x=xEntrys, y=yInicialCadastro + 210) #META self.chkValueMeta = BooleanVar() self.chkValueMeta.set(False) self.chkMeta = Checkbutton(self.cadastroFrame, text='Dispostivo da Meta', var=self.chkValueMeta, bg=cor_principal, activebackground=cor_principal, fg=cor_contraste, selectcolor=cor_principal) self.chkMeta.place(x=xLabels, y=yInicialCadastro + 260) #RESOLVIDO self.chkValueResol = BooleanVar() self.chkValueResol.set(False) self.chkResolv = Checkbutton(self.cadastroFrame, text='Problema Resolvido', var=self.chkValueResol, bg=cor_principal, activebackground=cor_principal, fg=cor_contraste, selectcolor=cor_principal) self.chkResolv.place(x=xEntrys + 100, y=yInicialCadastro + 260) #BOTAO DE INSERIR self.cadastroButton = Button(self.cadastroFrame, text="Inserir Atendimento", bg=cor_principal, fg=cor_contraste, width=entrysWidth, command=self.Inserir) self.cadastroButton.place(x=xEntrys - 50, y=yInicialCadastro + 300) def Calendar(self): # Create a GUI window self.new_gui = Tk() # Set the background colour of GUI window self.new_gui.config(background=cor_principal) #self.new_gui.resizable(width = False, height = False) #Transparencia self.new_gui.attributes("-alpha", 0.95) # set the name of tkinter GUI window self.new_gui.title("CALENDARIO") # Set the configuration of GUI window self.new_gui.geometry("250x300") def Proximo_Mes(): self.fetch_month += 1 if self.fetch_month == 13: self.fetch_year += 1 self.fetch_month = 1 self.cal_content = calendar.month(self.fetch_year, self.fetch_month) self.call_cal["text"] = self.cal_content def Volta_Mes(): self.fetch_month -= 1 if self.fetch_month == 0: self.fetch_year -= 1 self.fetch_month = 12 self.cal_content = calendar.month(self.fetch_year, self.fetch_month) self.call_cal["text"] = self.cal_content # get method returns current text as string self.fetch_year = 2021 self.fetch_month = 1 # calendar method of calendar module return # the calendar of the given year . self.cal_content = calendar.month(self.fetch_year, self.fetch_month) self.Frame_But = Frame(self.new_gui, width=250, height=40, bg=cor_principal, relief="raise") self.Frame_But.pack(side=TOP) self.Frame_Calen = Frame(self.new_gui, width=250, height=300, bg=cor_principal, relief="raise") self.Frame_Calen.pack(side=TOP) self.ant_but = Button(self.Frame_But, text="Anterior", width=10, command=Volta_Mes, bg=cor_principal, fg=cor_contraste) #self.ant_but.grid(row = 1,column = 0,padx=1) self.ant_but.place(x=20, y=15) self.next_but = Button(self.Frame_But, text="Proximo", width=10, command=Proximo_Mes, bg=cor_principal, fg=cor_contraste) self.next_but.place(x=150, y=15) #self.next_but.grid(row = 1, column = 0, padx=0.5) # Create a label for showing the content of the calender self.call_cal = Label(self.Frame_Calen, text=self.cal_content, font="Consolas 15 bold", anchor="e", justify=LEFT, bg=cor_principal, fg=cor_contraste) # grid method is used for placing # the widgets at respective positions # in table like structure. self.call_cal.place(x=10, y=20) #self.call_cal.grid(row = 3, column = 0, padx = 10) # start the GUI self.new_gui.mainloop() def Selecionar_Data(self): def Data_escolhida(): self.data = cal.selection_get() cal.see(datetime.date(year=2016, month=2, day=5)) for item in self.banco.dados.loc[self.banco.dados["Data"] == self.dia].values: self.listagem_v.insert('', 'end', values=tuple(item)) jan_cal = Tk() try: primeira_data = self.banco.dados["Data"].iloc[0] primeira_data = primeira_data.split("/") primeira_data = datetime.date(int(primeira_data[2]), int(primeira_data[1]), int(primeira_data[0])) except: primeira_data = datetime.date.today() data_ = data.split("/") ultima_data = datetime.date(int(data_[2]), int(data_[1]), int( data_[0])) + datetime.timedelta(days=1) print(primeira_data, ultima_data) cal = Calendar(jan_cal, font=fonte_Textos, locale='pt_BR', mindate=primeira_data, maxdate=ultima_data, bg="grey10", fg='grey8', year=2018, month=2) cal.pack(fill="both", expand=True) ttk.Button(jan_cal, text="ok", command=Data_escolhida).pack() def to_datetime(x=""): x = x.split("/") return datetime.date(int(x[2]), int(x[1]), int(x[0])) def to_data(x): return x.strftime("%d/%m/%Y") def Visualizar(self): #banco = Banco() #Abre a nova janela self.visualizar_janela = Tk() #CONFIGURACOES ---- #Titulo self.visualizar_janela.title(titulo) #Tamanho da janela self.visualizar_janela.geometry("{}x{}".format(largura, altura)) #Cor de Fundo self.visualizar_janela.configure(background=cor_principal) #Nao redimensionar self.visualizar_janela.resizable(width=False, height=False) #Transparencia self.visualizar_janela.attributes("-alpha", 0.95) #Icone self.visualizar_janela.iconbitmap(default="Icons/icon.ico") self.frame_opcoes = Frame(self.visualizar_janela, borderwidth=2, width=largura - 60, height=100, bg=cor_principal, relief="raise") self.frame_opcoes.place(x=30, y=10) self.frame_list = Frame(self.visualizar_janela, borderwidth=2, width=largura, height=altura - 150, bg=cor_principal, relief="raise") self.frame_list.place(x=30, y=150) #self.sel_data = ttk.Button(self.frame_opcoes,text="Selecionar Data",command = self.Selecionar_Data).pack() dadosCols = tuple(self.banco.dados.columns) self.listagem_v = ttk.Treeview(self.frame_list, columns=dadosCols, show='headings', height=20) self.listagem_v.bind('<Double-1>', self.Mostrar) self.listagem_v.column("Id", width=25, anchor=CENTER) self.listagem_v.heading("Id", text="ID", anchor=CENTER) self.listagem_v.column("Local", width=170, anchor=CENTER) self.listagem_v.heading("Local", text="Local", anchor=CENTER) self.listagem_v.column("Solicitante", width=100, anchor=CENTER) self.listagem_v.heading("Solicitante", text="Solicitante", anchor=CENTER) self.listagem_v.column("Atendimento", width=250, anchor=CENTER) self.listagem_v.heading("Atendimento", text="Atendimento", anchor=CENTER) self.listagem_v.column("Certificado", width=150, anchor=CENTER) self.listagem_v.heading("Certificado", text="Certificado", anchor=CENTER) self.listagem_v.column("Meta", width=70, anchor=CENTER) self.listagem_v.heading("Meta", text="Meta", anchor=CENTER) self.listagem_v.column("Resolvido", width=70, anchor=CENTER) self.listagem_v.heading("Resolvido", text="Resolvido", anchor=CENTER) self.listagem_v.column("Data", width=100, anchor=CENTER) self.listagem_v.heading("Data", text="Data", anchor=CENTER) #self.listagem_v.place(x=45,y=150) self.listagem_v.pack(side=LEFT) #BARRAS DE ROLAGEM DA VISUALIZACAO self.ysb = ttk.Scrollbar(self.frame_list, orient=VERTICAL, command=self.listagem_v.yview) self.listagem_v['yscroll'] = self.ysb.set self.ysb.pack(side=LEFT, fill=Y) # TEXTOS DOS CABEÇALHO for c in self.dadosCols: self.listagem_v.heading(c, text=c.title()) # INSRINDO OS ITENS if self.dia == False: for item in self.banco.dados.values: self.listagem_v.insert('', 'end', values=tuple(item)) else: for item in self.banco.dados.loc[self.banco.dados["Data"] == self.dia].values: self.listagem_v.insert('', 'end', values=tuple(item)) self.visualizar_janela.mainloop() def Mostrar(self, event): try: #global listagem, lista_atendimentos,lista_certificados,lista_locais,lista_solicitantes #Pega o item selecionado self.nodeId_1 = self.listagem.focus() #Pega as informacoes do item self.id_ = self.listagem.item(self.nodeId_1)['values'][0] local = self.listagem.item(self.nodeId_1)['values'][1] solicitante = self.listagem.item(self.nodeId_1)['values'][2] atendimento = self.listagem.item(self.nodeId_1)['values'][3] certificado = self.listagem.item(self.nodeId_1)['values'][4] meta = self.listagem.item(self.nodeId_1)['values'][5] resolvido = self.listagem.item(self.nodeId_1)['values'][6] data = self.listagem.item(self.nodeId_1)['values'][7] #Abre a nova janela self.mostrar_jan = Tk() #CONFIGURACOES ---- #Titulo self.mostrar_jan.title(titulo) #Tamanho da self.mostrar_janela self.mostrar_jan.geometry("500x450") #Cor de Fundo self.mostrar_jan.configure(background=cor_principal) #Nao redimensionar self.mostrar_jan.resizable(width=False, height=False) #Transparencia self.mostrar_jan.attributes("-alpha", 0.95) #Icone self.mostrar_jan.iconbitmap(default="Icons/icon.ico") x_l = 40 x_e = 200 y_i = 30 #Insere as labels de Informacoes #Local self.localLabel_ = Label(self.mostrar_jan, text="Local: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.localLabel_.place(x=x_l, y=y_i) self.localEntry_ = Label(self.mostrar_jan, text=local, font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_secundaria) self.localEntry_.place(x=x_e, y=y_i) #Solicitante self.solLabel_ = Label(self.mostrar_jan, text="Solicitante: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.solLabel_.place(x=x_l, y=y_i + 50) self.solEntry_ = Label(self.mostrar_jan, text=solicitante, font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_secundaria) self.solEntry_.place(x=x_e, y=y_i + 50) #Atendimento self.atendLabel_ = Label(self.mostrar_jan, text="Atendiemento: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.atendLabel_.place(x=x_l, y=y_i + 100) self.atendEntry_ = Label(self.mostrar_jan, text=atendimento, font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_secundaria) self.atendEntry_.place(x=x_e, y=y_i + 100) #Certificado self.certLabel_ = Label(self.mostrar_jan, text="Certificado: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.certLabel_.place(x=x_l, y=y_i + 150) self.certEntry_ = Label(self.mostrar_jan, text=certificado, font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_secundaria) self.certEntry_.place(x=x_e, y=y_i + 150) #Dispositivo Meta self.metaLabel_ = Label(self.mostrar_jan, text="Dispositivo Meta: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.metaLabel_.place(x=x_l, y=y_i + 200) self.meta_Entry_ = Label(self.mostrar_jan, text=meta, font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_secundaria) self.meta_Entry_.place(x=x_e, y=y_i + 200) #Problema Resolvido self.resolv_Label_ = Label(self.mostrar_jan, text="Resolvido: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.resolv_Label_.place(x=x_l, y=y_i + 250) self.resolv_Entry_ = Label(self.mostrar_jan, text=resolvido, font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_secundaria) self.resolv_Entry_.place(x=x_e, y=y_i + 250) #Data self.data_Label_ = Label(self.mostrar_jan, text="Data: ", font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_principal) self.data_Label_.place(x=x_l, y=y_i + 300) self.data_Entry_ = Label(self.mostrar_jan, text=data, font=fonte_Textos, anchor="w", fg=cor_contraste, bg=cor_secundaria) self.data_Entry_.place(x=x_e, y=y_i + 300) #Botao de excluir self.ex_button = Button(self.mostrar_jan, text="Excluir", width=20, bg=cor_principal, fg=cor_contraste, relief="raise", command=self.Excluir) self.ex_button.place(x=x_e - 25, y=y_i + 350) self.mostrar_jan.mainloop() except: pass def Sobre(self): messagebox.showinfo( title="SOBRE", message= "Software para controle de Suporte\n2021\nMeta Certificado Digital" ) def Excluir(self): #Abre o banco #self.banco = Banco() #Encontra o item no banco com base na ID do item selecionado x = self.banco.dados.query("Id == {} ".format(self.id_)) #Exlui o item do banco self.banco.dados = self.banco.dados.drop(x.index) self.banco.Atualiza() #Atualiza q quantidade de atendimentos self.qtd_atendimentos = self.banco.current self.qtd['text'] = self.qtd_atendimentos self.qtd_h = self.banco.dados.loc[self.banco.dados["Data"] == data].count() self.qtd_hj['text'] = self.qtd_h[0] #Atualiza a lista self.listagem.delete(self.nodeId_1) self.listagem.pack(side=LEFT) #Salva o banco self.banco.Save() #mensagem de sucesso messagebox.showinfo(title="Sucesso!", message="Cadastro Removido com Sucesso!") #Fecha a janela self.mostrar_jan.destroy() def Inserir(self): txt = "" #LOCAL local = self.localEntry.get().upper() if local == "": txt += "Local Inválido!\n" elif local not in lista_locais: add_local = messagebox.askyesno( title="Aviso!", message="Esse Local Não Está Cadastrado. Deseja Cadastrá-lo?") if add_local: lista_locais.append(local) self.localEntry.set_completion_list(lista_locais) else: self.localEntry.delete(0, END) return #SOLICITANTE solicitante = self.solEntry.get().upper() if solicitante not in lista_solicitantes: txt = txt + "Solicitante Inválido!\n" #ATENDIMENTO atendimento = self.atendEntry.get().upper() if atendimento == "": txt += "Atendimento Inválido!\n" elif atendimento not in lista_atendimentos: add_atend = messagebox.askyesno( title="Aviso!", message= "Esse Atendimento Não Está Cadastrado. Deseja Cadastrá-lo?") if add_atend: lista_atendimentos.append(atendimento) self.atendEntry.set_completion_list(lista_atendimentos) else: self.atendEntry.delete(0, END) #TIPO DE CERTIFICADO certificado = self.certEntry.get().upper() if certificado not in lista_certificados: txt = txt + "Tipo de Certificado Inválido!\n" #DISPOSITIVO DA META meta = "SIM" if not self.chkValueMeta.get(): meta = "NAO" #PROBLEMA RESOLVIDO resolv = "SIM" if not self.chkValueResol.get(): resolv = "NAO" #CASO TUDO ESTEJA CORRETO if txt == "": #CADASTRA NO BANCO DE DADOS #banco = Banco() ultimo = self.banco.current x = self.banco.dados["Id"] if ultimo: self.id_ = str(int(x[ultimo - 1]) + 1) else: self.id_ = str(1) nova_linha = [ self.id_, local, solicitante, atendimento, certificado, meta, resolv, data ] self.banco.dados.loc[self.banco.current] = nova_linha self.banco.Atualiza() #banco.Save() #MOSTRA MENSAGEM DE SUCESSO messagebox.showinfo(title="SUCESSO!", message="Atendimento Cadastrado com Sucesso!") #LIMPA AS SELEÇÕES E TEXTOS self.localEntry.delete(0, END) self.solEntry.delete(0, END) self.atendEntry.delete(0, END) self.certEntry.delete(0, END) self.chkValueMeta.set(False) self.chkValueResol.set(False) #ALTERA A QUANTIDADE DE ATENDIMENTOS self.qtd_atendimentos = self.banco.current self.qtd['text'] = self.qtd_atendimentos self.qtd.place(relx=0.5, rely=0.5, anchor=CENTER) self.qtd_h = self.banco.dados.loc[self.banco.dados["Data"] == data].count() self.qtd_hj['text'] = self.qtd_h[0] self.qtd_hj.place(relx=0.5, rely=0.5, anchor=CENTER) #ALTERA A LISTAGEM self.listagem.insert( '', 'end', values=tuple(self.banco.dados.loc[self.qtd_atendimentos - 1])) self.listagem.pack(side=LEFT) else: #CASO DE ERRADO messagebox.showerror(title="Impossível Cadastrar Atendimento", message=txt)
def create_window(): window = Tk() window.title("EDAutopilot Settings") window.geometry('280x300') window.resizable(False, False) logger.debug(os.name) if "nt" == os.name: from dev_autopilot import resource_path window.iconbitmap(resource_path('src/logo.ico')) defaults = getOptions() def on_closing(): if unsaved(): confirm = askyesnocancel( title="Save On Close", message="Do you want to save before closing?", default=YES, icon='warning') if confirm: on_save() elif confirm is None: return False global curr_window curr_window = None window.destroy() window.protocol("WM_DELETE_WINDOW", on_closing) def toggleFSS(): if dsState.get(): fssCheck['state'] = NORMAL else: fssCheck['state'] = DISABLED dsState = BooleanVar() dsState.set(defaults['DiscoveryScan']) dsCheck = Checkbutton(window, text='Automatic Discovery Scan', var=dsState, command=toggleFSS) dsCheck.place(relx=0.02, rely=0.02) fssState = BooleanVar() fssState.set(defaults['AutoFSS']) fssCheck = Checkbutton( window, text='Automatic FSS Scan\n (Currently waits for user to operate FSS)', var=fssState) fssCheck.place(relx=0.05, rely=0.09) startKeyLbl = Label(window, text='Start EDAutopilot Key:') startKeyLbl.place(relx=0.02, rely=0.23) def on_startKey(): getKeyForBtn(startKeyBtn) startKeyBtn = Button(window, text=defaults['StartKey'], command=on_startKey, width=20) startKeyBtn.place(relx=0.46, rely=0.22) startKeyLbl = Label(window, text='End EDAutopilot Key:') startKeyLbl.place(relx=0.02, rely=0.33) def on_endKey(): getKeyForBtn(endKeyBtn) endKeyBtn = Button(window, text=defaults['EndKey'], command=on_endKey, width=20) endKeyBtn.place(relx=0.46, rely=0.32) rtLbl = Label(window, text='Refuel threshold percentage:') rtLbl.place(relx=0.02, rely=0.43) def callback(strnum): return ((str.isdigit(strnum)) and (len(strnum) <= 3) and (0 <= int(strnum) <= 100)) or strnum == "" vcmd = (window.register(callback)) refuelThreshold = Entry(window, validate='all', validatecommand=(vcmd, '%P'), width=10, justify='center') refuelThreshold.insert(0, defaults['RefuelThreshold']) refuelThreshold.place(relx=0.62, rely=0.44) def get_refuel_threshold(entry): if not entry: return defaults['RefuelThreshold'] return str(int( entry.get())) # Just to be triply sure it's an int in str form def unsaved(): return str(fssState.get()) != defaults['AutoFSS'] or str(dsState.get()) != defaults['DiscoveryScan'] or \ startKeyBtn['text'] != defaults['StartKey'] or endKeyBtn['text'] != defaults['EndKey'] or \ get_refuel_threshold(refuelThreshold) != defaults['RefuelThreshold'] def on_save(): if not unsaved(): return if str(fssState.get()) != defaults['AutoFSS']: setOption('AutoFSS', fssState.get()) if str(dsState.get()) != defaults['DiscoveryScan']: setOption('DiscoveryScan', dsState.get()) if startKeyBtn['text'] != defaults['StartKey']: setOption('StartKey', startKeyBtn['text']) if endKeyBtn['text'] != defaults['EndKey']: setOption('EndKey', endKeyBtn['text']) if get_refuel_threshold( refuelThreshold) != defaults['RefuelThreshold']: setOption('RefuelThreshold', get_refuel_threshold(refuelThreshold)) saveBtn = Button(window, text="Save Settings", command=on_save) saveBtn.place(relx=0.70, rely=0.90) return window
class MainWin: def __init__(self, parent): def Help(): t = Toplevel() t.title("Help") t.label = Label(t, text='This small program will read the currently playing song from VLC and copy it to a folder of your choosing.') t.label.pack() t.label2 = Label(t, text='Great for easily making playlists from large libraries!') t.label2.pack() t.label3 = Label(t, text='') t.label3.pack() t.label4 = Label(t, text='') t.label4.pack() t.label5 = Label(t, text='Before you can use this program you need to make sure you have a few settings set correctly in VLC.') t.label5.pack() t.label6 = Label(t, text='Make sure you pick "All" for "Show Settings" in the bottom left of your Preferences') t.label6.pack() t.label7 = Label(t, text='First check the "Web" box at Tools -> Preferences -> Interface -> Main interfaces') t.label7.pack() t.label8 = Label(t, text='Next set your password at Tools -> Preferences -> Interface -> Main interfaces -> Lua -> Lua HTTP') t.label8.pack() t.label9 = Label(t, text='Finally, go to Tools -> Preferences -> Input / Codecs and scroll down to Network Settings and set your "HTTP Server Port"') t.label9.pack() t.label10 = Label(t, text='Save your settings and restart VLC and you should be good to go!') t.label10.pack() def Browse(root): root.withdraw() self.dirname = tkinter.filedialog.askdirectory(parent=root, initialdir="/", title='Choose a directory to copy to') return self.dirname def CheckPort(host, port): """Warns user if port is not open.""" with closing(socket.socket(socket.AF_INET, socket.SOCK_STREAM)) as sock: if sock.connect_ex((host, port)) != 0: tkinter.messagebox.showinfo('Error', 'Either VLC or the Port is not open!') self.startConnection.set(False) return False else: return True def ReadSettings(): Config = configparser.ConfigParser() if isfile('settings.ini') is True: Config.read('settings.ini') self.pswrd = Config.get('Settings', 'vlc password') self.port = Config.get('Settings', 'vlc http port') self.renameMethod = Config.get('Settings', 'renaming method') self.dirname = Config.get('Settings', 'new directory') self.overwriteAlways.set(Config.getboolean('Settings', 'overwrite always')) self.copyhotkey = Config.get('Settings', 'copy hotkey') Config.remove_section('Settings') return self.pswrd, self.port, self.renameMethod, self.dirname, self.overwriteAlways, self.copyhotkey def SaveSettings(pswrd, port, renameMethod, dirname, overwriteAlways, copyhotkey): Config = configparser.ConfigParser() cfgfile = open("settings.temp.ini", 'w+') Config.add_section('Settings') Config.set('Settings', 'vlc password', self.pswrd) Config.set('Settings', 'vlc http port', self.port) Config.set('Settings', 'renaming method', self.renameMethod) Config.set('Settings', 'new directory', self.dirname) Config.set('Settings', 'activate hotkey', str(self.activateHotkey.get())) Config.set('Settings', 'overwrite always', str(self.overwriteAlways.get())) Config.set('Settings', 'copy hotkey', self.copyhotkey) Config.write(cfgfile) time.sleep(.1) if isfile('settings.ini'): os.remove('settings.ini') cfgfile.close() os.rename('settings.temp.ini', 'settings.ini') def SetServerPass(): self.pswrd = self.PassEntry.get() return self.pswrd def SetServerPort(): if is_number(self.PortEntry.get()) is True: self.port = self.PortEntry.get() return self.port else: tkinter.messagebox.showinfo('Error', 'Only numbers allowed!') def SetRenameMethod(): if is_number(self.SetRenameEntry.get()) is False or int(self.SetRenameEntry.get()) > 6 or int(self.SetRenameEntry.get()) < 1: tkinter.messagebox.showinfo('Error', 'Only numbers 1-6 allowed!') else: self.renameMethod = self.SetRenameEntry.get() return self.renameMethod def SetHotkey(): hotkey = str(keyboard.read_key()) end = hotkey.rfind(' down') self.copyhotkey = hotkey[14:end] t = Toplevel() t.title("New Hotkey") t.label = Label(t, text='You chose: ' + self.copyhotkey) t.label.pack() return self.copyhotkey def CheckSettings(): if is_number(self.renameMethod) is True and int(self.renameMethod) > 0 and int(self.renameMethod) < 7: if is_number(self.port) is True: if self.pswrd != '': if self.dirname != '': return True else: return False else: return False else: return False else: return False def CheckVLC(): check = rwm.OpenProcess('vlc.exe') if check is not None: return 'Opened!' else: self.startConnection.set(False) return 'Not Open' def RenameMethods(): t = Toplevel() t.title("Rename Methods") t.label = Label(t, text='Here are your options for renaming!') t.label.pack() t.label2 = Label(t, text='1. Artist - Title') t.label2.pack() t.label3 = Label(t, text='2. Album - Title') t.label3.pack() t.label4 = Label(t, text='3. Artist - Album - Title') t.label4.pack() t.label5 = Label(t, text='4. Album - Artist - Title') t.label5.pack() t.label6 = Label(t, text='5. Title') t.label6.pack() t.label7 = Label(t, text='6. Don\'t Rename') t.label7.pack() def CurrentSong(): """When called, grabs info from VLC to rename the new file.""" status = vlcxml('status') if status is not None: startTitle = status.find("<info name='title'>") startArtist = status.find("<info name='artist'>") startAlbum = status.find("<info name='album'>") startStatus = status.find("<state>") fromstartTitle = status[startTitle:] fromstartArtist = status[startArtist:] fromstartAlbum = status[startAlbum:] fromstartStatus = status[startStatus:] endTitle = fromstartTitle.find("</info>") endArtist = fromstartArtist.find("</info>") endAlbum = fromstartAlbum.find("</info>") endStatus = fromstartStatus.find("</state>") title = fixName(fromstartTitle[19:endTitle]) artist = fixName(fromstartArtist[20:endArtist]) album = fixName(fromstartAlbum[19:endAlbum]) status = fixName(fromstartStatus[7:endStatus]) self.currentstatus = (status[0].upper() + status[1:]) if (artist + " - " + album + ' - ' + title) == " - - ": self.currentsong = 'No info available' self.currentartist = 'No info available' self.currentalbum = 'No info available' self.currenttitle = 'No info available' else: self.currentsong = (artist + " - " + album + ' - ' + title) self.currentartist = artist self.currentalbum = album self.currenttitle = title else: return None def vlcxml(page): if self.startConnection.get() is True: """Grabs the xml needed from VLC's HTTP server.""" s = requests.Session() s.auth = ('', self.pswrd) # Username is blank, just provide the password try: r = s.get('http://localhost:' + self.port + '/requests/' + str(page) + '.xml', verify=False) return r.text except requests.exceptions.RequestException as e: self.startConnection.set(False) tkinter.messagebox.showinfo('Error', 'Something went wrong! Check your settings and make sure VLC is open! \n\n' + str(e)) return None else: return None def is_number(num): """Given string 'num', returns true if 'num' is numeric.""" try: int(num) return True except ValueError: return False def fixName(t): """Given string 't', returns a filtered version.""" while t != (t.replace("&", "&").replace("<", "<").replace(">", ">") .replace("'", "'").replace('"', '"')): t = (t.replace("&", "&").replace("<", "<").replace(">", ">") .replace("'", "'").replace('"', '"')) return t def copyFile(): if CheckSettings() is True and CheckPort('127.0.0.1', int(self.port)) is True: """When called, grabs info from VLC to copy file to new path.""" x1 = vlcxml('status') start = x1.find('<currentplid>') end = x1.find('</currentplid>') plid = x1[start + 13:end] if plid is not None: x2 = vlcxml('playlist') start2 = x2.find('id="' + plid + '" duration=') fromStart = x2[start2:] start3 = fromStart.find('uri=') end2 = fromStart.find('/>') start3 = fromStart.find('uri=') end2 = fromStart.find('/>') filePath = fromStart[start3 + 13:end2 - 19] bugstart = x2.find(filePath) # Getting around VLC bug block bug1 = x2[bugstart:] bugend = bug1.find('/>') bugFixin = x2[:(bugstart + bugend)] bugg = bugFixin.count('vlc://nop') if bugg > 0: plid = str(int(plid) + bugg) start2 = x2.find('id="' + plid + '" duration=') fromStart = x2[start2:] start3 = fromStart.find('uri=') end2 = fromStart.find('/>') filePath = fromStart[start3 + 13:end2 - 1] # Bug block end convertURL = unquote(filePath) fileNameStart = convertURL.rfind('/') fileName = convertURL[fileNameStart:] newFile = (self.dirname + fileName) extensionStart = fileName.rfind('.') extension = fileName[extensionStart:] self.localtime = time.strftime("%H:%M:%S", time.localtime()) time.sleep(.1) try: if isfile(newFile) is True: if self.overwriteAlways.get() is True: os.remove(newFile) renameResponse = reName() if renameResponse is not None: if isfile(self.dirname + '/' + renameResponse + extension) is True: if self.overwriteAlways.get() is True: os.remove(self.dirname + '/' + renameResponse + extension) copy2(convertURL, self.dirname) os.rename(newFile, (self.dirname + '/' + renameResponse + extension)) self.ProgStatusVarLabel.config(text='Successful Overwrite at ' + self.localtime) else: self.ProgStatusVarLabel.config(text='File Already Exists! ' + self.localtime) else: copy2(convertURL, self.dirname) os.rename(newFile, (self.dirname + '/' + renameResponse + extension)) self.ProgStatusVarLabel.config(text='Successful Overwrite at ' + self.localtime) else: copy2(convertURL, self.dirname) self.ProgStatusVarLabel.config(text='Successful Copy at ' + self.localtime) else: self.ProgStatusVarLabel.config(text='File Already Exists! ' + self.localtime) else: renameResponse = reName() if renameResponse is not None: if isfile(self.dirname + '/' + renameResponse + extension) is True: if self.overwriteAlways.get() is True: os.remove(self.dirname + '/' + renameResponse + extension) copy2(convertURL, self.dirname) os.rename(newFile, (self.dirname + '/' + renameResponse + extension)) self.ProgStatusVarLabel.config(text='Successful Overwrite at ' + self.localtime) else: self.ProgStatusVarLabel.config(text='File Already Exists! ' + self.localtime) else: copy2(convertURL, self.dirname) os.rename(newFile, (self.dirname + '/' + renameResponse + extension)) self.ProgStatusVarLabel.config(text='Successful Copy at ' + self.localtime) else: copy2(convertURL, self.dirname) self.ProgStatusVarLabel.config(text='Successful Copy at ' + self.localtime) except PermissionError: self.ProgStatusVarLabel.config(text="File in use! Can't Delete " + self.localtime) elif CheckSettings() is False: tkinter.messagebox.showinfo('Error', 'Settings not correct, check your settings!') self.startConnection.set(False) def reName(): """When called, grabs info from VLC to rename the new file.""" status = vlcxml('status') startTitle = status.find("<info name='title'>") startArtist = status.find("<info name='artist'>") startAlbum = status.find("<info name='album'>") fromstartTitle = status[startTitle:] fromstartArtist = status[startArtist:] fromstartAlbum = status[startAlbum:] endTitle = fromstartTitle.find("</info>") endArtist = fromstartArtist.find("</info>") endAlbum = fromstartAlbum.find("</info>") title = fixName(fromstartTitle[19:endTitle]) artist = fixName(fromstartArtist[20:endArtist]) album = fixName(fromstartAlbum[19:endAlbum]) if int(self.renameMethod) > 0 and int(self.renameMethod) < 7: if self.renameMethod == "1": return str(artist + ' - ' + title) elif self.renameMethod == "2": return str(album + ' - ' + title) elif self.renameMethod == "3": return str(artist + ' - ' + album + ' - ' + title) elif self.renameMethod == "4": return str(album + ' - ' + artist + ' - ' + title) elif self.renameMethod == "5": return str(title) elif self.renameMethod == "6": return None def HotKeyBind(): if self.activateHotkey.get() is True: keyboard.add_hotkey(self.copyhotkey, copyFile) else: keyboard.clear_all_hotkeys() # Variables self.pswrd = '' self.port = '' self.renameMethod = '6' self.dirname = '' self.activateHotkey = BooleanVar() self.overwriteAlways = BooleanVar() self.startConnection = BooleanVar() self.copyhotkey = '' ReadSettings() self.currentsong = 'Nothing Playing!' self.currentartist = 'Nothing Playing!' self.currentalbum = 'Nothing Playing!' self.currenttitle = 'Nothing Playing!' self.currentstatus = 'Not Open' self.photo = PhotoImage(file='vlc banner.png') self.photo_label = Label(image=self.photo) self.photo_label.place(x=0, y=0) self.photo_label.image = self.photo self.seperator = Separator(parent, orient="horizontal") self.seperator.place(relwidth=1.0, y=131) Style().configure(self.seperator, background='#000') self.PassLabel = Label(parent, text='Vlc Server Password:'******'Times', 12), fg='black') self.PassLabel.place(x=5, y=145) self.PortLabel = Label(parent, text='Vlc Server Port:', font=('Times', 12), fg='black') self.PortLabel.place(x=40, y=195) self.RenMethLabel = Label(parent, text='Rename Method:', font=('Times', 12), fg='black') self.RenMethLabel.place(x=30, y=245) self.DirLabel = Label(parent, text='New Directory:', font=('Times', 12), fg='black') self.DirLabel.place(x=8, y=280) self.VLCStatusLabel = Label(parent, text='VLC Status:', font=('Times', 12), fg='black') self.VLCStatusLabel.place(x=27, y=305) self.ProgStatusLabel = Label(parent, text='Last Action:', font=('Times', 12), fg='black') self.ProgStatusLabel.place(x=27, y=330) self.CurrentSongLabel = Label(parent, text=('Current Song'), font=('Times', 12), fg='black') self.CurrentSongLabel.place(x=50, y=360) f = font.Font(self.CurrentSongLabel, self.CurrentSongLabel.cget("font")) f.configure(underline=True) self.CurrentSongLabel.configure(font=f) self.CurrentArtistLabel = Label(parent, text='Artist:', font=('Times', 12), fg='black') self.CurrentArtistLabel.place(x=17, y=385) self.CurrentAlbumLabel = Label(parent, text='Album:', font=('Times', 12), fg='black') self.CurrentAlbumLabel.place(x=10, y=410) self.CurrentTitleLabel = Label(parent, text='Title:', font=('Times', 12), fg='black') self.CurrentTitleLabel.place(x=24, y=435) self.PassVarLabel = Label(parent, text=self.pswrd, font=('Times', 12), fg='black') self.PassVarLabel.place(x=140, y=145) self.PortVarLabel = Label(parent, text=self.port, font=('Times', 12), fg='black') self.PortVarLabel.place(x=140, y=195) self.RenMethVarLabel = Label(parent, text=self.renameMethod, font=('Times', 12), fg='black') self.RenMethVarLabel.place(x=140, y=245) self.DirVarLabel = Label(parent, text=self.dirname, font=('Times', 12), fg='black') self.DirVarLabel.place(x=105, y=280) self.VLCStatusVarLabel = Label(parent, text='Not Open', font=('Times', 12), fg='black') self.VLCStatusVarLabel.place(x=105, y=305) self.ProgStatusVarLabel = Label(parent, text='Nothing yet!', font=('Times', 12), fg='black') self.ProgStatusVarLabel.place(x=105, y=330) self.CurrentArtistVarLabel = Label(parent, text=self.currentartist, font=('Times', 12), fg='black') self.CurrentArtistVarLabel.place(x=60, y=385) self.CurrentAlbumVarLabel = Label(parent, text=self.currentalbum, font=('Times', 12), fg='black') self.CurrentAlbumVarLabel.place(x=60, y=410) self.CurrentTitleVarLabel = Label(parent, text=self.currenttitle, font=('Times', 12), fg='black') self.CurrentTitleVarLabel.place(x=60, y=435) self.PassEntry = Entry(parent) self.PassEntry.place(w=120, h=35, x=240, y=140) self.PortEntry = Entry(parent) self.PortEntry.place(w=120, h=35, x=240, y=190) self.SetRenameEntry = Entry(parent) self.SetRenameEntry.place(w=120, h=35, x=240, y=240) def Refresh(): CurrentSong() self.PassVarLabel.config(text=self.pswrd) self.PortVarLabel.config(text=self.port) self.RenMethVarLabel.config(text=self.renameMethod) self.DirVarLabel.config(text=self.dirname) if self.startConnection.get() is False: self.CurrentArtistVarLabel.config(text='Start Connection to get info!') self.CurrentAlbumVarLabel.config(text='Start Connection to get info!') self.CurrentTitleVarLabel.config(text='Start Connection to get info!') self.VLCStatusVarLabel.config(text=CheckVLC()) else: self.CurrentArtistVarLabel.config(text=self.currentartist) self.CurrentAlbumVarLabel.config(text=self.currentalbum) self.CurrentTitleVarLabel.config(text=self.currenttitle) self.VLCStatusVarLabel.config(text=self.currentstatus) parent.after(500, Refresh) self.PassButton = Button(parent, text='Set', command=SetServerPass, font=('Times', 10)) self.PassButton.place(w=120, h=35, x=380, y=140) self.PortButton = Button(parent, text='Set', command=SetServerPort, font=('Times', 10)) self.PortButton.place(w=120, h=35, x=380, y=190) self.SetRenameButton = Button(parent, text='Set', command=SetRenameMethod, font=('Times', 10)) self.SetRenameButton.place(w=120, h=35, x=380, y=240) self.BrowseButton = Button(parent, text='Browse', command=lambda: Browse(Tk()), font=('Times', 10)) self.BrowseButton.place(w=120, h=35, x=570, y=290) self.SetHotkeyButton = Button(parent, text='Set Hotkey', command=SetHotkey, font=('Times', 10)) self.SetHotkeyButton.place(w=120, h=35, x=570, y=340) self.CopyButton = Button(parent, text='Copy File', command=copyFile, font=('Times', 10)) self.CopyButton.place(w=120, h=35, x=570, y=425) self.HelpButton = Button(parent, text='Setup', command=Help, font=('Times', 10)) self.HelpButton.place(w=120, h=35, x=570, y=140) self.HelpButton = Button(parent, text='Save Settings', command=lambda: SaveSettings(self.pswrd, self.port, self.renameMethod, self.dirname, self.overwriteAlways, self.copyhotkey), font=('Times', 10)) self.HelpButton.place(w=120, h=35, x=570, y=190) self.RenameMethodsButton = Button(parent, text='Renaming Methods', command=RenameMethods, font=('Times', 10)) self.RenameMethodsButton.place(w=120, h=35, x=570, y=240) self.ActivHotkeyCheckbox = Checkbutton(parent, text='Activate Hotkey', variable=self.activateHotkey, command=HotKeyBind, font=('Times', 10)) self.ActivHotkeyCheckbox.place(x=420, y=310) self.OvrAlwCheckbox = Checkbutton(parent, text='Overwrite New Files', variable=self.overwriteAlways, font=('Times', 10)) self.OvrAlwCheckbox.place(x=420, y=330) self.StartConCheckbox = Checkbutton(parent, text='Start Connection', variable=self.startConnection, font=('Times', 10)) self.StartConCheckbox.place(x=420, y=350) Refresh()
class LoginPanel: def __init__(self): #图形界面区域 self.root = Tk() self.root.title('登陆0.0.1') self.root.geometry('450x350+400+200') #头像区域 self.head = Canvas(self.root) #self.head.create_oval(165, 15, 265, 115) self.head.place(x=5, y=5, heigh=120, width=440) #输入区域 self.input = Canvas(self.root, bg='#ffffff') self.input.place(x=5, y=130, heigh=220, width=440) #登陆按钮 self.loginbutton = Button(self.input, text='登陆', bg='#4fcffd', command=self.loginbuttonclickevent) self.loginbutton.place(x=100, y=160, heigh=40, width=240) #账号输入框 self.accountinput = Entry(self.input, font=("仿宋", 16, "bold")) self.accountinput.place( x=130, y=60, heigh=30, width=210, ) #密码输入框 self.passwordinput = Entry(self.input, font=("仿宋", 16, "bold"), show='*') self.passwordinput.place(x=130, y=95, heigh=30, width=210) #自动登录checkbutton self.autologinvar = BooleanVar() self.autologincheck = Checkbutton( self.input, text='自动登录', variable=self.autologinvar, command=self.autologincheckbuttonstatusevent) self.autologincheck.place(x=100, y=130, heigh=15, width=80) #记住密码 self.remberpasswordvar = BooleanVar() self.remberpasswordcheck = Checkbutton( self.input, text='记住密码', variable=self.remberpasswordvar, command=self.remberpasswordcheckbuttonstatusevent) self.remberpasswordcheck.place(x=190, y=130, heigh=15, width=80) #找回密码 self.findpasswordbutton = Button(self.input, text='找回密码', bg='white') self.findpasswordbutton.place(x=290, y=130, heigh=15, width=50) #注册账号 self.registerbutton = Button(self.input, text='注册账号', bg='white', command=self.registerbuttonclickevent) self.registerbutton.place(x=10, y=190, heigh=15, width=50) #准备工作 #1、获取复选框状态(自动登录,记住密码) #2、如果自动登录已勾选,获取最近一次登录账号及对应密码输入框并直接登录,摧毁当前窗口,打开主界面窗口, #3、如果仅勾选记住密码,则仅获取最近一次登录账号及对应密码输入框,等待用户操作 #对应事件监听区域 #登录按钮点击事件 def loginbuttonclickevent(self): account = self.accountinput.get().strip().replace(' ', '') self.accountinput.delete(0, END) self.accountinput.insert(END, account) print(account) password = self.passwordinput.get().strip().replace(' ', '') self.passwordinput.delete(0, END) self.passwordinput.insert(END, password) print(password) if len(account) < 8 or len(password) < 8 or not account.isdigit(): messagebox.showinfo('登录失败', '查无此号') return -1 for c in password: if ord(c) > 255: messagebox.showinfo('登录失败', '密码错误\n( ⊙ o ⊙ )') return -2 print('等待连接数据库。。。') db = pymysql.connect('localhost', 'root', '123456', 'database1') cursor = db.cursor() print('连接成功') sql = "select pwd,nickname from user_info where id=%s" % account # print('sql',sql) # cursor.execute("select * from user_info") try: cursor.execute(sql) results = cursor.fetchall()[0] print('results', results) if results[0] == password: messagebox.showinfo('登录成功', '登录成功') db.close() self.root.destroy() mainpanel = MainPanel(results[1]) mainpanel.run() return 0 messagebox.showinfo('登录失败', '账号密码不匹配') except: print('登录抛出异常') db.rollback() db.close() return -3 #登录操作 #登录成功,自动保存账号,并根据记住密码复选框状态决定是否保存密码 #自动登录勾选事件 def autologincheckbuttonstatusevent(self): print('自动登录状态:', self.autologinvar.get()) #如果为自动登录状态,则记住密码为勾选状态 if self.autologinvar.get() == True: self.remberpasswordvar.set(True) #记住密码勾选事件 def remberpasswordcheckbuttonstatusevent(self): print('记住密码状态:', self.remberpasswordvar.get()) #注册账号按钮点击事件(未完成) def registerbuttonclickevent(self): register = RegisterPanel() register.run() #找回密码按钮点击事件(未完成) def findpasswordbuttonclickevent(self): pass def run(self): self.root.mainloop() pass
class Gui(Frame): def __init__(self, master): Frame.__init__(self, master) self.pack() global buienradarAPI #define master variables (geometry and background) master.geometry('{}x{}'.format(1600, 900)) master.resizable(width=False, height=False) master.filename = PhotoImage(file="achtergrond.png") master.background_label = Label(master, image=master.filename) master.background_label.place(x=0, y=0, relwidth=1, relheight=1) #define variables needed to get information from checkboxes in the gui self.IntVarWaterHeight = IntVar() self.IntVarRainLevel = IntVar() self.IntVarWindDirection = IntVar() self.IntVarWindSpeed = IntVar() #define graph dimensions self.graphHeight = 178 self.graphWidth = 698 self.startYvar = self.graphHeight + 2 self.startYvar = self.graphHeight + 2 self.waterLevelCoords = [0, 0, 0, 0, 0, 0, 0, 0] self.rainLevelCoords = [0, 0, 0, 0, 0, 0, 0, 0] self.windDirectionCoords = [0, 0, 0, 0, 0, 0, 0, 0] self.windSpeedCoords = [0, 0, 0, 0, 0, 0, 0, 0] self.keringStatus = 'OPEN' #define frame for gui box = Frame(master, relief=SUNKEN, borderwidth=2).pack() #define gui elements (graphs, buttons, checkboxes, sliders) self.waterLevelGraph = Canvas(box, height=self.graphHeight, width=self.graphWidth, relief=SUNKEN, borderwidth=1) self.waterLevelGraph.place(x=10, y=30) self.rainLevelGraph = Canvas(box, height=self.graphHeight, width=self.graphWidth, relief=SUNKEN, borderwidth=1) self.rainLevelGraph.place(x=10, y=250) self.windDirectionGraph = Canvas(box, height=self.graphHeight, width=self.graphWidth, relief=SUNKEN, borderwidth=1) self.windDirectionGraph.place(x=10, y=470) self.windSpeedGraph = Canvas(box, height=self.graphHeight, width=self.graphWidth, relief=SUNKEN, borderwidth=1) self.windSpeedGraph.place(x=10, y=690) self.statusLabel = Label(box, text=self.keringStatus, font=('Helvetica', 16), relief=SUNKEN, borderwidth=5) self.statusLabel.place(x=890, y=50, width=700, height=100) self.exitButton = Button(box, text='Afsluiten', font=('Helvetica', 16), command=exit, borderwidth=2) self.exitButton.place(x=1245, y=800, height=90, width=345) self.historyButton = Button(box, text='Historie', font=('Helvetica', 16), borderwidth=2, command=lambda: self.showHistoryWindow()) self.historyButton.place(x=890, y=800, height=40, width=345) self.historyStartEntry = Entry(box, borderwidth=2) self.historyStartEntry.insert(0, 'jjjj-mm-dd uu:mm') self.historyStartEntry.place(x=890, y=850, height=40, width=170) self.historyEndEntry = Entry(box, borderwidth=2) self.historyEndEntry.insert(0, 'jjjj-mm-dd uu:mm') self.historyEndEntry.place(x=1065, y=850, height=40, width=170) self.waterLevelSlider = Scale(box, from_=0, to=75, resolution=25, relief=RAISED) self.waterLevelSlider.place(x=910, y=230, height=265) self.waterLevelCheck = Checkbutton(box, variable=self.IntVarWaterHeight) self.waterLevelCheck.place(x=1120, y=350) self.rainLevelSlider = Scale(box, from_=0, to=250, resolution=10, relief=RAISED) self.rainLevelSlider.place(x=910, y=505, height=265) self.rainLevelCheck = Checkbutton(box, variable=self.IntVarRainLevel) self.rainLevelCheck.place(x=1140, y=626) self.windDirectionSlider = Scale(box, from_=0, to=350, resolution=10, relief=RAISED) self.windDirectionSlider.place(x=1245, y=230, height=265) self.windSpeedSlider = Scale(box, from_=0, to=35, relief=RAISED) self.windSpeedSlider.place(x=1245, y=505, height=265) self.windSpeedCheck = Checkbutton(box, variable=self.IntVarWindSpeed) self.windSpeedCheck.place(x=1505, y=485) self.applyConfigButton = Button(box, text='toepassen', font=('Helvetica', 16), command=self.updateConfig) self.applyConfigButton.place(x=1462, y=180, height=30, width=117) #function used to test checkboxes def getConfig(self): waterHeightConfigCheck = self.IntVarWaterHeight.get() rainLevelConfigCheck = self.IntVarRainLevel.get() windDirectionConfigCheck = self.IntVarWindDirection.get() windSpeedConfigCheck = self.IntVarWindSpeed.get() checksList = [] checksList.append(waterHeightConfigCheck) checksList.append(rainLevelConfigCheck) checksList.append(windDirectionConfigCheck) checksList.append(windSpeedConfigCheck) return checksList #function use to create window with title and text as argument def create_window(self, title, text): t = Toplevel(self) t.wm_title(title) i = Text(t, relief="flat", height=50, width=93) i.insert(1.0, text) i.config(state='disabled') print(text) i.pack() #function used to show the historywindow def showHistoryWindow(self): string = self.getHistoryString() self.create_window('Historie', string) #function used to format the data from the database into a string for the database def getHistoryWindowTextString(self, data): formatString = '| {:17}| {:9}| {:12}| {:11}| {:13}| {:7}| {:9}|' string = '' titles = formatString.format('Tijd', 'Status', 'Waterstand', 'Windkracht', 'Windrichting', 'Server', 'Neerslag') string += titles + '\n' for item in data: string += formatString.format( data[data.index(item)]['Tijd'], data[data.index(item)]['Status'], str(data[data.index(item)]['Waterstand']), str(data[data.index(item)]['Windkracht']), str(data[data.index(item)]['Windrichting']), str(data[data.index(item)]['Instantie']), str(data[data.index(item)]['Neerslag'])) + '\n' return string #function used to generate the textstring for the history window def getHistoryString(self): self.startEntryString = self.historyStartEntry.get() self.endEntryString = self.historyEndEntry.get() returnValue = 'beginwaarde' if validDateString(self.startEntryString) == True: if validDateString(self.endEntryString) == True: if time.mktime( time.strptime(self.startEntryString, '%Y-%m-%d %H:%M')) < time.mktime( time.strptime( self.endEntryString, '%Y-%m-%d %H:%M')): dateTuple = (self.startEntryString, self.endEntryString) historyData = database.getHistory(dateTuple) returnValue = self.getHistoryWindowTextString(historyData) else: returnValue = 'Begintijd gelijk aan of later dan eindtijd' print(validDateString(self.endEntryString)) else: returnValue = 'Eindtijd onjuist' else: returnValue = 'Begintijd onjuist' print('functie doorlopen') print(returnValue) return returnValue #function used to read config from the GUI and write to file def updateConfig(self): print('config updated') if self.IntVarWaterHeight.get() == 0: waterheightParameter = '-' else: waterheightParameter = self.waterLevelSlider.get() if self.IntVarWindSpeed.get() == 0: windSpeedParameter = '-' else: windSpeedParameter = self.windSpeedSlider.get() if self.IntVarRainLevel.get() == 0: rainLevelParameter = '-' else: rainLevelParameter = self.rainLevelSlider.get() windDirectionParameter = self.windDirectionSlider.get() writeParameters('./parameters.json', windDirectionParameter, windSpeedParameter, waterheightParameter, rainLevelParameter) #function used to update the list with y-coordinates for the tkinter canvaess def updateYCoordList(self, list, type): if type == 'rainLevel': list.append(self.getRainLevelYCoord()) list.remove(list[0]) elif type == 'waterLevel': list.append(self.getWaterLevelYCoord()) list.remove(list[0]) elif type == 'windDirection': list.append(self.getWindDirectionYCoord()) list.remove(list[0]) elif type == 'windSpeed': list.append(self.getWindSpeedYCoord()) list.remove(list[0]) else: list.append(36) list.remove(list[0]) return list #function used to draw a graph using tkinter canvas module with a list of y-coordinates and a canvas as arguments def drawGraph(self, list, canvas): canvas.delete('all') startX = 0 for index in range(len(list) - 1): startY = self.startYvar - list[index] try: endY = self.startYvar - list[index + 1] except: print('error') pass endX = startX + 100 canvas.create_line(startX, startY, endX, endY) startX += 100 #function used to update graph with graph type and update interval as arguments def updateGraph(self, list, canvas, type, miliseconds): self.drawGraph(self.updateYCoordList(list, type), canvas) canvas.after(miliseconds, self.updateGraph, list, canvas, type, miliseconds) #function used to update statuslabel ever quarter of a second def updateStatusLabel(self, label): text = self.getKeringStatus() label.configure(text=text) label.after(250, self.updateStatusLabel, label) #function used to get the status of the kering from the gpio system def getKeringStatus(self): try: data = serverFunctions.gpioRequest() statusString = 'status:' + data[1] return statusString except: return 'ERROR' #function used to generate y-coordinate for rainFall def getRainLevelYCoord(self): rainLevel = buienradarAPI['regenMMPU'] if rainLevel == '-': rainLevel = 0 rainLevelY = int(float(rainLevel) * 1.388888888888889) return rainLevelY #function used to generate y-coordinate for wind speed def getWindSpeedYCoord(self): windSpeed = buienradarAPI['windsnelheidMS'] windSpeedY = int(float(windSpeed) * 5) return windSpeedY #function used to generate y-coordinate for wind direction def getWindDirectionYCoord(self): windDirection = buienradarAPI['windrichtingGR'] windDirectionY = int(float(windDirection) * 0.4) return windDirectionY #function used to generate y-coordinate for water level def getWaterLevelYCoord(self): data = serverFunctions.gpioRequest() return data[0] * 2
def show(self): """ Init and show the window. """ # init and config self.window = Tk() self.window.title("Configurations") self.window.resizable(False, False) self.window.configure(bg="#2c2825") # center the window self.center_window() # main label txt1 = Label(self.window, text="Please choose an algorithm", fg="#cfaf4f", bg="#2c2825") txt1.place(x=22, y=1) # the three buttons b1 = Button( self.window, text="A*", command=lambda: self.choose(0), height=1, width=6, bg="#cfaf4f", fg="black", ) b2 = Button( self.window, text="BFS", command=lambda: self.choose(1), height=1, width=6, bg="#cfaf4f", fg="black", ) b3 = Button( self.window, text="DFS", command=lambda: self.choose(2), height=1, width=6, bg="#cfaf4f", fg="black", ) b1.place(x=10, y=30) b2.place(x=70, y=30) b3.place(x=130, y=30) # check box self.shows = IntVar(value=1) chbtn1 = Checkbutton( self.window, text="show steps", fg="#cfaf4f", bg="#2c2825", variable=self.shows, ) chbtn1.place(x=190, y=30) # run main loop self.window.mainloop()
class MethodValidationScreen(InputUtils): def __init__(self,root,settings): intro_font = gui_font(letterfont, 10) self.root = root self.add_features(settings) def get_state(settings,statevars): Base_Parameters= namedtuple("Base_Parameters",'Curve,Repeatability,Reproducibility') to_do=[] for i in range(0,9,3): if statevars[i] is not None: to_do.append(Base_Parameters(Curve=statevars[i].get(),Repeatability=statevars[i+1].get(),Reproducibility=statevars[i+2].get())) settings['basic_settings']=to_do return defaultdict(lambda:None,settings) def initiate_validation(root=None,settings=None): Validation(root=root,settings=settings) return None def modobject(self,atrr=None): try: if atrr is not None: self.atrr =MethodValidationScreen.convert_input(self.atrr) else: raise KeyValueError except KeyValueError: print("Attribute is void!") def add_features(self,settings): # To implement : R and r are state disabled until curve is checked. Attempt to set these as class vars and have advanced settings inherit them. # Very buggy, must fix. 2 state vars are linked in the display and give incorrect values to the user but not the backend.Curve checkboxes appear ticked initially. intro_font = gui_font(letterfont, 15) var_std = StringVar() var_spike = StringVar() var_matrix = StringVar() var_std_R = BooleanVar() var_std_r = BooleanVar() var_spike_R = BooleanVar() var_spike_r = BooleanVar() var_matrix_R = BooleanVar() var_matrix_r = BooleanVar() var_auto = BooleanVar() statevars = [var_std, var_std_R, var_std_r, var_spike, var_spike_R, var_spike_r, var_matrix, var_matrix_R, var_matrix_r, var_auto] self.root.mainframe = Frame(self.root, bg='navyblue') self.root.mainframe.place(relx=0, rely=0, relheight=1, relwidth=1) self.label_title = Label( self.root.mainframe, text="Validate Method With:", font=intro_font, bg='blue', padx=50) self.label_title.place(relx=0.4, rely=0.1) self.chkbtn_std = Checkbutton(self.root.mainframe, text="Standards Curve", font=("Times New Roman", 10), variable=var_std, onvalue="STD", offvalue=None, bg='blue') self.chkbtn_std.place(relx=0.1, rely=0.3) self.chkbtn_spike = Checkbutton(self.root.mainframe, text="Spike Curve", font=("Times New Roman", 10), variable=var_spike, onvalue="Spike", offvalue=None, bg='blue') self.chkbtn_spike.place(relx=0.4, rely=0.3) self.chkbtn_matrix = Checkbutton(self.root.mainframe, text="Matrix Curve", font=("Times New Roman", 10), variable=var_matrix, onvalue="Matrix", offvalue=None, bg='blue') self.chkbtn_matrix.place(relx=0.7, rely=0.3) self.chkbtn_std_R = Checkbutton(self.root.mainframe, text="Reproducibility", font=("Times New Roman", 10), variable=var_std_R, onvalue=True, offvalue=False, bg='blue') self.chkbtn_std_R.place(relx=0.1, rely=0.6) self.chkbtn_std_r = Checkbutton(self.root.mainframe, text="Repeatability", font=("Times New Roman", 10), variable=var_std_r, onvalue=True, offvalue=False, bg='blue') self.chkbtn_std_r.place(relx=0.1, rely=0.65) self.chkbtn_Spike_R = Checkbutton(self.root.mainframe, text="Reproducibility", font=("Times New Roman", 10), variable=var_spike_R, onvalue=True, offvalue=False, bg='blue') self.chkbtn_Spike_R.place(relx=0.4, rely=0.6) self.chkbtn_Spike_r = Checkbutton(self.root.mainframe, text="Repeatability", font=("Times New Roman", 10), variable=var_spike_r, onvalue=True, offvalue=False, bg='blue') self.chkbtn_Spike_r.place(relx=0.4, rely=0.65) self.chkbtn_Matrix_R = Checkbutton(self.root.mainframe, text="Reproducibility", font=("Times New Roman", 10), variable=var_matrix_R, onvalue=True, offvalue=False, bg='blue') self.chkbtn_Matrix_R.place(relx=0.7, rely=0.6) self.chkbtn_Matrix_r = Checkbutton(self.root.mainframe, text="Repeatability", font=("Times New Roman", 10), variable=var_matrix_r, onvalue=True, offvalue=False, bg='blue') self.chkbtn_Matrix_r.place(relx=0.7, rely=0.65) self.chkbtn_auto = Checkbutton(self.root.mainframe, text="Auto Detect Files", font=( "Times New Roman", 8), variable=var_auto, onvalue=True, offvalue=False) self.chkbtn_auto.place(relx=0.1, rely=0.8) ''' project params are duplicated Integrate into a single settings defaultdict''' self.btn_ok = Button(self.root.mainframe, text="Ok", font=intro_font, command=lambda: MethodValidationScreen.initiate_validation(root=self.root,settings=MethodValidationScreen.get_state(settings,statevars))) self.btn_ok.place(relx=0.1, rely=0.9) self.btn_advanced = Button( self.root.mainframe, text="Advanced Settings", font=intro_font, command=lambda: MethodValidationSettingsScreen(self.root,MethodValidationScreen.get_state(settings,statevars))) self.btn_advanced.place(relx=0.3, rely=0.9) self.btn_exit = Button( self.root.mainframe, text="Back", font=intro_font, command=self.root.quit) self.btn_exit.place(relx=0.5, rely=0.9) self.btn_bk = Button(self.root.mainframe, text="Exit", font=intro_font, command=lambda: ProjectTypeScreen(self.r)) self.btn_bk.place(relx=0.7, rely=0.9)
image = ImageTk.PhotoImage( Image.open( "C:/Users/Kaito Yamada/Documents/GitHub/nanigasi/library/GUI/Tkinter/imagefile/image2.png" )) glabel = Label(root, image=image) glabel.place(x=5, y=50, width=100, height=100) entry = Entry(root) entry.place(x=5, y=160, width=100, height=30) entry.insert(tkinter.END, "entry") print("entry=" + entry.get()) bv = tkinter.BooleanVar() bv.set(True) checkbtn = Checkbutton(root, text="checkbutton", variable=bv) checkbtn.place(x=5, y=205, width=100, height=30) print("checkbtn=" + str(bv.get())) scale = Scale(root, orient="horizontal") scale.place(x=205, y=5, width=100, height=50) scale.set(30) print(scale.get()) scrolledtext = ScrolledText(root, state="normal") scrolledtext.place(x=205, y=75, width=200, height=100) scrolledtext.insert(tkinter.END, "scrolled text") print(scrolledtext.get("1.0", "1.2")) root.mainloop()
class filtrar: def __init__(self, parent): self.parent = parent self.pathLocation = get_secret("MAIN_PATH") self.func = functions(self) self.contador = None self.mesDe = StringVar() self.anoDe = StringVar() self.anoAte = StringVar() self.mesAte = StringVar() def Filtrar(self): self.top = Toplevel(self.parent) self.top.wm_title("Filtrar Pedidos") self.top.geometry("391x370+100+50") self.contador = 0 self.anoDe.set(strftime("%Y")) self.mesDe.set(self.func.getMes(strftime("%B"))) self.anoAte.set("") self.mesAte.set("") check = IntVar() check.set(0) # Apartir desta data # =========================A PARTIR DE========================================== labelDe = Label(self.top) labelDe['text'] = "A partir de:" labelDe.place(y=5, x=5) labelAno = Label(self.top) labelAno['text'] = "Ano" labelAno.place(y=20, x=50) self.entryAnoDe = Entry(self.top) self.entryAnoDe["textvariable"] = self.anoDe self.entryAnoDe.textvariable = self.anoDe self.entryAnoDe["width"] = 4 self.entryAnoDe.focus() self.entryAnoDe.bind("<Return>", self.setNext) self.entryAnoDe.place(y=40, x=50) labelMes = Label(self.top) labelMes["text"] = "Mes" labelMes.place(y=60, x=50) self.entryMesDe = Entry(self.top) self.entryMesDe["textvariable"] = self.mesDe self.entryMesDe.textvariable = self.mesDe self.entryMesDe["width"] = 10 self.entryMesDe.bind("<Return>", self.setNext) self.entryMesDe.place(y=80, x=50) # =========================ATE================================================== self.frame = LabelFrame(self.top) self.frame['width'] = 100 self.frame['height'] = 117 self.frame['borderwidth'] = 3 self.frame.place(y=2, x=125) self.checkBox = Checkbutton(self.frame) self.checkBox['text'] = "Até" self.checkBox['variable'] = check self.checkBox['command'] = lambda: self.ativaAte(check.get()) self.checkBox['onvalue'] = 1 self.checkBox['offvalue'] = 0 self.checkBox.variable = check self.checkBox.place(y=1, x=2) labelAno = Label(self.frame) labelAno['text'] = "Ano" labelAno.place(y=20, x=5) self.entryAnoAte = Entry(self.frame) self.entryAnoAte["state"] = DISABLED self.entryAnoAte["width"] = 4 self.entryAnoAte['textvariable'] = self.anoAte self.entryAnoAte.bind("<Return>", self.setNext) self.entryAnoAte.place(y=40, x=5) labelMes = Label(self.frame) labelMes["text"] = "Mes" labelMes.place(y=60, x=5) self.entryMesAte = Entry(self.frame) self.entryMesAte["state"] = DISABLED self.entryMesAte["width"] = 10 self.entryMesAte['textvariable'] = self.mesAte self.entryMesAte.bind("<Return>", self.setNext) self.entryMesAte.place(y=80, x=5) # =========================FILTRO=============================================== labelEntry = Label(self.top) labelEntry['text'] = "Filtro" labelEntry.place(y=20, x=265) self.entryFiltro = Entry(self.top) self.entryFiltro['width'] = 15 self.entryFiltro.bind("<Return>", lambda _: self.getFiltrado()) self.entryFiltro.place(y=40, x=240) # ======================================================================= # LABEL PARA COMPLETAR ESPAÇOS # ======================================================================= Label(self.top).pack() Label(self.top).pack() Label(self.top).pack() Label(self.top).pack() Label(self.top).pack() Label(self.top).pack() Label(self.top).pack() # ----------------------------------------------------------------------- self.scrollbar = Scrollbar(self.top) self.scrollbar.pack(side=RIGHT, fill=BOTH) self.customFont = font.Font(family="Arial", size=10) self.textFrame = Text(self.top) self.textFrame['font'] = self.customFont self.textFrame['height'] = 11 self.textFrame['width'] = 51 self.textFrame['borderwidth'] = 3 self.textFrame['takefocus'] = False self.textFrame['yscrollcommand'] = self.scrollbar.set self.textFrame.yscrollcommand = self.scrollbar.set self.textFrame.place(y=160, x=5) self.scrollbar['command'] = self.textFrame.yview self.scrollbar.command = self.textFrame.yview self.labelTotal = Label(self.top) self.labelTotal['text'] = "Total de pedidos: 0" self.labelTotal.place(y=345, x=3) buttonFiltrar = Button(self.top) buttonFiltrar['text'] = "Filtrar" buttonFiltrar['command'] = self.getFiltrado buttonFiltrar.bind("<Return>", lambda _: self.getFiltrado()) buttonFiltrar.place(y=130, x=80) button_limpar = Button(self.top) button_limpar['text'] = "Limpar Resultados" button_limpar['command'] = self.limpar_resultados button_limpar.bind("<Return>", lambda _: self.limpar_resultados()) button_limpar.place(y=130, x=130) buttonCancel = Button(self.top) buttonCancel['text'] = "Voltar" buttonCancel['command'] = self.top.destroy buttonCancel.bind("<Return>", lambda _: self.top.destroy()) buttonCancel.place(y=130, x=250) # toolTips ToolTip(self.entryAnoDe, "Exemplos:\n2016\n2015\n2014") ToolTip(self.entryMesDe, "Exemplos:\nAbril\nDezembro\nJaneiro") ToolTip(self.entryFiltro, "Exemplos:\nURA\n15/04/16\nJoão") msg = "Marque caso queira obter resultados\napartir de uma faixa de data." ToolTip(self.checkBox, msg) def limpar_resultados(self): self.textFrame['state'] = NORMAL self.textFrame.delete(1.0, END) self.contador = 0 self.labelTotal.config(text=f"Total de pedidos: {self.contador}") self.textFrame['state'] = DISABLED self.entryAnoDe.focus() def getListas(self): ano = [] listasMeses = [] meses = [ 'JANEIRO', 'FEVEREIRO', 'MARÇO', 'ABRIL', 'MAIO', 'JUNHO', 'JULHO', 'AGOSTO', 'SETEMBRO', 'OUTUBRO', 'NOVEMBRO', 'DEZEMBRO' ] # =============================================================================== # EXCEPTIONS # =============================================================================== def mudarCor(key, cor): entry = { 0: self.entryAnoAte, 1: self.entryAnoDe, 2: self.entryMesAte, 3: self.entryMesDe, } if key == 4: for i in range(4): entry[i].config(fg=cor) elif key >= 4: for i in range(4): if i != (key - 5): entry[i].config(fg=cor) else: entry[key].config(fg=cor) try: anoDe = int(self.anoDe.get()) mesDe = self.mesDe.get().upper() if anoDe <= 2015: self.entryAnoDe.focus() mudarCor(1, 'red') # AnoDe RED mudarCor(6, 'black') # Restante BLACK messagebox.showwarning("ERRO", "Ano Invalido", parent=self.top) return ("ERRO", "ERRO") elif mesDe not in meses: self.entryMesDe.focus() mudarCor(3, 'red') # MesDeDe RED mudarCor(8, 'black') # Restante BLACK messagebox.showwarning("ERRO", "Mes Invalido", parent=self.top) return ("ERRO", "ERRO") except ValueError: if self.anoDe.get() != "": self.entryAnoDe.focus() mudarCor(1, 'red') # AnoDe RED mudarCor(6, 'black') # Restante BLACK messagebox.showwarning("ERRO", "Ano Invalido", parent=self.top) return ("ERRO", "ERRO") if self.anoAte.get() == "" and self.mesAte.get().upper() == "": anoAte = int(self.anoDe.get()) mesAte = self.mesDe.get().upper() else: try: anoAte = int(self.anoAte.get()) mesAte = self.mesAte.get().upper() if self.anoDe.get() == "": anoDe = anoAte mesDe = mesAte if anoAte <= 2015: self.entryAnoAte.focus() mudarCor(0, 'red') # AnoAte RED mudarCor(5, 'black') # Restante BLACK messagebox.showwarning("ERRO", "Ano Invalido", parent=self.top) return ("ERRO", "ERRO") elif anoAte < anoDe: self.entryAnoDe.focus() mudarCor(0, 'red') # AnoAte e AnoDe RED mudarCor(5, 'black') # Restante BLACK mudarCor(1, 'red') msg = """Ano "De" tem de ser maior que Ano "Ate" """ messagebox.showwarning("ERRO", msg, parent=self.top) return ("ERRO", "ERRO") elif mesAte not in meses: self.entryMesAte.focus() mudarCor(2, 'red') # MesAte RED mudarCor(7, 'black') # Restante BLACK messagebox.showwarning("ERRO", "Mes Invalido", parent=self.top) return ("ERRO", "ERRO") elif anoAte == anoDe: if meses.index(mesDe) > meses.index(mesAte): self.entryMesDe.focus() mudarCor(2, 'red') # MesAte e MesDe RED mudarCor(7, 'black') # Restante BLACK mudarCor(3, 'red') msg = """Mes "De" tem de ser anterior ao Mes "Ate" Exemplo: Mes De: Junho Mes Até: Julho """ messagebox.showwarning("ERRO", msg, parent=self.top) return ("ERRO", "ERRO") except ValueError: self.entryAnoAte.focus() self.entryAnoAte['fg'] = 'red' mudarCor(0, 'red') # AnoAte RED mudarCor(5, 'black') # Restante BLACK messagebox.showwarning("ERRO", "Ano Invalido", parent=self.top) return ("ERRO", "ERRO") mudarCor(4, 'black') # TODOS BALCK # =============================================================================== # Função # =============================================================================== for x in range(anoDe, anoAte + 1): ano.append(x) aux = [] if anoDe == anoAte: if mesDe == mesAte: listasMeses.append([mesDe]) else: for i in range(meses.index(mesDe), meses.index(mesAte) + 1): aux.append(meses[i]) listasMeses.append(aux) elif x != anoDe and x != anoAte: listasMeses.append(meses) elif x == anoDe: index = meses.index(mesDe) for i in range(index, 12): aux.append(meses[i]) listasMeses.append(aux) else: index = meses.index(mesAte) for i in range(0, index + 1): aux.append(meses[i]) listasMeses.append(aux) return (ano, listasMeses) def getFiltrado(self): anos, meses = self.getListas() if anos == "ERRO" or meses == "ERRO": return if self.textFrame.get(1.0) != '\n': self.textFrame['state'] = NORMAL self.textFrame.delete(1.0, END) self.contador = 0 self.textFrame['state'] = NORMAL for cont in range(len(anos)): mes = meses[cont] y = anos[cont] for m in mes: try: _path = os.path.abspath( os.path.join(self.pathLocation, str(y), f"{m}.cfg")) with open(_path, 'r', encoding=ENCODING) as file: lines = file.readlines()[1:] for line in lines: if self.entryFiltro.get().upper() in line.rstrip( ).upper(): self.textFrame.insert(END, line.rstrip() + "\n") self.contador += 1 else: self.contador += 0 self.labelTotal.config( text=f"Total de pedidos: {self.contador}") except IOError: message = """Arquivo %s/%s.cfg não localizado!""" % (y, m) messagebox.showwarning("Erro!", message, parent=self.top) self.textFrame['state'] = DISABLED def ativaAte(self, flag): toolTipAno = ToolTip(self.entryAnoAte, "Exemplos:\n2016\n2015\n2014") toolTipMes = ToolTip(self.entryMesAte, "Exemplos:\nAbril\nDezembro\nJaneiro") if flag == 1: self.entryAnoAte.config(state=NORMAL) self.entryAnoDe.focus() self.entryMesAte.config(state=NORMAL) self.frame['borderwidth'] = 0 toolTipAno.startShowing() toolTipMes.startShowing() self.anoAte.set(self.anoDe.get()) self.mesAte.set(self.mesDe.get().upper()) self.anoDe.set("") self.mesDe.set("") else: self.anoDe.set(self.anoAte.get()) self.mesDe.set(self.mesAte.get().upper()) self.anoAte.set("") self.mesAte.set("") self.entryAnoAte.config(state=DISABLED) self.entryMesAte.config(state=DISABLED) self.entryFiltro.focus() self.frame['borderwidth'] = 3 toolTipAno.stopShowing() toolTipMes.stopShowing() def setNext(self, event): event.widget.tk_focusNext().focus() return ("break")
class vedoGUI(Frame): def __init__(self, parent): Frame.__init__(self, parent, bg="white") self.parent = parent self.filenames = [] self.noshare = BooleanVar() self.flat = BooleanVar() self.xspacing = StringVar() self.yspacing = StringVar() self.zspacing = StringVar() self.background_grad = BooleanVar() self.initUI() def initUI(self): self.parent.title("vedo") self.style = Style() self.style.theme_use("clam") self.pack(fill=BOTH, expand=True) ############import Button(self, text="Import Files", command=self._importCMD, width=15).place(x=115, y=17) ############meshes Frame(root, height=1, width=398, bg="grey").place(x=1, y=60) Label(self, text="Meshes", fg="white", bg="green", font=("Courier 11 bold")).place(x=20, y=65) # color Label(self, text="Color:", bg="white").place(x=30, y=98) colvalues = ('by scalar', 'gold', 'red', 'green', 'blue', 'coral', 'plum', 'tomato') self.colorCB = Combobox(self, state="readonly", values=colvalues, width=10) self.colorCB.current(0) self.colorCB.place(x=100, y=98) # mode modvalues = ('surface', 'surf. & edges', 'wireframe', 'point cloud') self.surfmodeCB = Combobox(self, state="readonly", values=modvalues, width=14) self.surfmodeCB.current(0) self.surfmodeCB.place(x=205, y=98) # alpha Label(self, text="Alpha:", bg="white").place(x=30, y=145) self.alphaCB = Scale( self, from_=0, to=1, resolution=0.02, bg="white", length=220, orient="horizontal", ) self.alphaCB.set(1.0) self.alphaCB.place(x=100, y=125) # lighting Label(self, text="Lighting:", bg="white").place(x=30, y=180) lightvalues = ('default', 'metallic', 'plastic', 'shiny', 'glossy') self.lightCB = Combobox(self, state="readonly", values=lightvalues, width=10) self.lightCB.current(0) self.lightCB.place(x=100, y=180) # shading phong or flat self.flatCB = Checkbutton(self, text="flat shading", var=self.flat, bg="white") #self.flatCB.select() self.flatCB.place(x=210, y=180) # rendering arrangement Label(self, text="Arrange as:", bg="white").place(x=30, y=220) schemevalues = ('superpose (default)', 'mesh browser', 'n sync-ed renderers') self.schememodeCB = Combobox(self, state="readonly", values=schemevalues, width=20) self.schememodeCB.current(0) self.schememodeCB.place(x=160, y=220) # share cam self.noshareCB = Checkbutton(self, text="independent cameras", variable=self.noshare, bg="white") self.noshareCB.place(x=160, y=245) ############volumes Frame(root, height=1, width=398, bg="grey").place(x=1, y=275) Label(self, text="Volumes", fg="white", bg="blue", font=("Courier 11 bold")).place(x=20, y=280) # mode Label(self, text="Rendering mode:", bg="white").place(x=30, y=310) modevalues = ( "isosurface (default)", "composite", "maximum proj", "lego", "slicer", "slicer2d", ) self.modeCB = Combobox(self, state="readonly", values=modevalues, width=20) self.modeCB.current(0) self.modeCB.place(x=160, y=310) Label(self, text="Spacing factors:", bg="white").place(x=30, y=335) self.xspacingCB = Entry(self, textvariable=self.xspacing, width=3) self.xspacing.set('1.0') self.xspacingCB.place(x=160, y=335) self.yspacingCB = Entry(self, textvariable=self.yspacing, width=3) self.yspacing.set('1.0') self.yspacingCB.place(x=210, y=335) self.zspacingCB = Entry(self, textvariable=self.zspacing, width=3) self.zspacing.set('1.0') self.zspacingCB.place(x=260, y=335) ############## options Frame(root, height=1, width=398, bg="grey").place(x=1, y=370) Label(self, text="Options", fg='white', bg="brown", font=("Courier 11 bold")).place(x=20, y=375) # backgr color Label(self, text="Background color:", bg="white").place(x=30, y=405) bgcolvalues = ("white", "lightyellow", "azure", "blackboard", "black") self.bgcolorCB = Combobox(self, state="readonly", values=bgcolvalues, width=9) self.bgcolorCB.current(3) self.bgcolorCB.place(x=160, y=405) # backgr color gradient self.backgroundGradCB = Checkbutton(self, text="gradient", variable=self.background_grad, bg="white") self.backgroundGradCB.place(x=255, y=405) ################ render button Frame(root, height=1, width=398, bg="grey").place(x=1, y=437) Button(self, text="Render", command=self._run, width=15).place(x=115, y=454) def _importCMD(self): ftypes = [ ("All files", "*"), ("VTK files", "*.vtk"), ("VTK files", "*.vtp"), ("VTK files", "*.vts"), ("VTK files", "*.vtu"), ("Surface Mesh", "*.ply"), ("Surface Mesh", "*.obj"), ("Surface Mesh", "*.stl"), ("Surface Mesh", "*.off"), ("Surface Mesh", "*.facet"), ("Volume files", "*.tif"), ("Volume files", "*.slc"), ("Volume files", "*.vti"), ("Volume files", "*.mhd"), ("Volume files", "*.nrrd"), ("Volume files", "*.nii"), ("Volume files", "*.dem"), ("Picture files", "*.png"), ("Picture files", "*.jpg"), ("Picture files", "*.bmp"), ("Picture files", "*.gif"), ("Picture files", "*.jpeg"), ("Geojson files", "*.geojson"), ("DOLFIN files", "*.xml.gz"), ("DOLFIN files", "*.xml"), ("DOLFIN files", "*.xdmf"), ("Neutral mesh", "*.neu*"), ("GMESH", "*.gmsh"), ("Point Cloud", "*.pcd"), ("3DS", "*.3ds"), ("Numpy scene file", "*.npy"), ("Numpy scene file", "*.npz"), ] self.filenames = tkFileDialog.askopenfilenames(parent=root, filetypes=ftypes) args.files = list(self.filenames) def _run(self): tips() args.files = list(self.filenames) if self.colorCB.get() == "by scalar": args.color = None else: if self.colorCB.get() == 'red': args.color = 'crimson' elif self.colorCB.get() == 'green': args.color = 'limegreen' elif self.colorCB.get() == 'blue': args.color = 'darkcyan' else: args.color = self.colorCB.get() args.alpha = self.alphaCB.get() args.wireframe = False args.showedges = False args.point_size = 0 if self.surfmodeCB.get() == 'point cloud': args.point_size = 2 elif self.surfmodeCB.get() == 'wireframe': args.wireframe = True elif self.surfmodeCB.get() == 'surf. & edges': args.showedges = True else: pass # normal surface mode args.lighting = self.lightCB.get() args.flat = self.flat.get() args.no_camera_share = self.noshare.get() args.background = self.bgcolorCB.get() args.background_grad = None if self.background_grad.get(): b = getColor(args.background) args.background_grad = (b[0] / 1.8, b[1] / 1.8, b[2] / 1.8) args.multirenderer_mode = False args.scrolling_mode = False if self.schememodeCB.get() == "n sync-ed renderers": args.multirenderer_mode = True elif self.schememodeCB.get() == "mesh browser": args.scrolling_mode = True args.ray_cast_mode = False args.lego = False args.slicer = False args.slicer2d = False args.lego = False args.mode = 0 if self.modeCB.get() == "composite": args.ray_cast_mode = True args.mode = 0 elif self.modeCB.get() == "maximum proj": args.ray_cast_mode = True args.mode = 1 elif self.modeCB.get() == "slicer": args.slicer = True elif self.modeCB.get() == "slicer2d": args.slicer2d = True elif self.modeCB.get() == "lego": args.lego = True args.x_spacing = 1 args.y_spacing = 1 args.z_spacing = 1 if self.xspacing.get() != '1.0': args.x_spacing = float(self.xspacing.get()) if self.yspacing.get() != '1.0': args.y_spacing = float(self.yspacing.get()) if self.zspacing.get() != '1.0': args.z_spacing = float(self.zspacing.get()) draw_scene(args) if os.name == "nt": exit() if settings.plotter_instance: settings.plotter_instance.close()
def check_buttons(self): cb = Checkbutton(self.root, text="Показать", command=self.onClickCkeckButton) cb.place(height=40, relx=.9, rely=.3, anchor="c")
def main(): root = tkinter.Tk() root.title("Putty Controller") servers_file = "/Documents/servers.txt" accounts_file = "/Documents/accounts.txt" def destroy_frame(frame): for widget in frame.winfo_children(): widget.destroy() w_server = tkinter.Frame(root, width=300, height=290, borderwidth=1, relief=GROOVE) destroy_frame(w_server) w_buttoms = tkinter.Frame(root, width=120, height=290, borderwidth=1, relief=GROOVE) destroy_frame(w_buttoms) servers = functions.load_file(servers_file) server_key = tkinter.StringVar() server_key.set(str(list(servers.keys())[-1])) title_server = tkinter.Message(w_server, text="Server", width=100) title_server.place(x=1, y=67) servers_list = Listbox(w_server, yscrollcommand=Scrollbar.set) #servers_list.config(command = servers_list.yview) for server in servers.keys(): servers_list.insert(END, str(server)) servers_list.place(x=80, y=65, width=200, height=120) servers_scroll = tkinter.Scrollbar(w_server) servers_scroll.place(x=280, y=65, width=15, height=120) servers_scroll.config(command=servers_list.yview) title_show_server = tkinter.Message(w_server, text="Last Opened", width=100) title_show_server.place(x=1, y=32) show_server = Message(w_server, text=server_key.get(), aspect=2000, anchor=W, relief=SUNKEN) show_server.place(x=80, y=30, width=215, height=30) title_server_standalone = tkinter.Message(w_server, text="Connect to: ", width=100) title_server_standalone.place(x=1, y=193) server_standalone = tkinter.Entry(w_server) server_standalone.place(x=80, y=195, width=215) title_user_standalone = tkinter.Message(w_server, text="User: "******"Password: "******"Use account: ", width=100) title_accounts.place(x=1, y=220) account_check = Checkbutton(w_server, text="ACC1", variable=accounts_key0) account_check.place(x=75, y=220) account_check = Checkbutton(w_server, text="ACC2", variable=accounts_key1) account_check.place(x=125, y=220) account_check = Checkbutton(w_server, text="ACC3", variable=accounts_key2) account_check.place(x=175, y=220) account_check = Checkbutton(w_server, text="OTHER", variable=accounts_other, command=enable_fields) account_check.place(x=235, y=220) def do_open_putty(accounts_key0, accounts_key1, accounts_key2, accounts_other): if server_standalone.get() != "": accounts_used = list() if accounts_key0.get() != 0: accounts_key0 = "ACC1" else: accounts_key0 = "" if accounts_key1.get() != 0: accounts_key1 = "ACC2" else: accounts_key1 = "" if accounts_key2.get() != 0: accounts_key2 = "ACC3" else: accounts_key2 = "" if accounts_other.get() != 0: accounts_other = user_standalone.get() else: accounts_other = "" accounts_used.append(accounts_key0) accounts_used.append(accounts_key1) accounts_used.append(accounts_key2) accounts_used.append(accounts_other) for account in accounts_used: if account == "ACC1" or account == "ACC2" or account == "ACC3": user = str(accounts.get(str(account))).split(",")[1] password = str(accounts.get(str(account))).split(",")[2] functions.open_putty(user, password, server_standalone.get()) functions.update_server(w_server, server_standalone.get()) elif account != "": user = user_standalone.get() password = password_standalone.get() functions.open_putty(user, password, server_standalone.get()) functions.update_server(w_server, server_standalone.get()) else: ip = str( servers.get(str(servers_list.get( servers_list.curselection())))).split(",")[1] account = str( servers.get(str(servers_list.get( servers_list.curselection())))).split(",")[2] user = str(accounts.get(str(account))).split(",")[1] password = str(accounts.get(str(account))).split(",")[2] functions.open_putty(user, password, ip) functions.update_server( w_server, servers_list.get(servers_list.curselection())) def button_open_putty(): do_open_putty(accounts_key0, accounts_key1, accounts_key2, accounts_other) def do_open_winscp(accounts_key0, accounts_key1, accounts_key2, accounts_other, sudo_value): if server_standalone.get() != "": accounts_used = list() if accounts_key0.get() != 0: accounts_key0 = "ACC1" else: accounts_key0 = "" if accounts_key1.get() != 0: accounts_key1 = "ACC2" else: accounts_key1 = "" if accounts_key2.get() != 0: accounts_key2 = "ACC3" else: accounts_key2 = "" if accounts_other.get() != 0: accounts_other = user_standalone.get() else: accounts_other = "" accounts_used.append(accounts_key0) accounts_used.append(accounts_key1) accounts_used.append(accounts_key2) accounts_used.append(accounts_other) for account in accounts_used: if account == "ACC1" or account == "ACC2" or account == "ACC3": user = str(accounts.get(str(account))).split(",")[1] password = str(accounts.get(str(account))).split(",")[2] functions.open_winscp(user, password, server_standalone.get(), sudo_value.get()) functions.update_server(w_server, server_standalone.get()) elif account != "": user = user_standalone.get() password = password_standalone.get() functions.open_winscp(user, password, server_standalone.get(), sudo_value.get()) functions.update_server(w_server, server_standalone.get()) else: ip = str( servers.get(str(servers_list.get( servers_list.curselection())))).split(",")[1] account = str( servers.get(str(servers_list.get( servers_list.curselection())))).split(",")[2] user = str(accounts.get(str(account))).split(",")[1] password = str(accounts.get(str(account))).split(",")[2] functions.open_winscp(user, password, ip, sudo_value.get()) functions.update_server( w_server, servers_list.get(servers_list.curselection())) def button_open_winscp(): do_open_winscp(accounts_key0, accounts_key1, accounts_key2, accounts_other, sudo_value) def do_open_wfreerdp(accounts_key0, accounts_key1, accounts_key2, accounts_other, full_screen_value): if server_standalone.get() != "": accounts_used = list() if accounts_key0.get() != 0: accounts_key0 = "ACC1" else: accounts_key0 = "" if accounts_key1.get() != 0: accounts_key1 = "ACC2" else: accounts_key1 = "" if accounts_key2.get() != 0: accounts_key2 = "ACC3" else: accounts_key2 = "" if accounts_other.get() != 0: accounts_other = user_standalone.get() else: accounts_other = "" accounts_used.append(accounts_key0) accounts_used.append(accounts_key1) accounts_used.append(accounts_key2) accounts_used.append(accounts_other) title = "Server: " + str(server_standalone.get()) width = 1440 height = 900 for account in accounts_used: if account == "ACC1" or account == "ACC2" or account == "ACC3": user = str(accounts.get(str(account))).split(",")[1] password = str(accounts.get(str(account))).split(",")[2] functions.open_wfreerdp(title, server_standalone.get(), user, password, width, height, full_screen_value.get()) functions.update_server(w_server, server_standalone.get()) elif account != "": user = user_standalone.get() password = password_standalone.get() functions.open_wfreerdp(title, server_standalone.get(), user, password, width, height, full_screen_value.get()) functions.update_server(w_server, server_standalone.get()) else: title = str( servers.get(str(servers_list.get( servers_list.curselection())))).split(",")[0] ip = str( servers.get(str(servers_list.get( servers_list.curselection())))).split(",")[1] account = str( servers.get(str(servers_list.get( servers_list.curselection())))).split(",")[2] user = str(accounts.get(str(account))).split(",")[1] password = str(accounts.get(str(account))).split(",")[2] width = str( servers.get(str(servers_list.get( servers_list.curselection())))).split(",")[3] height = str( servers.get(str(servers_list.get( servers_list.curselection())))).split(",")[4] functions.open_wfreerdp(title, ip, user, password, width, height, full_screen_value.get()) functions.update_server( w_server, servers_list.get(servers_list.curselection())) def button_open_wfreerdp(): do_open_wfreerdp(accounts_key0, accounts_key1, accounts_key2, accounts_other, full_screen_value) button = tkinter.Button(w_buttoms, text='Open Putty', command=button_open_putty) button.place(x=8, y=30, width=100, height=30) button = tkinter.Button(w_buttoms, text='Open WinSCP', command=button_open_winscp) button.place(x=8, y=70, width=100, height=30) sudo_value = IntVar() sudo_value_check = Checkbutton(w_buttoms, text="With sudo?", variable=sudo_value) sudo_value_check.place(x=8, y=100) button = tkinter.Button(w_buttoms, text='Open WFreeRDP', command=button_open_wfreerdp) button.place(x=8, y=130, width=100, height=30) full_screen_value = IntVar() full_screen_value_check = Checkbutton(w_buttoms, text="Full Screen?", variable=full_screen_value) full_screen_value_check.place(x=8, y=160) def refresh(self): root.wm_attributes("-topmost", ontop_value.get()) def do_refresh(): refresh(root) ontop_value = IntVar() ontop_value_check = Checkbutton(w_server, text="On Top?", variable=ontop_value, command=do_refresh) ontop_value_check.place(x=1, y=1) w_server.pack(padx=1, pady=1, side=LEFT) w_buttoms.pack(padx=1, pady=1, side=RIGHT) root.wm_attributes("-topmost", ontop_value.get()) root.resizable(width=False, height=False) root.mainloop()
class TextSimilarityWindow: """ This class is used for creating the minimalistic UI for the Text similarity index processor which is used to find the similarity index (100%, 99% matching text etc...) between text say, requirements, Tests... """ i = ROW_SPACER def __init__(self, win): """constructor for text Similarity Window, which initializes the input variables needed to fetch from user """ self.filename = None self.new_text = None self.is_new_text = IntVar() self.browsebutton = Button(win, text="Browse", command=self.__browse_func) self.browsebutton.place(x=450, y=ROW_SPACER) def __place_ui_item(text, val, width=10): """ Function used to place the UI elements to respective place in the UI """ _id = Label(win, text=text) _id.place(x=10, y=ROW_SPACER * val) _text_in = Entry(win, width=width) _text_in.place(x=200, y=ROW_SPACER * val) _text_in.delete(0, END) return _id, _text_in self.path, self.path_t = __place_ui_item("Input File Path", 1, 30) self.uniq_id, self.uniq_id_t = __place_ui_item("Unique ID Column", 2) self.steps_id, self.steps_t = __place_ui_item("Columns Of Interest", 3) self.range_id, self.range_t = __place_ui_item("similarity range", 4) def __new_text_compare(): """ Function used to create the place holder for the User input used for the new text to be compared """ if self.is_new_text.get() == 1: self.new_text = Entry(win, width=10) self.new_text.place(x=250, y=ROW_SPACER * 6, width=340, height=50) else: self.new_text.destroy() self.check_is_new_text = Checkbutton(win, text="New Text Comparison", variable=self.is_new_text, command=__new_text_compare) self.check_is_new_text.place(x=50, y=ROW_SPACER * 6) self.submit = Button(win, text="Process", command=self.process) self.submit.place(x=250, y=ROW_SPACER * 9) def __browse_func(self): """ Function used for providing the Browse to file path in the GUI """ try: self.filename = filedialog.askopenfilename() self.path_t.delete(0, END) self.path_t.insert(0, str(self.filename)) except TypeError as error: print("Exception at browse_func method:", str(error)) # pragma: no mutate LOG.error("Error:%s", str(error)) # pragma: no mutate def __get_new_text(self): """ Function used to get the user input text in case of new text for similarity checking, else to return None """ return str( self.new_text.get()) if self.is_new_text.get() == 1 else None def process(self): """ Function which is the entry for all the processing activity.""" try: similarity_io_obj = SimilarityIO(self.path_t.get(), self.uniq_id_t.get(), self.steps_t.get(), self.range_t.get(), 100, self.is_new_text.get(), self.__get_new_text(), 500000) similarity_io_obj.orchestrate_similarity() except TypeError as error: print("Error:", str(error)) # pragma: no mutate LOG.error("Error:%s", str(error)) # pragma: no mutate
def cont_prediction(self, old_window): """ :param old_window: :return: """ old_window.destroy() cont_prediction_window = Tk() self.new_window(cont_prediction_window, "MitoSegNet Navigator - Prediction", 500, 330) self.small_menu(cont_prediction_window) dir_data_path_prediction = StringVar(cont_prediction_window) popup_var = StringVar(cont_prediction_window) batch_var = StringVar(cont_prediction_window) model_name = StringVar(cont_prediction_window) min_obj_size = StringVar(cont_prediction_window) min_obj_size.set(0) dir_data_path_test_prediction = StringVar(cont_prediction_window) found = IntVar() found.set(0) # open choose directory window def askopendir_pred(): set_dir_data_path = filedialog.askdirectory(parent=cont_prediction_window, title='Choose a directory') dir_data_path_prediction.set(set_dir_data_path) if dir_data_path_prediction.get() != "": file_list = os.listdir(dir_data_path_prediction.get()) new_list = [i for i in file_list if ".hdf5" in i and not ".csv" in i] if len(new_list) != 0: found.set(1) self.place_text(cont_prediction_window, "Found the following model files", 40, 60, 35, 190) model_name.set(new_list[0]) model_name_popupMenu = OptionMenu(cont_prediction_window, model_name, *set(new_list)) model_name_popupMenu.place(bordermode=OUTSIDE, x=230, y=63, height=30, width=200) else: self.place_text(cont_prediction_window, "No model found", 40, 60, 35, 360) text = "Select MitoSegNet Project directory" self.place_browse(askopendir_pred, text, dir_data_path_prediction, 20, 10, None, None, cont_prediction_window) # open choose directory window def askopendir_test_pred(): set_dir_data_path_test = filedialog.askdirectory(parent=cont_prediction_window, title='Choose a directory') dir_data_path_test_prediction.set(set_dir_data_path_test) text_s = "Select folder containing 8-bit images to be segmented" + " " * 30 self.place_browse(askopendir_test_pred, text_s, dir_data_path_test_prediction, 20, 100, None, None, cont_prediction_window) ps_filter = StringVar(cont_prediction_window) ps_filter.set(False) psf_button = Checkbutton(cont_prediction_window, text="Post-segmentation filtering", variable=ps_filter, onvalue=True, offvalue=False) psf_button.place(bordermode=OUTSIDE, x=15, y=280, height=30, width=200) # start prediction def start_prediction(): if dir_data_path_prediction.get() != "" and found.get() == 1 and dir_data_path_test_prediction.get() != "": try: ts_path = dir_data_path_prediction.get() + os.sep + "train" + os.sep + "image" tile_size, tile_size = self.get_image_info(ts_path, True, False) except: print("Could not retrieve tile size. Please make sure the images used for training are located " "under" + ts_path) if batch_var.get() == "One folder": y, x = self.get_image_info(dir_data_path_test_prediction.get(), True, False) else: y, x = self.get_image_info(dir_data_path_test_prediction.get(), True, True) try: x_res = cont_prediction_window.winfo_screenwidth() y_res = cont_prediction_window.winfo_screenheight() except: print("Error when trying to retrieve screenwidth and screenheight. ", "Skipping post-segmentation filtering") x_res = 0 y_res = 0 ps_filter.set(False) self.prediction(dir_data_path_test_prediction.get(), dir_data_path_prediction.get(), "", model_name.get(), batch_var.get(), popup_var.get(), tile_size, y, x, min_obj_size.get(), ps_filter.get(), x_res, y_res, cont_prediction_window) else: messagebox.showinfo("Error", "Entries not completed", parent=cont_prediction_window) self.place_prediction_text(min_obj_size, batch_var, popup_var, cont_prediction_window) self.place_button(cont_prediction_window, "Start prediction", start_prediction, 360, 280, 30, 110)
def show_record_types(self, width, height): self.dtr = BooleanVar() self.hbr = BooleanVar() self.mir = BooleanVar() self.mpr = BooleanVar() self.mrr = BooleanVar() self.pcr = BooleanVar() self.pir = BooleanVar() self.prr = BooleanVar() self.ptr = BooleanVar() self.rdr = BooleanVar() self.sbr = BooleanVar() self.sdr = BooleanVar() self.tsr = BooleanVar() self.wcr = BooleanVar() self.wir = BooleanVar() self.wrr = BooleanVar() DTR = Checkbutton(self, text="DTR", variable=self.dtr, command=self.check_box_clicked) HBR = Checkbutton(self, text="HBR", variable=self.hbr, command=self.check_box_clicked) MIR = Checkbutton(self, text="MIR", variable=self.mir, command=self.check_box_clicked) MPR = Checkbutton(self, text="MPR", variable=self.mpr, command=self.check_box_clicked) MRR = Checkbutton(self, text="MRR", variable=self.mrr, command=self.check_box_clicked) PCR = Checkbutton(self, text="PCR", variable=self.pcr, command=self.check_box_clicked) PIR = Checkbutton(self, text="PIR", variable=self.pir, command=self.check_box_clicked) PRR = Checkbutton(self, text="PRR", variable=self.prr, command=self.check_box_clicked) PTR = Checkbutton(self, text="PTR", variable=self.ptr, command=self.check_box_clicked) RDR = Checkbutton(self, text="RDR", variable=self.rdr, command=self.check_box_clicked) SBR = Checkbutton(self, text="SBR", variable=self.sbr, command=self.check_box_clicked) SDR = Checkbutton(self, text="SDR", variable=self.sdr, command=self.check_box_clicked) TSR = Checkbutton(self, text="TSR", variable=self.tsr, command=self.check_box_clicked) WCR = Checkbutton(self, text="WCR", variable=self.wcr, command=self.check_box_clicked) WIR = Checkbutton(self, text="WIR", variable=self.wir, command=self.check_box_clicked) WRR = Checkbutton(self, text="WRR", variable=self.wrr, command=self.check_box_clicked) DTR.place(x=width*0.20, y=height*0.70) HBR.place(x=width*0.20, y=height*0.75) MIR.place(x=width*0.30, y=height*0.70) MPR.place(x=width*0.30, y=height*0.75) MRR.place(x=width*0.20, y=height*0.60) PCR.place(x=width*0.20, y=height*0.65) PIR.place(x=width*0.30, y=height*0.60) PRR.place(x=width*0.30, y=height*0.65) PTR.place(x=width*0.20, y=height*0.50) RDR.place(x=width*0.20, y=height*0.55) SBR.place(x=width*0.30, y=height*0.50) SDR.place(x=width*0.30, y=height*0.55) TSR.place(x=width*0.20, y=height*0.40) WCR.place(x=width*0.20, y=height*0.45) WIR.place(x=width*0.30, y=height*0.40) WRR.place(x=width*0.30, y=height*0.45) generate_records_button = Button(self, text="Generate Records", command=self.run_records) generate_records_button.pack(side=RIGHT)
class Win2: def run(self): # Variable self.usbChoiceList = [] self.startUpChoice = False # Main window self.win = Tk() self.win.title("Easy USB Backup") self.win.geometry('700x500') self.win.iconbitmap(path + 'material/a.ico') self.win.resizable(0, 0) self.win.option_add('*tearOff', False) #================================================================================================== # Menu functions def Control(): # Variable self.config1 = 0 self.config2 = 0 # Control window self.conWin = Tk() self.conWin.title("控制中心") self.conWin.iconbitmap(path + 'material/a.ico') self.conWin.geometry("710x80") self.conWin.resizable(0, 0) # Label self.conl1 = Label(self.conWin, text="检测时间间隔(s)", font=('fangsong', 13)) self.conl2 = Label(self.conWin, text="备份文件夹命名方式", font=('fangsong', 13)) self.conl3 = Label(self.conWin, text="检测到U盘插入时是否提示", font=('fangsong', 13)) # Entry self.cone1 = Entry(self.conWin, width=64) # Radiobutton functions def conr1f(): if self.config1 != 0: self.conrL1 = [ self.conr1, self.conr2, self.conr3, self.conr4 ] self.conrL1[self.config1].deselect() self.config1 = 0 else: self.conrL1[self.config1].select() def conr2f(): if self.config1 != 1: self.conrL1 = [ self.conr1, self.conr2, self.conr3, self.conr4 ] self.conrL1[self.config1].deselect() self.config1 = 1 else: self.conrL1[self.config1].select() def conr3f(): if self.config1 != 2: self.conrL1 = [ self.conr1, self.conr2, self.conr3, self.conr4 ] self.conrL1[self.config1].deselect() self.config1 = 2 else: self.conrL1[self.config1].select() def conr4f(): if self.config1 != 3: self.conrL1 = [ self.conr1, self.conr2, self.conr3, self.conr4 ] self.conrL1[self.config1].deselect() self.config1 = 3 else: self.conrL1[self.config1].select() def conr7f(): if self.config2 != 0: self.conrL2 = [self.conr7, self.conr8] self.conrL2[self.config2].deselect() self.config2 = 0 else: self.conrL2[self.config2].select() def conr8f(): if self.config2 != 1: self.conrL2 = [self.conr7, self.conr8] self.conrL2[self.config2].deselect() self.config2 = 1 else: self.conrL2[self.config2].select() # Checkbutton self.conr1 = Checkbutton(self.conWin, text="时间", command=conr1f) self.conr2 = Checkbutton(self.conWin, text="U盘名称", command=conr2f) self.conr3 = Checkbutton(self.conWin, text="时间+U盘名称", command=conr3f) self.conr4 = Checkbutton(self.conWin, text="U盘名称+时间", command=conr4f) self.conr7 = Checkbutton(self.conWin, text="是", command=conr7f) self.conr8 = Checkbutton(self.conWin, text="否", command=conr8f) # Button fuctions def apply(): Log("Apply button is clicked") try: self.time = int(self.cone1.get()) self.jsconfig = { 'time': self.time, 'config1': self.config1, 'config2': self.config2 } with open(path + 'info/config.json', encoding='utf-8') as fileConf: fileConff = fileConf.readlines() if fileConff == []: with open(path + 'info/config.json', mode='w', encoding='utf-8') as f: dump(self.jsconfig, f, indent=4, separators=(',', ':')) if (messagebox.showinfo("控制中心", "应用成功")) == "ok": self.conWin.destroy() elif fileConff != []: with open(path + 'info/config.json', encoding='utf-8') as f: self.ff = load(f) self.ff["time"] = self.time self.ff['config1'] = self.config1 self.ff['config2'] = self.config2 with open(path + 'info/config.json', mode='w', encoding='utf-8') as f: dump(self.ff, f, indent=4, separators=(",", ":")) if (messagebox.showinfo("控制中心", "应用成功")) == "ok": self.conWin.destroy() except: messagebox.showerror("控制中心", "您输入的数据错误,或您打开了多个控制中心窗口.") def advice(): Log("Advice button is clicked") self.cone1.delete(0, END) self.cone1.insert('insert', '2') self.conrL1 = [self.conr1, self.conr2, self.conr3, self.conr4] self.conrL1[self.config1].deselect() self.conr3.select() self.config1 = 2 self.conrL2 = [self.conr7, self.conr8] self.conrL2[self.config2].deselect() self.conr8.select() self.config2 = 1 # Button self.conb1 = Button(self.conWin, text="应用", relief=GROOVE, width=7, command=apply) self.conb2 = Button(self.conWin, text="推荐设置", relief=GROOVE, width=7, command=advice) # Display self.conl1.place(x=0, y=0) self.cone1.place(x=250, y=2) self.conl2.place(x=0, y=25) self.conr1.place(x=170, y=25) self.conr2.place(x=220, y=25) self.conr3.place(x=290, y=25) self.conr4.place(x=393, y=25) self.conl3.place(x=0, y=50) self.conr7.place(x=210, y=50) self.conr8.place(x=245, y=50) self.conb1.place(x=580, y=48) self.conb2.place(x=640, y=48) self.conWin.mainloop() #================================================================================================== def About(): # About window self.aboutwin = Toplevel() self.aboutwin.title("关于") self.aboutwin.geometry("300x200") self.aboutwin.resizable(0, 0) self.aboutwin.iconbitmap(path + 'material/a.ico') # Label self.aboutl1 = Label(self.aboutwin, text="Easy USB Backup", font=('Arial', 16)) self.aboutl2 = Label(self.aboutwin, text="作者:Skyler Sun", font=('fangsong', 14)) self.aboutl3 = Label(self.aboutwin, text="GUI设计:徐笳棋", font=('fangsong', 14)) self.aboutl4 = Label(self.aboutwin, text="版本号:0-4", font=('fangsong', 14)) # Display self.aboutl1.pack(side='top') self.aboutl2.place(x=15, y=30) self.aboutl3.place(x=15, y=55) self.aboutl4.place(x=15, y=80) self.aboutwin.mainloop() #================================================================================================== # Menu self.winMenubar = Menu(self.win) self.winmenu = Menu(self.winMenubar) self.winmenu.add_command(label="控制中心", command=Control) self.winmenu.add_command(label="关于", command=About) self.winMenubar.add_cascade(label="设置", menu=self.winmenu) self.win['menu'] = self.winMenubar # Background self.backgroundImg = PhotoImage(file=path + 'material/g.gif') self.canvas = Canvas(width=700, height=480, highlightthickness=0, borderwidth=0) self.canvas.create_image(0, 0, image=self.backgroundImg, anchor='nw') # Label self.canvas.create_text(135, 25, text="选择U盘(可移动DISK)", font=('Arial', 17), fill='red') self.canvas.create_text(70, 365, text="备份位置", font=('Arial Black', 17), fill='red') self.canvas.create_text(590, 440, text="By: Skyler Sun", font=('Arial Black', 17), fill='white') self.location = Label(self.win, width=34, height=1, font=('fangsong', 17), anchor='w') # Frame self.usbFrame = Frame(self.win) # Text self.usbText = Text(self.usbFrame, height=23, width=67) # Checkbutton fuctioins def usbAct(content): if content in self.usbChoiceList: self.usbChoiceList.remove(content) Log(content + " disk is removed") elif content not in self.usbChoiceList: Log(content + " disk is added") self.usbChoiceList.append(content) self.usbChoiceList.sort() with open(path + 'info/config.json', encoding='utf-8') as f: ff = f.readlines() if ff != []: with open(path + 'info/config.json', encoding='utf-8') as F: i = load(F) i['usbChoiceList'] = str(self.usbChoiceList) with open(path + 'info/config.json', mode='w', encoding='utf-8') as F: dump(i, F, indent=4, separators=(',', ':')) Log("USB Choice List: " + str(self.usbChoiceList)) elif ff == []: self.dict = {"usbChoiceList": str(self.usbChoiceList)} with open(path + 'info/config.json', mode='w', encoding='utf-8') as F: dump(self.dict, F, indent=4, separators=(",", ":")) def usbDf(): usbAct('D') def usbEf(): usbAct('E') def usbFf(): usbAct('F') def usbGf(): usbAct('G') def usbHf(): usbAct('H') def usbIf(): usbAct('I') def usbJf(): usbAct('J') def usbKf(): usbAct('K') def usbLf(): usbAct('L') def usbMf(): usbAct('M') def usbNf(): usbAct('N') def usbOf(): usbAct('O') def usbPf(): usbAct('P') def usbQf(): usbAct('Q') def usbRf(): usbAct('R') def usbSf(): usbAct('S') def usbTf(): usbAct('T') def usbUf(): usbAct('U') def usbVf(): usbAct('V') def usbWf(): usbAct('W') def usbXf(): usbAct('X') def usbYf(): usbAct('Y') def usbZf(): usbAct('Z') # Checkbutton self.usbD = Checkbutton(self.usbText, text="D盘", bg='white', command=usbDf) self.usbE = Checkbutton(self.usbText, text="E盘", bg='white', command=usbEf) self.usbF = Checkbutton(self.usbText, text="F盘", bg='white', command=usbFf) self.usbG = Checkbutton(self.usbText, text="G盘", bg='white', command=usbGf) self.usbH = Checkbutton(self.usbText, text="H盘", bg='white', command=usbHf) self.usbI = Checkbutton(self.usbText, text="I盘", bg='white', command=usbIf) self.usbJ = Checkbutton(self.usbText, text="J盘", bg='white', command=usbJf) self.usbK = Checkbutton(self.usbText, text="K盘", bg='white', command=usbKf) self.usbL = Checkbutton(self.usbText, text="L盘", bg='white', command=usbLf) self.usbM = Checkbutton(self.usbText, text="M盘", bg='white', command=usbMf) self.usbN = Checkbutton(self.usbText, text="N盘", bg='white', command=usbNf) self.usbO = Checkbutton(self.usbText, text="O盘", bg='white', command=usbOf) self.usbP = Checkbutton(self.usbText, text="P盘", bg='white', command=usbPf) self.usbQ = Checkbutton(self.usbText, text="Q盘", bg='white', command=usbQf) self.usbR = Checkbutton(self.usbText, text="R盘", bg='white', command=usbRf) self.usbS = Checkbutton(self.usbText, text="S盘", bg='white', command=usbSf) self.usbT = Checkbutton(self.usbText, text="T盘", bg='white', command=usbTf) self.usbU = Checkbutton(self.usbText, text="U盘", bg='white', command=usbUf) self.usbV = Checkbutton(self.usbText, text="V盘", bg='white', command=usbVf) self.usbW = Checkbutton(self.usbText, text="W盘", bg='white', command=usbWf) self.usbX = Checkbutton(self.usbText, text="X盘", bg='white', command=usbXf) self.usbY = Checkbutton(self.usbText, text="Y盘", bg='white', command=usbYf) self.usbZ = Checkbutton(self.usbText, text="Z盘", bg='white', command=usbZf) self.usbText.window_create('insert', window=self.usbD) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbE) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbF) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbG) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbH) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbI) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbJ) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbK) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbL) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbM) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbN) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbO) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbP) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbQ) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbR) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbS) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbT) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbU) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbV) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbW) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbX) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbY) self.usbText.insert('insert', '\n') self.usbText.window_create('insert', window=self.usbZ) # ScrollBar self.usbScrollBar = Scrollbar(self.usbFrame, width=20, orient='vertical') # Button fuction def throughf(): self.copyTo = filedialog.askdirectory() with open(path + 'info/config.json', encoding='utf-8') as f: if f.readlines() == []: with open(path + 'info/config.json', mode='w', encoding='utf-8') as F: self.dict = {"copyTo": self.copyTo} dump(self.dict, F, indent=4, separators=(",", ":")) else: with open(path + 'info/config.json', encoding='utf-8') as F: self.dict = load(F) self.dict["copyTo"] = self.copyTo with open(path + 'info/config.json', mode='w', encoding='utf-8') as F: dump(self.dict, F, indent=4, separators=(",", ":")) self.copyToPath.set(self.copyTo) def startUpButtonf(): if self.startUpChoice == False: Popen( 'copy ' + winPath + 'startup\\startup.exe "C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp"', shell=True) with open('C:/Easy USB Backup Info.pyc', mode='w') as i: i.write(winPath + "main.exe") Log("开机自启已选择") self.startUpText.set("开机自启") self.startUpChoice = True elif self.startUpChoice == True: Popen( 'del ' + '"C:\\ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\StartUp\\startup.exe"', shell=True) Log("开机不自启已选择") self.startUpText.set("开机不自启") self.startUpChoice = False def Helpf(): Log("Help window starts") # Help window self.helP = Toplevel() self.helP.geometry('500x318') self.helP.title('Easy USB Backup') self.helP.iconbitmap(path + 'material/a.ico') self.helP.resizable(0, 0) # Extensions self.helPBar = Scrollbar(self.helP, orient='vertical', width=20) self.helPText = Text(self.helP, width=68, yscrollcommand=self.helPBar.set) with open(path + 'material/h.pyc', encoding='utf-8') as file: helPContent = file.readlines() for i in helPContent: self.helPText.insert('insert', i) self.helPText.config(state='disabled') self.helPBar.config(command=self.helPText.yview) # Display self.helPText.place(x=0, y=0) self.helPBar.pack(side='right', fill='y') self.helP.mainloop() def Hidef(): self.win.withdraw() messagebox.showinfo("Easy USB Backup", "窗口已隐藏,按下alt来还原窗口") def onPress(key): try: i = [] i.append(str(key.char)) del i except AttributeError: if str(key) == 'Key.alt_l': self.win.deiconify() listener.stop() def onRelease(key): pass listener = pynput.keyboard.Listener(on_press=onPress, on_release=onRelease) listener.start() def LogLook(): Popen('"' + winPath + 'Easy USB Backup.log"', shell=True) def Killf(): Popen('taskkill /f /im main.exe', shell=True) def BackupLook(): try: i1 = -1 i = list(self.copyTo) for I in i: i1 += 1 if I == "/": i[i1] = "\\" i = ''.join(i) del i1 Popen('explorer ' + i, shell=True) del i except: messagebox.showerror("Easy USB Backup", "请先选择备份目录") def Startf(): if messagebox.showinfo("Easy USB Backup", " 程序已开始, 请勿多次点击开始备份按钮") == 'ok': def BackupRun(): with open(path + 'info/config.json', encoding='utf-8') as f: q = f.readlines() if q == []: Log("Json file is empty") messagebox.showerror("Easy USB Backup", " 设置错误 ") else: Log("Json file has items") with open(path + 'info/config.json', encoding='utf-8') as f: i = load(f) order = 1 try: time = i['time'] config1 = i['config1'] config2 = i['config2'] copyTo = i['copyTo'] usbChoiceList = list(i['usbChoiceList']) order = 0 except: Log("Json file is not currect") messagebox.showerror("Easy USB Backup", " 设置错误 ") if list(copyTo)[-1] != '/': copyTo += '/' if order == 0: usbChoiceList.remove('[') usbChoiceList.remove(']') # change list def ChangeUSBList(content): while True: try: usbChoiceList.remove(content) except ValueError: break ChangeUSBList("'") ChangeUSBList(',') ChangeUSBList(' ') # check usbchoicelist uusbChoiceList = usbChoiceList[:] localDisks = [] order = -1 ordeR = 0 for i in disk_partitions(): if "removable" not in i.opts: localDisks.append(i.mountpoint) for i in usbChoiceList: order += 1 uusbChoiceList[order] += ':\\' usbChoiceList[order] += ':/' if uusbChoiceList[order] in localDisks: a = Tk() a.withdraw() Log("USB choice is wrong") messagebox.showerror( "Easy USB Backup", "您选择的U盘有误, 请重新选择") a.destroy() ordeR = 1 break # Start to detect if ordeR == 0: # Variable order1 = 1 copyedDevices = [] usbDevices = [] position1 = '' position2 = '' # thread function def cpThf(): if config2 == 0: if messagebox.showinfo( 'Easy USB Backup', '检测到有U盘插入') == 'ok': copyedDevices.append(position1) copytree(position1, position2) elif config2 == 1: copyedDevices.append(position1) copytree(position1, position2) while True: Log('Start to detect USB') devices = disk_partitions() for device in devices: if "removable" in device.opts: mountpoint = list( device.mountpoint)[0] + ':/' usbDevices.append(mountpoint) order1 = 0 if copyedDevices != []: for i in copyedDevices: if i not in usbDevices: copyedDevices.remove(i) if order1 == 0: Log('Found USB') # copy starts for device in usbDevices: if (device in usbChoiceList) and ( device not in copyedDevices): position1 = device ddevice = list(device) ddevice.pop() ddevice = ''.join(ddevice) wwinPath = list(winPath) wwinPath[0] = wwinPath[ 0].upper() wwinPath = ''.join(wwinPath) Popen('vol ' + ddevice + ' > ' + wwinPath + 'info\\name.pyc', shell=True) sleep(3) # with open(path + 'info/name.pyc', encoding='unicode_escape') as f: with open(path + 'info/name.pyc', encoding='gbk') as f: usbname = list( f.readlines()[0]) usbName = [] allow = -4 for i in usbname: if allow == 0: if i != '\n': usbName.append(i) elif allow != 0: if i == ' ': allow += 1 usbName = ''.join(usbName) if config1 == 0: now = strftime( '%Y-%m-%d %H-%M-%S') position2 = copyTo + now elif config1 == 1: position2 = copyTo + usbName elif config1 == 2: now = strftime( '%Y-%m-%d %H-%M-%S') position2 = copyTo + now + ', ' + usbName elif config1 == 3: now = strftime( '%Y-%m-%d %H-%M-%S') position2 = copyTo + usbName + ', ' + now cpTh = Thread(target=cpThf, daemon=True) cpTh.start() usbDevices.clear() Log('End detect') sleep(time) BackupTh = Thread(target=BackupRun, daemon=True) BackupTh.start() # Button self.through = Button(self.win, text="浏览", command=throughf, relief=GROOVE, width=8) self.startUpButton = Button(self.win, font=('fangsong', 15), relief=GROOVE, command=startUpButtonf, width=10) self.helpButton = Button(self.win, text="使用必读", relief=GROOVE, width=10, font=('fangsong', 15), command=Helpf) self.hideButton = Button(self.win, text="隐藏", relief=GROOVE, width=10, font=('fangsong', 15), command=Hidef) self.logButton = Button(self.win, text="日志文件", relief=GROOVE, width=10, font=('fangsong', 15), command=LogLook) self.killButton = Button(self.win, text="结束任务", relief=GROOVE, width=10, font=('fangsong', 15), command=Killf) self.BackupButton = Button(self.win, text="备份目录", relief=GROOVE, width=10, font=('fangsong', 15), command=BackupLook) self.startButton = Button(self.win, text="开始备份", relief=GROOVE, width=10, font=('fangsong', 15), command=Startf) # Config self.usbText.config(state='disabled', cursor='arrow') self.usbText.configure(yscrollcommand=self.usbScrollBar.set) self.usbScrollBar.config(command=self.usbText.yview) # Display # StartUpButton self.startUpButton.place(x=540, y=50) self.startUpText = StringVar() self.startUpText.set("开机不自启") self.startUpButton.config(textvariable=self.startUpText) # Location self.location.place(x=19, y=380) self.copyToPath = StringVar() self.location.config(textvariable=self.copyToPath) # Others self.through.place(x=443, y=380) self.usbText.pack(side='left') self.usbScrollBar.pack(side='right', fill='y') self.canvas.place(x=0, y=0) self.usbFrame.place(x=19, y=45) self.helpButton.place(x=540, y=100) self.hideButton.place(x=540, y=150) self.logButton.place(x=540, y=200) self.killButton.place(x=540, y=250) self.BackupButton.place(x=540, y=300) self.startButton.place(x=540, y=350) # Loop self.win.mainloop() Log("=========Program ends=========")
class PageOptions(): def __init__(self): self.root = Tk() self.createWidgets() self.root.mainloop() def initialize_variables(self): # Initial size of the app self.HEIGHT = 600 self.WIDTH = 800 self.root.title("Categorization Dialog Widget") self.root.minsize(750, 550) def createWidgets(self): self.initialize_variables() # Background self.canvas = Canvas(self.root, height=self.HEIGHT, width=self.WIDTH) self.background_label = Label(self.root, bg='#3C1E5F') self.background_label.place(relwidth=1, relheight=1) self.canvas.pack() # Upper frame with logo and info message self.higher_frame = Frame(self.root, bg='#FFD164', bd=5) self.higher_frame.place(relx=0.5, rely=0.1, relwidth=0.85, relheight=0.35, anchor='n') self.logo = Canvas(self.higher_frame, bd=1) self.logo.place(relx=0, rely=0, relwidth=1, relheight=0.5) self.img = PhotoImage(file="logo.png") self.img = self.img.subsample(6) self.logo.create_image(0, 0, anchor='nw', image=self.img) self.var = "Sentiment Classification and Categorization of txt files" self.infoMessage = Message(self.higher_frame, text=self.var, justify='center', width=350, font=("Courier bold", 16)) self.infoMessage.place(relx=0.4, rely=0.05, relwidth=0.5, relheight=0.3) # Menubar with Option, Result and Direct input self.menubar() # Lower frame with scrollbars for displaying of categories and file names self.lower_frame = Frame(self.root, bg='#FFD164', bd=5) self.lower_frame.place(relx=0.5, rely=0.35, relwidth=0.85, relheight=0.55, anchor='n') self.lower_frame.grid_rowconfigure(0, weight=1) self.lower_frame.grid_columnconfigure(0, weight=1) self.optionCanvas = Canvas(self.lower_frame, bg='white', bd=3) self.optionCanvas.place(relwidth=1, relheight=1) # select language (English or Swedish) self.selectLanguage(self.optionCanvas) # open folder with input files self.openFolder = Label(self.optionCanvas, text="Open a folder with input files", justify='left', bg='white', font=("Courier bold", 12)) self.openFolder.place(relx=0.1, rely=0.4, relwidth=0.3, relheight=0.2) self.button = Button(self.optionCanvas, text="Browse", font=("Courier", 12), bg='#EE7C7D', activebackground='#f2d9e6', command=lambda: self.fileDialog()) self.button.place(relx=0.5, rely=0.4, relwidth=0.3, relheight=0.15) # save result in excel file self.CheckVar = IntVar() self.excelFileCheckbutton = Checkbutton(self.optionCanvas, text="Save as excel", variable=self.CheckVar, \ onvalue=1, offvalue=0, bg='white', font=("Courier bold", 12), height=5, width=20) self.excelFileCheckbutton.place(relx=0.1, rely=0.6, relwidth=0.3, relheight=0.15) # Middle frame with buttons bar def menubar(self): self.middle_frame = Frame(self.root, bg='#FFD164', bd=5) self.middle_frame.place(relx=0.5, rely=0.25, relwidth=0.85, relheight=0.1, anchor='n') self.button = Button(self.middle_frame, text="Options", font=("Courier", 12), bg='#EE7C7D', activebackground='#f2d9e6', command=lambda: self.fileDialog()) self.button.place(relx=0.1, relwidth=0.2, relheight=1) self.button = Button(self.middle_frame, text="Result", font=("Courier", 12), bg='#EE7C7D', activebackground='#f2d9e6', command=lambda: self.fileDialog()) self.button.place(relx=0.4, relwidth=0.2, relheight=1) self.button = Button(self.middle_frame, text="Direct input", font=("Courier", 12), bg='#EE7C7D', activebackground='#f2d9e6', command=lambda: self.fileDialog()) self.button.place(relx=0.7, relwidth=0.2, relheight=1) # select language (English or Swedish) def selectLanguage(self, parentWidget): # Create a Tkinter variable self.tkvar = StringVar() # Dictionary with options self.choices = {'English', 'Swedish'} self.tkvar.set('English') # set the default option # Popup menu with languages self.popupMenu = OptionMenu(parentWidget, self.tkvar, *self.choices) self.popupLabel = Label(parentWidget, text="Choose a language", bg='white', justify='left', font=("Courier bold", 12)) self.popupLabel.place(relx=0.1, rely=0.1, relwidth=0.3, relheight=0.2) self.popupMenu.configure(bd=3, bg='#EE7C7D') self.popupMenu.place(relx=0.5, rely=0.1, relwidth=0.3, relheight=0.15) # on change dropdown value def change_dropdown(*args): print(self.tkvar.get()) # link function to change dropdown self.tkvar.trace('w', change_dropdown) # Gets the selected folder by the user and uses keywordSearch in txt files, then presents categories and file names def fileDialog(self): try: self.folderSelected = filedialog.askdirectory() self.categorizer = Categorizer(self.folderSelected) self.dict_obj = self.categorizer.categorizeFilesFromDirectoryInMapAndSubDirectory() self.results.insert(END, "Category".ljust(20, ' ') + "File name") self.results.insert(END, "\n") for key, val in self.dict_obj.items(): self.results.insert(END, str(key).ljust(20, ' ') + str(val)) except UnicodeDecodeError: self.results.insert(END, "Selected folder does not contain txt files.")
def initUI(self): # self.master.title('Выберите параметры для анализа') self.pack(fill=BOTH, expand=True) #self.var = BooleanVar() self.parent.title('Выберите параметры для анализа') #self.style = Style() #self.style.theme_use("default") #names = ['Выравнивание абзаца', 'Отступ перед абзацем(см)', 'Отступ после абзаца(см)', 'Отступ слева(см)', # 'Отступ справа(см)', 'Отступ первой строки абзаца(см)', 'Не отрывать от следующего абзаца', # 'Не разрывать абзац', 'Абзац с новой страницы', 'Запрет висячих строк', 'Курсивный текст', # 'Полужирный текст', 'Подчёркнутый текст', 'Название шрифта', 'Размер шрифта(кегль)', # 'Цвет текста, RGB', 'Цвет заливки текста', 'Начать анализ'] self.var1 = BooleanVar() cb1 = Checkbutton(self, text='Выравнивание абзаца', variable=self.var1) cb1.place(x=20, y=20) self.var2 = BooleanVar() cb1 = Checkbutton(self, text='Отступ перед абзацем(см)', variable=self.var2) cb1.place(x=20, y=40) self.var3 = BooleanVar() cb1 = Checkbutton(self, text='Отступ после абзаца(см)', variable=self.var3) cb1.place(x=20, y=60) self.var4 = BooleanVar() cb1 = Checkbutton(self, text='Отступ слева(см)', variable=self.var4) cb1.place(x=20, y=80) self.var5 = BooleanVar() cb1 = Checkbutton(self, text='Отступ справа(см)', variable=self.var5) cb1.place(x=20, y=100) self.var6 = BooleanVar() cb1 = Checkbutton(self, text='Отступ первой строки абзаца(см)', variable=self.var6) cb1.place(x=20, y=120) self.var7 = BooleanVar() cb1 = Checkbutton(self, text='Не отрывать от следующего абзаца', variable=self.var7) cb1.place(x=20, y=140) self.var8 = BooleanVar() cb1 = Checkbutton(self, text='Не разрывать абзац', variable=self.var8) cb1.place(x=20, y=160) self.var9 = BooleanVar() cb1 = Checkbutton(self, text='Абзац с новой страницы', variable=self.var9) cb1.place(x=20, y=180) self.var10 = BooleanVar() cb1 = Checkbutton(self, text='Запрет висячих строк', variable=self.var10) cb1.place(x=20, y=200) self.var11 = BooleanVar() cb1 = Checkbutton(self, text='Курсивный текст', variable=self.var11) cb1.place(x=20, y=220) self.var12 = BooleanVar() cb1 = Checkbutton(self, text='Полужирный текст', variable=self.var12) cb1.place(x=20, y=240) self.var13 = BooleanVar() cb1 = Checkbutton(self, text='Подчёркнутый текст', variable=self.var13) cb1.place(x=20, y=260) self.var14 = BooleanVar() cb1 = Checkbutton(self, text='Название шрифта', variable=self.var14) cb1.place(x=20, y=280) self.var15 = BooleanVar() cb1 = Checkbutton(self, text='Размер шрифта(кегль)', variable=self.var15) cb1.place(x=20, y=300) self.var16 = BooleanVar() cb1 = Checkbutton(self, text='Цвет текста, RGB', variable=self.var16) cb1.place(x=20, y=320) self.var17 = BooleanVar() cb1 = Checkbutton(self, text='Цвет заливки текста', variable=self.var17) cb1.place(x=20, y=340) self.var18 = BooleanVar() #cb[i] = Checkbutton(self, text=names[i], variable=self.var, command=self.onClick) #cb1.place(x=50, y=50) self.pack(fill=BOTH, expand=1) quitButton = Button(self, text='Начать анализ', command=self.quit) quitButton.place(x=200, y=200) print(self.var1.get()) print(self.var2.get()) print(self.var3.get()) print(self.var4.get()) print(self.var5.get()) print(self.var6.get()) print(self.var7.get()) print(self.var8.get()) print(self.var9.get()) print(self.var10.get()) print(self.var11.get()) print(self.var12.get()) print(self.var13.get()) print(self.var14.get()) print(self.var15.get()) print(self.var16.get()) print(self.var17.get())
class SearchHelper: def __init__(self, searchframe): self.frame = searchframe # keyword entry largefont = ('Veranda', 24) self.ent_keyword = Entry(self.frame, width=40, relief='raised', font=largefont, bd=1) # todo <Return> and entry is not empty call search() self.but_search = Button( self.frame, text='Search', width=15, state='disable', font="Veranda 16", command=lambda: self.frame.search( 'http://cbrown686-test.apigee.net/cyberapi/articles?q=keywordtitlebody&title=' + self.ent_keyword.get() + '&body=' + self.ent_keyword.get())) self.var = IntVar() self.var.set(0) self.check_filter = Checkbutton(self.frame, text="Advanced Filter", onvalue=1, offvalue=0, variable=self.var, command=self.filter_op, font="Veranda 16") calltipwindow.createToolTip( self.check_filter, "Click here for options to narrow your search") calltipwindow.createToolTip( self.ent_keyword, "Enter a word or phrase here to search by.") self.ent_keyword.bind('<Escape>', self.clear_text) self.ent_keyword.bind( '<Key>', lambda event: self.callenable(event, 'DefaultSearch')) if self.var.get(): self.frame.searchButton(None) # filter stuff self.appearing_label = Label(searchframe, text='Appearing In:', background='#282828', font=15, foreground='#5DE0DC') self.box_value = StringVar() self.box = Combobox(searchframe, textvariable=self.box_value) calltipwindow.createToolTip( self.appearing_label, "Select where you want us to search " "for your provided search phrase.") calltipwindow.createToolTip( self.box, "Select where you want us to search " "for your provided search phrase.") self.box['values'] = ('Default', 'Title', 'Body', 'URL') self.box.current(0) self.box.bind('<<ComboboxSelected>>', self.setbaseurl) # author self.author_label = Label(searchframe, text='Author:', background='#282828', font=15, foreground='#5DE0DC') self.author_entry = Entry(searchframe, width=22, bd=2, background='#9A9A9A') calltipwindow.createToolTip( self.author_label, "Enter an author's first and/or last name (not case-sensitive).") calltipwindow.createToolTip( self.author_entry, "Enter an author's first and/or last name (not case-sensitive).") # subjectivity self.fsub_label = Label(searchframe, text='Subjectivity:', background='#282828', font=15, foreground='#5DE0DC') calltipwindow.createToolTip( self.fsub_label, "Choose an option here if you only want to see articles" " that are more objectively or subjectively written") self.var2 = IntVar() self.var2.set(1) self.fsub_nv = Radiobutton(searchframe, text="Don't Care", variable=self.var2, value=1, background='#282828', foreground='#5DE0DC') calltipwindow.createToolTip( self.fsub_nv, "Select this if you want all articles returned regarless of how they are written." ) self.fsub_gt = Radiobutton(searchframe, text='More Subjective', variable=self.var2, value=2, background='#282828', foreground='#5DE0DC') calltipwindow.createToolTip( self.fsub_gt, "Select this if you only want articles that are more subjectively written." ) self.fsub_lt = Radiobutton(searchframe, text='More Objective', variable=self.var2, value=3, background='#282828', foreground='#5DE0DC') calltipwindow.createToolTip( self.fsub_lt, "Select this if you only want articles that are more objectively written." ) # date self.fD_label = Label(searchframe, text='Date:', background='#282828', font=15, foreground='#5DE0DC') self.fD_format = Label(searchframe, text='00/00/0000', background='#282828', foreground='#BBBBBB') self.fD_format.configure(foreground='grey') self.fD_beinlab = Label(searchframe, text='From:', background='#282828', foreground='#BBBBBB') self.fD_endlab = Label(searchframe, text='To:', background='#282828', foreground='#BBBBBB') self.fD_ent = Entry(searchframe, width=10, bd=2, background='#9A9A9A') self.fD_ent.insert('end', '01/01/0001') self.fD_ent2 = Entry(searchframe, width=10, bd=2, background='#9A9A9A') self.fD_ent2.insert('end', strftime('%m/%d/%Y')) calltipwindow.createToolTip( self.fD_label, "Narrow your results to articles published in the dates here.") calltipwindow.createToolTip( self.fD_format, "Narrow your results to articles published in the dates here.") calltipwindow.createToolTip( self.fD_beinlab, "Narrow your results to articles published in the dates here.") calltipwindow.createToolTip( self.fD_endlab, "Narrow your results to articles published in the dates here.") calltipwindow.createToolTip(self.fD_ent, "Enter Start Date here.") calltipwindow.createToolTip(self.fD_ent2, "Enter End Date here.") # filter placements offset = 100 self.appearing_label.place(x=400, y=380 + offset) # appearing pick self.box.place(x=510, y=380 + offset) # author label self.author_label.place(x=400, y=405 + offset) # author entry self.author_entry.place(x=510, y=405 + offset) # subjectivity self.fsub_label.place(x=400, y=430 + offset) self.fsub_nv.place(x=510, y=430 + offset) self.fsub_gt.place(x=510, y=455 + offset) self.fsub_lt.place(x=510, y=480 + offset) # date self.fD_label.place(x=400, y=505 + offset) self.fD_format.place(x=445, y=507 + offset) self.fD_beinlab.place(x=510, width=45, y=505 + offset) self.fD_ent.place(x=555, width=65, y=505 + offset) self.fD_endlab.place(x=630, y=505 + offset) self.fD_ent2.place(x=660, width=65, y=505 + offset) # buttons self.but_search.place(relx=.505, rely=.6, anchor=W) # ENTRY BOX for keyword self.ent_keyword.place(relx=.5, rely=.5, anchor=CENTER) # check button self.check_filter.place(relx=.495, rely=.6, relheight=.059, anchor=E) self.hidefilters() #filter options populate uppon check box of Advanced search option def filter_op(self): if self.var.get() is 1: self.showfilters() else: self.hidefilters() def resetsearch(self): self.ent_keyword.destroy() self.but_search.destroy() self.check_filter.destroy() self.appearing_label.destroy() self.box.destroy() self.author_label.destroy() self.author_entry.destroy() self.fsub_label.destroy() self.fsub_nv.destroy() self.fsub_gt.destroy() self.fsub_lt.destroy() self.fD_label.destroy() self.fD_format.destroy() self.fD_ent.destroy() self.fD_beinlab.destroy() self.fD_endlab.destroy() self.fD_ent2.destroy() self.__init__(self.frame) def hidefilters(self): self.appearing_label.lower() self.box.lower() self.author_label.lower() self.author_entry.lower() self.fsub_label.lower() self.fsub_nv.lower() self.fsub_gt.lower() self.fsub_lt.lower() self.fD_label.lower() self.fD_format.lower() self.fD_ent.lower() self.fD_beinlab.lower() self.fD_endlab.lower() self.fD_ent2.lower() def showfilters(self): self.appearing_label.lift() self.box.lift() self.author_label.lift() self.author_entry.lift() self.fsub_label.lift() self.fsub_nv.lift() self.fsub_gt.lift() self.fsub_lt.lift() self.fD_label.lift() self.fD_format.lift() self.fD_ent.lift() self.fD_beinlab.lift() self.fD_endlab.lift() self.fD_ent2.lift() def showsearch(self): self.ent_keyword.lift() self.but_search.lift() self.check_filter.lift() if self.var.get(): self.showfilters() def hidesearch(self): self.ent_keyword.lower() self.but_search.lower() self.check_filter.lower() def setbaseurl(self, event): if self.box.current() is 0: self.but_search.config(command=lambda: self.frame.search( 'http://cbrown686-test.apigee.net/cyberapi/articles?q=keywordtitlebody&title=' + self.ent_keyword.get() + '&body=' + self.ent_keyword.get())) elif self.box.current() is 1: self.but_search.config(command=lambda: self.frame.search( 'http://cbrown686-test.apigee.net/cyberapi/articles?q=keywordtitle&title=' + self.ent_keyword.get())) elif self.box.current() is 2: self.but_search.config(command=lambda: self.frame.search( 'http://cbrown686-test.apigee.net/cyberapi/articles?q=bodyonly&body=' + self.ent_keyword.get())) elif self.box.current() is 3: self.but_search.config(command=lambda: self.frame.search( 'http://cbrown686-test.apigee.net/cyberapi/articles?q=uri&uripath=' + self.ent_keyword.get())) def addurlfilters(self, url): if self.var.get(): au = self.author_entry.get() au = au.replace(' ', '+') # var2 is the state of the radio check button if self.var2.get() == 2: url = url + '&author=' + au + '&sub=gt&sdate=' + self.fD_ent.get( ) + '&edate=' + self.fD_ent2.get() # print(url) elif self.var2.get() == 3: url = url + '&author=' + au + '&sub=gt&sdate=' + self.fD_ent.get( ) + '&edate=' + self.fD_ent2.get() else: url = url + '&author=' + au + '&sub=&sdate=' + self.fD_ent.get( ) + '&edate=' + self.fD_ent2.get() else: url = url + '&author=&sub=&sdate=01/01/0001&edate=' + strftime( '%m/%d/%Y') return url # Hitting escape when editing the ENTRY box will clear it and disable the search button from being able to be used. def clear_text(self): self.ent_keyword.delete(0, 'end') self.but_search.configure(state='disable') def callenable(self, event, searchtype): self.frame.after(100, lambda: self.enablesearch(event, searchtype)) # event bind when Return is entered after a title keyword is entered will enable the search button. def enablesearch(self, event, searchtype): string = '' if searchtype == 'DefaultSearch': string = self.ent_keyword.get() if string.strip() != '': self.but_search.configure(state='normal') else: self.but_search.configure(state='disabled')
def __init__(self, master, title, x_coor, y_coor, data, variant=False): self.__chb_var = IntVar() self.__state = StringVar() self.__count = StringVar() self.__xObs = StringVar() self.__p_value = StringVar() self.__result = StringVar() self.__results = [] self.__variant = variant checkbox = Checkbutton(master, text=title, variable=self.__chb_var) checkbox.place(x=x_coor, y=y_coor) state_label = LabelTag(master, 'State', (x_coor + 60), (y_coor + 30), width=100, font_size=12, border=2, relief='groove') if variant: self.__state.set('-1.0') else: self.__state.set('+1') state_option = OptionMenu(master, self.__state, *data) state_option.place(x=(x_coor + 60), y=(y_coor + 60), height=25, width=100) if not variant: xObs_label = LabelTag(master, 'CHI-SQUARED', (x_coor + 165), (y_coor + 30), width=350, font_size=12, border=2, relief='groove') xObs_Entry = Entry(master, textvariable=self.__xObs) xObs_Entry.place(x=(x_coor + 165), y=(y_coor + 60), width=350, height=25) else: count_label = LabelTag(master, 'Count', (x_coor + 165), (y_coor + 30), width=350, font_size=12, border=2, relief='groove') count_Entry = Entry(master, textvariable=self.__count) count_Entry.place(x=(x_coor + 165), y=(y_coor + 60), width=350, height=25) pass p_value_label = LabelTag(master, 'P-Value', (x_coor + 520), (y_coor + 30), width=350, font_size=12, border=2, relief='groove') p_value_Entry = Entry(master, textvariable=self.__p_value) p_value_Entry.place(x=(x_coor + 520), y=(y_coor + 60), width=350, height=25) conclusion_label = LabelTag(master, 'Conclusion', (x_coor + 875), (y_coor + 30), width=150, font_size=12, border=2, relief='groove') conclusion_Entry = Entry(master, textvariable=self.__result) conclusion_Entry.place(x=(x_coor + 875), y=(y_coor + 60), width=150, height=25) update_button = Button(master, text='Update', command=self.update) update_button.config(font=("Calibri", 10)) update_button.place(x=(x_coor + 1030), y=(y_coor + 60), width=180, height=25)
def __init__(self): # The main window self.root = Tk(className=" Virtual led matrix") self.root.geometry("%sx%s" % (WINDOW_WIDTH, WINDOW_HEIGHT)) self.root.configure(background=BG_COLOR) # The canvas we draw LEDs on self.canvas = Canvas(self.root, background=BG2_COLOR, highlightthicknes=0, width=CANVAS_WIDTH, height=CANVAS_HEIGHT) self.canvas.place(x=GENERAL_SPACING, y=GENERAL_SPACING) # The widgets posing as leds self.grid_leds = [[self.canvas.create_oval( i * LED_SIZE + 2, j * LED_SIZE + 2, (i + 1) * LED_SIZE - 2, (j + 1) * LED_SIZE - 2, fill="#000000") for j in range(MATRIX_HEIGHT)] for i in range(MATRIX_WIDTH)] # Let's create a canvas for the buttons self.button_canvas = Canvas(self.root, background=BG2_COLOR, highlightthicknes=0) self.button_canvas.place(x=CANVAS_WIDTH + GENERAL_SPACING * 2, y=GENERAL_SPACING, width=BUTTON_CANVAS_WIDTH, height=BUTTON_CANVAS_HEIGHT) # Now let's place the buttons and put them in the list self.buttons = [] self.buttons_down = [] for i in range(NUM_BUTTONS): x = (i + 1) * BUTTON_SPACING + i * BUTTON_WIDTH y = BUTTON_SPACING button = self.button_canvas.create_rectangle( x, y, (i + 1) * BUTTON_SPACING + (i + 1) * BUTTON_WIDTH, BUTTON_SPACING + BUTTON_HEIGHT, fill=BUTTON_UP_COLOR, ) self.buttons.append(button) self.buttons_down.append(False) for i in range(NUM_BUTTONS): x = (i + 1) * BUTTON_SPACING + (i + 0.5) * BUTTON_WIDTH y = BUTTON_SPACING + BUTTON_HEIGHT*0.5 self.button_canvas.create_text(x, y, text="BTN%i" % i) # When buttons are pressed/released, execute functions to handle it self.button_canvas.bind('<Button-1>', self.button_clicked) self.button_canvas.bind('<ButtonRelease-1>', self.button_released) # Let's create a canvas for the switches self.switch_canvas = Canvas(self.root, background=BG2_COLOR, highlightthicknes=0) self.switch_canvas.place(x=CANVAS_WIDTH + GENERAL_SPACING * 2, y=BUTTON_CANVAS_HEIGHT + GENERAL_SPACING * 2, width=SWITCH_CANVAS_WIDTH, height=SWITCH_CANVAS_HEIGHT) # Now let's place the switches and put them in the list self.switches = [] self.switches_activated = [] for i in range(NUM_SWITCHES): self.switches_activated.append(IntVar()) switch = Checkbutton(self.switch_canvas, text="SW%i" % i, var=self.switches_activated[i]) switch.place(x=(i + 1) * SWITCH_SPACING + i * SWITCH_WIDTH, y=SWITCH_SPACING, width=SWITCH_WIDTH, height=SWITCH_HEIGHT) self.switches.append(switch) self.slider_canvas = Canvas(self.root, background=BG2_COLOR, highlightthicknes=0) self.slider_canvas.place(x=GENERAL_SPACING, y=CANVAS_HEIGHT + GENERAL_SPACING * 2, width=SLIDER_CANVAS_WIDTH, height=SLIDER_CANVAS_HEIGHT) self.sliders = [] for i in range(NUM_SLIDERS): slider = Scale(self.slider_canvas, from_=SLIDER_MIN, to=SLIDER_MAX, orient="horizontal", label="Sensor %i:" % i) slider.place(x=SLIDER_SPACING, y=i*SLIDER_HEIGHT + (i+1)*SLIDER_SPACING, width=SLIDER_WIDTH, height=SLIDER_HEIGHT) self.sliders.append(slider) self.closed = False self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
def create_add_multiple_points_check(self): check_state = BooleanVar() add_multiple_points_check = Checkbutton(self, text="Add multiple points", bg="white", var=check_state, onvalue=1, offvalue=0, command=self.add_multiple_points_clb) add_multiple_points_check.place(x=10, y=90) return add_multiple_points_check, check_state
class GeoDemonstrator(Tk, GeoMixinTrans, GeoMixinHelp): # Konstruktor aplikacije def __init__(self): # Log poruka o pokretanju aplikacije print('Dobro došli u aplikaciju GeoDemonstrator!') # Pozivanje konstruktora roditeljske klase super().__init__() # Postavljanje naziva aplikacije self.title('GeoDemonstrator') # Inicijalizacija liste tačaka self.tačke = [] self.ttačke = [] # Inicijalizacija liste identifikatora # na platnu trenutno iscrtanih tačaka self.id_tač = [] # Inicijalizacija figure self.figura = None # Inicijalizacija transformacija iz platna # u iscrtani koordinatni sistem i obrnuto self.puk = Skal(1 / 7, -1 / 7) * Trans(-204, -132) self.kup = Trans(204, 132) * Skal(7, -7) # Inicijalizacija elemenata GKI self.init_gki() # Inicijalizacija elemenata GKI def init_gki(self): # Postavljanje veličine i pozicije prozora self.geometry('450x450+75+75') # Onemogućavanje promene veličine prozora, # pošto je Tk prilično plastičan, pa promene # ugrožavaju zamišljeni izgled aplikacije self.resizable(False, False) # Inicijalizacija glavnog menija self.init_meni() # Inicijalizacija platna self.init_platno() # Kontrola unosa tačaka self.init_unos() # Inicijalizacija glavnog menija def init_meni(self): # Pravljenje glavnog menija meni = Menu(self) # Postavljanje sporednog padajućeg menija self.umeni = Menu(meni) self.umeni.add_command(label='Zaključi unos', command=self.promena_unosa) self.umeni.add_command(label='Ispravi figuru', command=self.ispravi) self.umeni.add_command(label='Očisti platno', command=partial(self.novo_platno, True)) # Postavljanje glavnog menija i vezivanje # komandi za odgovarajuće funkcionalnosti meni.add_cascade(label='Opcije', menu=self.umeni) meni.add_command(label='Pomoć (H)', command=self.pomoć) meni.add_command(label='Info (G)', command=self.info) self.config(menu=meni) # Vezivanje tipki za akcije analogne # onima iz prethodno postavljenog menija; # od F1 se odustalo jer se ne ponaša kako # treba na operativnom sistemu Windows self.bind('<H>', self.pomoć) self.bind('<h>', self.pomoć) self.bind('<G>', self.info) self.bind('<g>', self.info) self.bind('<Escape>', self.kraj) # Vezivanje protokola zatvaranja prozora # za istu akciju kao za Kraj i Escape self.protocol('WM_DELETE_WINDOW', self.kraj) # Inicijalizacija platna def init_platno(self): # Pravljenje okvira za platno okvir_p = LabelFrame(self, text='Zakoračite u svet geometrijskih' ' transformacija', padx=10, pady=10) okvir_p.place(x=10, y=10, height=300, width=430) # Postavljanje platna unutar okvira self.platno = Canvas(okvir_p, height=261, width=405) self.platno.place(x=0, y=0) # Postavljanje koordinatnog sistema na platno; # slika nije lokalna promenljiva, pošto bi je u # tom slučaju 'pojeo' sakupljač otpadaka self.slika = self.učitaj_sliku('koord.gif') self.platno.create_image(203, 131, image=self.slika) # Vezivanje čuvanja tačke za klik na platno self.unos = True self.platno.bind('<Button-1>', self.dodaj_tačku) # Vezivanje promene unosa za desni klik, # a ispravljanja figure za srednji, prema # sugestiji asistenta, čime se dobija na # lakoći korišćenja, bez potrebe za menijem self.platno.bind('<Button-2>', self.ispravi) self.platno.bind('<Button-3>', self.promena_unosa) # Okvir za magični svet transformacija def init_unos(self): # Pravljenje okvira za elemente self.okvir_d = LabelFrame(self, text='Unosite tačke klikovima' ' po platnu', padx=10, pady=10) self.okvir_d.place(x=10, y=315, height=128, width=430) # Inicijalizacija polja sa transformacijama self.init_trans() # Oznake parametara koje korisnik unosi x_koord_labela = Label(self, text='x:') y_koord_labela = Label(self, text='y:') ugao_labela = Label(self, text='\u03b8:') # Postavljanje oznaka na prozor x_koord_labela.place(x=185, y=348) y_koord_labela.place(x=185, y=375) ugao_labela.place(x=185, y=403) # Polja za unos vrednosti transformacija self.x_koord = Entry(self, width=4, state='disabled') self.y_koord = Entry(self, width=4, state='disabled') self.ugao = Entry(self, width=4, state='disabled') # Postavljanje polja na prozor self.x_koord.place(x=200, y=348) self.y_koord.place(x=200, y=375) self.ugao.place(x=200, y=403) # Postavljanje ostalih elemenata self.init_centar() self.init_inverz() # Transformacijski okvir def init_trans(self): # Mapa za preslikavanje niske u # odgavarajuću klasu transformacije self.funkcije = { 'translacija': Trans, 'skaliranje': Skal, 'smicanje': Smic, 'rotacija': Rot, 'refleksija': Refl } # Pravljenje okvira za odabir transformacije okvir_t = LabelFrame(self, text='Izaberite transformaciju', padx=23, pady=7) okvir_t.place(x=18, y=337, height=95, width=158) # U zavisnosti od vrednosti var koju pročitamo iz # padajućeg menija, poziva se prava transformacija self.tr = StringVar(self) self.tr.set('') # Funkcija za praćenje promenljive; izveštava o odabiru # transformacije i kontroliše pristup poljima za unos # parametara u zavisnosti od odabira; nepakovana lista # argumenata *args je neophodna kako bi se prosledili # (i zanemarili) dodatni podaci o promeni odabira, slično # kao što npr. kolbek funkcije u GLUT-u obavezno primaju # koordinate događaja, iako one često nisu nužan podatak self.tr.trace( 'w', lambda *args: print('Odabrana transformacija:' ' {}.'.format(self.tr.get())) or self.kontrola( )) # Padajuća lista geometrijskih transformacija; # umesto dosad korišćene fje place za postavljanje # objekta na tačno određeno mesto na prozoru, ovde # se koristi pack, koji objekat optimalno spakuje # na raspoloživom prostoru; iz tog razloga je i # roditeljski element upravo transformacioni okvir, # u koji se pakuje, a ne self, kako je dosad bilo OptionMenu(okvir_t, self.tr, 'translacija', 'skaliranje', 'smicanje', 'rotacija', 'refleksija').pack(fill='x') # Dugme za pokretanje transformacije self.dugme_t = Button(okvir_t, text='Transformiši', command=self.transformiši, state='disabled') self.dugme_t.pack(fill='x') # Odabir centra transformacije def init_centar(self): # Promenljiva za praćenje self.centar = StringVar(self) self.centar.set(None) self.centar.trace( 'w', lambda *args: print('Odabran {}' ' za centar transformacije.'.format( self.centar.get())) if self.centar.get() != 'None' else None) # Oznaka za odabir centra odabir_centra = Label(self, text='Centar transformacije:') odabir_centra.place(x=265, y=330) # Dugme za transformaciju sa centrom # u koordinatnom početku self.radio1 = Radiobutton(self, text='centar platna', padx=3, variable=self.centar, value='centar platna', state='disabled', command=partial(self.kontrola, True)) self.radio1.place(x=242, y=350) # Dugme za transformaciju sa centrom # u centru mase (baricentru) figure self.radio2 = Radiobutton(self, text='centar mase', padx=3, variable=self.centar, value='centar mase', state='disabled', command=partial(self.kontrola, True)) self.radio2.place(x=242, y=370) # Dugme za transformaciju sa centrom # u korisnički unetoj tački self.radio3 = Radiobutton(self, text='uneta tačka', padx=3, variable=self.centar, value='korisnički unos', state='disabled', command=partial(self.kontrola, True)) self.radio3.place(x=242, y=390) # Oznake za unos centra transformacija t1_labela = Label(self, text='t1:') t2_labela = Label(self, text='t2:') # Postavljanje oznaka na prozor t1_labela.place(x=360, y=358) t2_labela.place(x=360, y=385) # Polja za unos centra transformacija self.t1_koord = Entry(self, width=4, state='disabled') self.t2_koord = Entry(self, width=4, state='disabled') # Postavljanje polja na prozor self.t1_koord.place(x=380, y=358) self.t2_koord.place(x=380, y=385) # Funkcija za praćenje inverza def init_inverz(self): self.inv = BooleanVar(self) self.inv.trace( 'w', lambda *args: print('Odabrana inverzna' ' transformacija.') if self.inv.get() else print('Odabrana klasična transformacija.')) # Dugme za odabir inverza self.inverz = Checkbutton(self, text='Invertuj promenu', variable=self.inv, state='disabled') self.inverz.place(x=262, y=410)
file_name = StringVar() file_name.set('') file_name_label = Label(root, textvariable=file_name, justify=LEFT, wraplengt=250) file_name_label.place(x=20, y=150) connect_int = IntVar() connect_check = Checkbutton(root, text=u"connect to unity\n(port 5067)", variable=connect_int, onvalue=1, offvalue=0) # connect_check.config(font=("Courier", 12)) connect_check.place(x=160, y=5) debug_int = IntVar() debug_check = Checkbutton(root, text=u"Display in console", variable=debug_int, onvalue=1, offvalue=0) # debug_check.config(font=("Courier", 12)) debug_check.place(x=160, y=50) file_button = Button(text=u'Start', command=execute) file_button.config(font=("Courier", 25)) file_button.place(x=160, y=80) root.mainloop()
opcije="0|||".split("|") else: opcije="0|||".split("|") #else: # os.makedirs("C:\\EOP") # opcije="0||".split("|") t.title('EOP') t.config(bg='green',width = 300,height = 600) c1=Checkbutton(t,text="Remember me",variable=remember,bg='lightblue',activebackground="blue") c1.place(x=105,y=450) if opcije[0]=="1": c1.select() l1=Label(t,text="REGISTER TO EOP",font=("Verdana",18),bg='pink') l1.place(x=40,y=1) l2=Label(t,text="USERNAME:"******"E-MAIL:",bg='pink') l3.place(x=5,y=100) l4=Label(t,text="PASSWORD:",bg='pink') l4.place(x=5,y=150) e1=Entry(t,textvariable=StringVar(t, value='')) e1.place(x=80,y=51) e2=Entry(t,textvariable=StringVar(t, value=''))