class Data_Cell(Cell): def __init__(self, master, variable, anchor=W, bordercolor=None, borderwidth=1, padx=0, pady=0, background=None, foreground=None, font=None): Cell.__init__(self, master, background=background, highlightbackground=bordercolor, highlightcolor=bordercolor, highlightthickness=borderwidth, bd=0) self._message_widget = Message(self, textvariable=variable, font=font, background=background, foreground=foreground) self._message_widget.pack(expand=True, padx=padx, pady=pady, anchor=anchor) self.bind("<Configure>", self._on_configure) def _on_configure(self, event): self._message_widget.configure(width=event.width)
def aviso_aguarde_instalando(self, recente): """ Realizando a atualização """ if self.tp_atualizacao is not None: self.tp_atualizacao.destroy() self.tp_atualizacao = Toplevel(None) self.tp_atualizacao.withdraw() self.tp_atualizacao.focus_force() self.tp_atualizacao.resizable(False, False) self.tp_atualizacao.tk.call('wm', 'iconphoto', self.tp_atualizacao._w, self.icon) self.tp_atualizacao.configure( self.design.dic["aviso_versao_top_level"]) self.tp_atualizacao.grid_columnconfigure(1, weight=1) self.tp_atualizacao.title('Atualizando.... Não feche a Safira!') #try: # self.tp_atualizacao.wm_attributes('-type', 'splash') #except Exception as erro: # print("Erro ao remover barra de titulos => ", erro) fr_atualizaca = Frame(self.tp_atualizacao) lb_versao_dev = Label(fr_atualizaca, text='{:^30}'.format('Aguarde Atualizando!')) lb_versao_tex = Message(fr_atualizaca, text=' ' * 50, width=200) fr_botoes = Frame(fr_atualizaca) bt_atualiza = Button(fr_botoes) fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"]) lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"]) lb_versao_tex.configure(self.design.dic["aviso_versao_ms"]) fr_botoes.configure(self.design.dic["aviso_versao_btn"]) bt_atualiza.configure(self.design.dic["aviso_versao_btn_atualiza"], relief=FLAT) fr_atualizaca.grid_columnconfigure(1, weight=1) fr_botoes.grid_columnconfigure(1, weight=1) fr_botoes.grid_columnconfigure(2, weight=1) fr_atualizaca.grid(row=1, column=1, sticky=NSEW) lb_versao_dev.grid(row=1, column=1) lb_versao_tex.grid(row=2, column=1, sticky=NSEW) fr_botoes.grid(row=3, column=1, sticky=NSEW) j_width = self.tp_atualizacao.winfo_reqwidth() j_height = self.tp_atualizacao.winfo_reqheight() t_width = self.tela.winfo_screenwidth() t_heigth = self.tela.winfo_screenheight() self.tp_atualizacao.geometry("+{}+{}".format( int(t_width / 2) - int(j_width / 2), int(t_heigth / 2) - int(j_height / 2))) self.tp_atualizacao.deiconify() self.tp_atualizacao.update() th = Thread( target=lambda ver=recente, lb=lb_versao_tex, bt_at=bt_atualiza, lb_2=lb_versao_dev: self.aplica_versao(ver, lb, bt_at, lb_2)) th.start()
class OptimusGui(): def __init__(self, master): self.master = master master.title("Optimus Manager Gui") self.warning_label = Label( master, text= "changing graphics configuration requires this to be run as root!") self.warning_label.grid(row=2, column=1, columnspan=3) self.status_output = Message(master, text="getting status...") self.status_output.grid(columnspan=2, row=1, column=1) self.intel_button = Button(master, text="use intel graphics", command=lambda: self.swapGraphics("intel")) self.intel_button.grid(row=3, column=1) self.hybrid_button = Button( master, text="use hybrid graphics", command=lambda: self.swapGraphics("hybrid")) self.hybrid_button.grid(row=3, column=2) self.nvidia_button = Button( master, text="use nvidia graphics", command=lambda: self.swapGraphics("nvidia")) self.nvidia_button.grid(row=3, column=3) self.quit_button = Button(master, text="quit", command=master.quit) self.quit_button.grid(row=4, column=3) self.updateStatus() def swapGraphics(self, swap_val): if swap_val == "intel": # print("swapping to intel!") subprocess.run(["nvidia-optimus-manager", "configure", "intel"]) elif swap_val == "hybrid": # print("swapping to hybrid!") subprocess.run(["nvidia-optimus-manager", "configure", "hybrid"]) elif swap_val == "nvidia": # print("swapping to nvidia!") subprocess.run(["nvidia-optimus-manager", "configure", "nvidia"]) else: print("invalid argument for swapGraphics!") self.updateStatus() def updateStatus(self): print("updating status!") output = subprocess.check_output(["nvidia-optimus-manager", "status"], encoding="ascii") self.status_output.configure(text=output)
def units(self): mainframe = Frame(self.root) mainframe.master.title("Units") mainframe.style = Style() mainframe.style.theme_use("default") message = 'How would you like to measure the EC?' lbl1 = Message(mainframe, text=message) lbl1.pack(expand=True, fill='x') lbl1.bind("<Configure>", lambda e: lbl1.configure(width=e.width - 10)) mainframe.pack(fill=BOTH, expand=True) button1 = Button(mainframe, text="Date", command=lambda: self.save_value("Date")) button1.pack(side=LEFT, padx=5, pady=5) button2 = Button(mainframe, text="Flight Hours", command=lambda: self.save_value("FH")) button2.pack(side=RIGHT, padx=5, pady=5) button3 = Button(mainframe, text="Flight Cycles", command=lambda: self.save_value("FC")) button3.pack(side=RIGHT, padx=5, pady=5) self.root.mainloop()
def create_footer(self, parent_frame): footer = Frame(parent_frame) disclaimer = Message( footer, text=self.config.disclaimer_text, anchor=CENTER ) disclaimer.grid(row=0, pady=2) parent_frame.bind( "<Configure>", lambda e: disclaimer.configure(width=e.width - 20) ) if self.config.requirement_link_text: requirement_link = Text( footer, height=1, bg=disclaimer.cget("bg"), relief=FLAT, font=disclaimer.cget("font"), ) requirement_link.tag_configure("center", justify="center") hyperlinks = HyperlinkManager(requirement_link) requirement_link.insert(INSERT, "Validating: ") requirement_link.insert( INSERT, self.config.requirement_link_text, hyperlinks.add(self.open_requirements), ) requirement_link.tag_add("center", "1.0", "end") requirement_link.config(state=DISABLED) requirement_link.grid(row=1, pady=2) ToolTip(requirement_link, self.config.requirement_link_url) footer.grid_columnconfigure(0, weight=1) footer.pack(fill=BOTH, expand=True) return footer
def value_input(self, unit): self.unit = unit mainframe = Frame(self.root) mainframe.master.title("Units") mainframe.style = Style() mainframe.style.theme_use("default") message = 'What {} range? ex: 10, 100, 750, etc'.format(unit) lbl1 = Message(mainframe, text=message) lbl1.pack(expand=True, fill='x') lbl1.bind("<Configure>", lambda e: lbl1.configure(width=e.width)) mainframe.pack(fill=BOTH, expand=True) self.entrybox = Entry(mainframe) self.entrybox.pack() button = Button(mainframe, text='OK', command=lambda: self.quit_gui()) button.pack() self.root.mainloop()
class YoutubeAudioDownloader: def __init__(self): self.root = Tk() winWidth = int(self.root.winfo_screenwidth() * WIN_WIDTH_RATIO) self.root.geometry("{}x{}".format(winWidth, WIN_HEIGHT)) self.msg = Message(self.root, aspect=winWidth - 10) self.msg.grid(row=2, column=0, columnspan=2, padx=2) self.msgText = '' if os.name == 'posix': configFilePathName = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/youtube_audio_download/audiodownload.ini' else: configFilePathName = 'D:\\Development\\Python\\youtube_audio_download\\audiodownload.ini' self.configMgr = ConfigManager(configFilePathName) self.emailLst = self.configMgr.getEmailLst() # format = "%(asctime)s: %(message)s" # logging.basicConfig(format=format, level=logging.INFO,datefmt="%H:%M:%S") # logging.info(self.emailLst) def getPlaylistUrlFromClipboard(self): playlistUrl = None try: playlistUrl = self.root.clipboard_get() except TclError as e: # playlistUrl remains None pass return playlistUrl def displayError(self, msg): return msgb.showerror(message=msg) def getConfirmation(self, msg): return msgb.askquestion(message=msg) def doDownload(self): playlistUrl = self.getPlaylistUrlFromClipboard() if playlistUrl == None: self.displayError('Playlist URL not in clipboard. Program closed.') return playlist = None try: playlist = Playlist(playlistUrl) playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)") except KeyError as e: self.displayError('Playlist URL not in clipboard. Program closed.') return except http.client.InvalidURL as e: self.displayError(str(e)) return playlistTitle = playlist.title() if 'Oops' in playlistTitle: self.displayError( 'The URL obtained from clipboard is not pointing to a playlist. Program closed.' ) return playlistName, timeInfo = self.splitPlayListTitle(playlistTitle) targetAudioDir = AUDIO_DIR + DIR_SEP + playlistName if not os.path.isdir(targetAudioDir): targetAudioDirList = targetAudioDir.split(DIR_SEP) targetAudioDirShort = DIR_SEP.join(targetAudioDirList[-2:]) if self.getConfirmation( "Directory\n{}\nwill be created.\n\nContinue with download ?" .format(targetAudioDirShort)) != 'yes': return os.makedirs(targetAudioDir) for video in playlist.videos: audioStream = video.streams.get_by_itag(YOUTUBE_STREAM_AUDIO) videoTitle = video.title self.msgText = self.msgText + 'downloading ' + videoTitle + '\n' self.msg.configure(text=self.msgText) self.root.update() audioStream.download(output_path=targetAudioDir) for file in [ n for n in os.listdir(targetAudioDir) if re.search('mp4', n) ]: mp4FilePathName = os.path.join(targetAudioDir, file) mp3FilePathName = os.path.join(targetAudioDir, os.path.splitext(file)[0] + '.mp3') if timeInfo: timeStartSec, timeEndSec = self.splitTimeInfo(timeInfo) import moviepy.editor as mp # not working on Android clip = mp.AudioFileClip(mp4FilePathName).subclip( timeStartSec, timeEndSec) # disable if do not want any clipping clip.write_audiofile(mp3FilePathName) clip.close() os.remove(mp4FilePathName) else: if os.path.isfile(mp3FilePathName): os.remove(mp3FilePathName) os.rename(mp4FilePathName, mp3FilePathName) def splitPlayListTitle(self, playlistTitle): pattern = r"(.+) ([\d\./]+)" playlistName = None timeInfo = None match = re.match(pattern, playlistTitle) if match: playlistName = match.group(1) timeInfo = match.group(2) else: # no time info provided in the play list title playlistName = playlistTitle return playlistName, timeInfo def splitTimeInfo(self, timeInfo): timeLst = timeInfo.split('/') timeStartHHMMSS = timeLst[0].split('.') timeEndHHMMSS = timeLst[1].split('.') timeStartSec = int(timeStartHHMMSS[0]) * 3600 + int( timeStartHHMMSS[1]) * 60 + int(timeStartHHMMSS[2]) timeEndSec = int(timeEndHHMMSS[0]) * 3600 + int( timeEndHHMMSS[1]) * 60 + int(timeEndHHMMSS[2]) return timeStartSec, timeEndSec
class App: def __init__(self, master): master.minsize(width=300, height=80) self.savedRealmName = [] self.savedRealmAddress = [] self.selectRealmButton = [] self.removeRealmButton = [] self.rlmManager = RealmManager() self.cfgManager = ConfigManager() if not self.cfgManager.hasGameFolder(): newGameFolder = chooseGameFolder() # Force user to choose a game folder while newGameFolder is None: isCanceled = simpledialog.askretrycancel( 'Question', 'You need to select a game folder', parent=root) if isCanceled: root.destroy() return newGameFolder = chooseGameFolder() self.cfgManager.updateGameFolder(newGameFolder) self.mainFrame = Frame(master, width=300, height=100) self.mainFrame.grid(row=0, column=0, padx=20) self.title = Message(self.mainFrame, text='WoW Realm Changer', width=400, font=('Helvetica', 18, 'bold')) self.title.grid() inputFrame = Frame(self.mainFrame) inputFrame.grid(row=1, column=0) self.realmInputLabel = Message(inputFrame, text='set realmlist:', width=100, font=('Helvetica', 11)) self.realmInputLabel.grid(row=1, column=1) self.realmAddressInput = Entry(inputFrame) self.realmAddressInput.grid(row=1, column=2) self.saveButton = Button(inputFrame, text='SAVE', command=self.addRealm) self.saveButton.grid(row=1, column=4) self.currentRealmFrame = Frame(self.mainFrame) self.currentRealmFrame.grid(row=2, column=0) self.realmInitText = Message(self.currentRealmFrame, text=self.rlmManager.currentRealm(), width=300, font=('Helvetica', 11)) self.realmInitText.grid(row=2, column=0) self.buildSavedRealmsList() def buildSavedRealmsList(self): self.savedRealmsFrame = Frame(self.mainFrame) self.savedRealmsFrame.grid(row=3, pady=(20, 10)) self.savedRealmsMessage = Message(self.savedRealmsFrame, text='Saved Realms', width=300, font=('Helvetica', 15, 'bold')) self.savedRealmsMessage.grid() for idx, realm in enumerate(self.cfgManager.savedRealms()): self.addRealmRow(realm) def setActiveRealm(self, realm): self.rlmManager.changeActiveRealm(realm) self.realmInitText.configure(text='Realm changed to: ' + realm['name']) def removeSavedRealm(self, idx): self.cfgManager.removeRealm(idx) self.removeRealmRow(idx) def addRealm(self): realmName = simpledialog.askstring('Input', 'What is the name of the realm?', parent=root) realmAddress = self.realmAddressInput.get() realm = {'address': realmAddress, 'name': realmName} self.cfgManager.addRealm(realm) self.addRealmRow(realm) def removeRealmRow(self, index): self.savedRealmName[index].destroy() self.savedRealmAddress[index].destroy() self.selectRealmButton[index].destroy() self.removeRealmButton[index].destroy() def addRealmRow(self, realm): if not realm: return index = len(self.savedRealmName) name = realm['name'] address = realm['address'] self.savedRealmName.append( Message(self.savedRealmsFrame, text=name, width=250)) self.savedRealmName[index].grid(column=0, row=index + 1) self.savedRealmAddress.append( Message(self.savedRealmsFrame, text=address, width=250)) self.savedRealmAddress[index].grid(column=1, row=index + 1) self.selectRealmButton.append( Button(self.savedRealmsFrame, text='SET', command=lambda rlm=realm: self.setActiveRealm(rlm))) self.selectRealmButton[index].grid(column=2, row=index + 1) self.removeRealmButton.append( Button(self.savedRealmsFrame, text='REMOVE', command=lambda idx=index: self.removeSavedRealm(idx))) self.removeRealmButton[index].grid(column=3, row=index + 1) self.totalRealmItems = index + 1
def aviso_versao(self, baixada, recente): """ Aviso, existe uma nova versão disponível """ self.tp_atualizacao = Toplevel( self.tela, self.design.dic["aviso_versao_top_level"]) self.tp_atualizacao.withdraw() self.tp_atualizacao.focus_force() self.tp_atualizacao.resizable(False, False) self.tp_atualizacao.tk.call('wm', 'iconphoto', self.tp_atualizacao._w, self.icon) self.tp_atualizacao.grid_columnconfigure(1, weight=1) self.tp_atualizacao.title( self.interface_idioma["titulo_aviso_atualizacao"][self.idioma]) # Tentar remover a barra de rolagem #try: # self.tp_atualizacao.wm_attributes('-type', 'splash') #except Exception as erro: # print("Erro ao remover barra de titulos => ", erro) # Objetos da interface fr_atualizaca = Frame(self.tp_atualizacao) lb_versao_dev = Label( fr_atualizaca, text=self.interface_idioma["versao_nova_disponivel"][self.idioma]) lb_versao_tex = Message( fr_atualizaca, text='{}'.format(self.interface_idioma["texto_update_disponivel"][ self.idioma]).format(recente)) fr_botoes = Frame(fr_atualizaca) bt_cancela = Button( fr_botoes, text=self.interface_idioma["versao_nao_quero"][self.idioma]) bt_atualiza = Button( fr_botoes, text=self.interface_idioma["atualizar_agora"][self.idioma]) # Configurações de desingn fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"]) lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"]) lb_versao_tex.configure(self.design.dic["aviso_versao_ms"]) fr_botoes.configure(self.design.dic["aviso_versao_btn"]) bt_cancela.configure(self.design.dic["aviso_versao_btn_cancela"], relief=FLAT) bt_atualiza.configure(self.design.dic["aviso_versao_btn_atualiza"], relief=FLAT) # Eventos bt_atualiza.configure( command=lambda rec=recente: self.aviso_aguarde_instalando(rec)) bt_cancela.configure( command=lambda event=None: self.tp_atualizacao.destroy()) # Posicionamento de itens fr_atualizaca.grid_columnconfigure(1, weight=1) fr_botoes.grid_columnconfigure(1, weight=1) fr_botoes.grid_columnconfigure(2, weight=1) fr_atualizaca.grid(row=1, column=1, sticky=NSEW) lb_versao_dev.grid(row=1, column=1) lb_versao_tex.grid(row=2, column=1, sticky=NSEW) fr_botoes.grid(row=3, column=1, sticky=NSEW) bt_cancela.grid(row=1, column=1) bt_atualiza.grid(row=1, column=2) # Posicionando a tela j_width = self.tp_atualizacao.winfo_reqwidth() j_height = self.tp_atualizacao.winfo_reqheight() t_width = self.tela.winfo_screenwidth() t_heigth = self.tela.winfo_screenheight() self.tp_atualizacao.geometry("+{}+{}".format( int(t_width / 2) - int(j_width / 2), int(t_heigth / 2) - int(j_height / 2))) self.tp_atualizacao.deiconify() self.tp_atualizacao.update()
def aviso_versao_atualizada(self, baixada): self.tp_atualizacao = Toplevel( self.tela, self.design.dic["aviso_versao_tp_atualizada"]) self.tp_atualizacao.withdraw() self.tp_atualizacao.focus_force() self.tp_atualizacao.resizable(False, False) self.tp_atualizacao.tk.call('wm', 'iconphoto', self.tp_atualizacao._w, self.icon) #try: # self.tp_atualizacao.wm_attributes('-type', 'splash') #except Exception as erro: # print("Erro ao remover barra de titulos => ", erro) self.tp_atualizacao.grid_columnconfigure(1, weight=1) j_width = self.tp_atualizacao.winfo_reqwidth() j_height = self.tp_atualizacao.winfo_reqheight() t_width = self.tela.winfo_screenwidth() t_heigth = self.tela.winfo_screenheight() self.tp_atualizacao.title( self.interface_idioma["titulo_aviso_atualizado"][self.idioma]) fr_atualizaca = Frame(self.tp_atualizacao) lb_versao_dev = Label( fr_atualizaca, text=self.interface_idioma["atualizado_versao_ultima"][ self.idioma]) lb_versao_tex = Message( fr_atualizaca, text='{}'.format( self.interface_idioma["texto_atualizado"][self.idioma]).format( baixada["versao"]), relief=FLAT) fr_botoes = Frame(fr_atualizaca) bt_cancela = Button( fr_botoes, text=self.interface_idioma["texto_nao_quero"][self.idioma], relief=FLAT) bt_facebook = Button( fr_botoes, self.design.dic["aviso_versao_bt_facebook_atualizada"], text=self.interface_idioma["atualizado_facebook"][self.idioma], relief=FLAT) bt_blogger_ = Button( fr_botoes, self.design.dic["aviso_versao_bt_blog_atualizada"], text=self.interface_idioma["atualizado_blog"][self.idioma], relief=FLAT) # Configurações de desingn fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"]) lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"]) lb_versao_tex.configure(self.design.dic["aviso_versao_ms"]) fr_botoes.configure(self.design.dic["aviso_versao_btn"]) bt_cancela.configure(self.design.dic["aviso_versao_btn_cancela"], relief=FLAT) #bt_atualiza.configure(self.design.dic["aviso_versao_btn_atualiza"], relief=FLAT) bt_cancela.configure( command=lambda event=None: self.tp_atualizacao.destroy()) bt_facebook.configure(command=lambda event=None: self.abrir_site( "https://www.facebook.com/safiralang/")) bt_blogger_.configure(command=lambda event=None: self.abrir_site( "https://safiralang.blogspot.com/")) fr_atualizaca.grid_columnconfigure(1, weight=1) fr_botoes.grid_columnconfigure(1, weight=1) fr_botoes.grid_columnconfigure(2, weight=1) fr_botoes.grid_columnconfigure(3, weight=1) fr_atualizaca.grid(row=1, column=1, sticky=NSEW) lb_versao_dev.grid(row=1, column=1) lb_versao_tex.grid(row=2, column=1, sticky=NSEW) fr_botoes.grid(row=3, column=1, sticky=NSEW) bt_cancela.grid(row=1, column=1) bt_facebook.grid(row=1, column=2) bt_blogger_.grid(row=1, column=3) self.tp_atualizacao.geometry("+{}+{}".format( int(t_width / 2) - int(j_width / 2), int(t_heigth / 2) - int(j_height / 2))) self.tp_atualizacao.update() self.tp_atualizacao.deiconify()
def __aviso_versao_atualizada(self): self.__tp_atualizacao = Toplevel( self.master, self.design.dic["aviso_versao_tp_atualizada"]) self.__tp_atualizacao.withdraw() self.__tp_atualizacao.focus_force() self.__tp_atualizacao.resizable(False, False) self.__tp_atualizacao.tk.call('wm', 'iconphoto', self.__tp_atualizacao._w, self.icon) self.__tp_atualizacao.grid_columnconfigure(1, weight=1) j_width = self.__tp_atualizacao.winfo_reqwidth() j_height = self.__tp_atualizacao.winfo_reqheight() t_width = self.master.winfo_screenwidth() t_heigth = self.master.winfo_screenheight() self.__tp_atualizacao.title( self.interface_idioma["titulo_aviso_atualizado"][self.idioma]) fr_atualizaca = Frame(self.__tp_atualizacao) lb_versao_dev = Label( fr_atualizaca, text=self.interface_idioma["atualizado_versao_ultima"][ self.idioma]) lb_versao_tex = Message( fr_atualizaca, text='{}'.format( self.interface_idioma["texto_atualizado"][self.idioma]).format( self.versao_safira), relief=FLAT) fr_botoes = Frame(fr_atualizaca) bt_cancela = Button( fr_botoes, text=self.interface_idioma["texto_nao_quero"][self.idioma], relief=FLAT) bt_facebook = Button( fr_botoes, self.design.dic["aviso_versao_bt_facebook_atualizada"], text=self.interface_idioma["atualizado_facebook"][self.idioma], relief=FLAT) bt_blogger_ = Button( fr_botoes, self.design.dic["aviso_versao_bt_blog_atualizada"], text=self.interface_idioma["atualizado_blog"][self.idioma], relief=FLAT) # Configurações de desingn fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"]) lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"]) lb_versao_tex.configure(self.design.dic["aviso_versao_ms"]) fr_botoes.configure(self.design.dic["aviso_versao_btn"]) bt_cancela.configure(self.design.dic["aviso_versao_btn_cancela"], relief=FLAT) bt_cancela.configure( command=lambda event=None: self.__tp_atualizacao.destroy()) bt_facebook.configure(command=lambda event=None: self.__abrir_site( "https://www.facebook.com/safiralang/")) bt_blogger_.configure(command=lambda event=None: self.__abrir_site( "https://safiralang.blogspot.com/")) fr_atualizaca.grid_columnconfigure(1, weight=1) fr_botoes.grid_columnconfigure(1, weight=1) fr_botoes.grid_columnconfigure(2, weight=1) fr_botoes.grid_columnconfigure(3, weight=1) fr_atualizaca.grid(row=1, column=1, sticky=NSEW) lb_versao_dev.grid(row=1, column=1) lb_versao_tex.grid(row=2, column=1, sticky=NSEW) fr_botoes.grid(row=3, column=1, sticky=NSEW) bt_cancela.grid(row=1, column=1) bt_facebook.grid(row=1, column=2) bt_blogger_.grid(row=1, column=3) x, y = int(t_width / 2) - int(j_width / 2), int(t_heigth / 2) - int( j_height / 2) self.__tp_atualizacao.geometry("+{}+{}".format(x, y)) self.__tp_atualizacao.update() self.__tp_atualizacao.deiconify()
error_label["text"] = "" for err in parser_ouput: error_label["text"] += err + "\n" else: error_label["text"] = "" save_pseudocode() if current_dir == 16 and len(to_go_files) == 0: transcript_lable['text'] = "Finished" else: set_up_next_example() root = Tk() root.geometry("1300x900") root.resizable(0, 0) root.configure(background='black') b = Button(root, text="Next", command=next_callback) b.pack() transcript_lable = Message(root, text="Text", width=1200, font=("Courier", 24)) transcript_lable.configure(background='black', foreground='white') transcript_lable.pack() pseudo_textfield = Text(root, font=("Courier", 24), width=70, height=20) pseudo_textfield.pack() bottom_next = Button(root, text="Next", command=next_callback) bottom_next.pack() error_label = Message(root, text="", width=1200, font=("Courier", 16)) error_label.configure(background='black', foreground='red') error_label.pack() set_up_next_example() root.mainloop()
class GUI: """ A class to represent the gui for this program. """ def __init__(self): # There may be other compatible types I am not aware of self.image_types = ['png', 'jpg', 'gif', 'jpeg'] # Create window self.window = Tk() self.window.title("Image Saturation Reader") self.window.state("zoomed") # Set default variables self.current_image_name = "None Selected" self.current_image = None self.current_mode = 'area' self.canvas_size = None self.corners = [] self.sight_lines = [] # Find screen height self.width = self.window.winfo_screenwidth() self.height = self.window.winfo_screenheight() # Populate window self._generate_window() # Bind events self.canvas.bind('<Motion>', self.motion) self.canvas.bind('<Leave>', self.leave) self.canvas.bind('<Button-1>', self.click) # Final stylizations self.area_mode_button.config(relief=SUNKEN) def _generate_window(self): """ Generate the components inside the window. """ # Left-side information panel info_panel = ttk.Frame(self.window) # Create components inside left panel choose_image = Button(info_panel, text='Choose Image', command=self.choose_image) image_label = Message(info_panel, text='Image:', width=40) self.image_name = Message(info_panel, text=self.current_image_name, width=100) self.image_width = Message(info_panel, text='W: ', width=50) self.image_height = Message(info_panel, text='H: ', width=50) self.separator = Message(info_panel, text='=======', width=75) self.x = Message(info_panel, text='x: ', width=40) self.y = Message(info_panel, text='y: ', width=40) self.r = Message(info_panel, text='r: ', width=40) self.g = Message(info_panel, text='g: ', width=40) self.b = Message(info_panel, text='b: ', width=40) self.num_pixels = Message(info_panel, text='# Pixels: ', width=50) self.hue = Message(info_panel, text='Hue: ', width=75) self.saturation = Message(info_panel, text='Saturation: ', width=75) self.value = Message(info_panel, text='Value: ', width=75) self.pixel_mode_button = Button(info_panel, text='Pixel Mode', command=self.pixel_mode) self.area_mode_button = Button(info_panel, text='Area Mode', command=self.area_mode) # Place the components inside left panel choose_image.grid(padx=5, pady=5, sticky="N") image_label.grid(sticky=W) self.image_name.grid(sticky=W) self.image_width.grid(sticky=W) self.image_height.grid(sticky=W) self.separator.grid() self.x.grid(sticky=W) self.y.grid(sticky=W) self.r.grid(sticky=W) self.g.grid(sticky=W) self.b.grid(sticky=W) self.num_pixels.grid(sticky=W) self.hue.grid(sticky=W) self.saturation.grid(sticky=W) self.value.grid(sticky=W) self.area_mode_button.grid() self.pixel_mode_button.grid() # Create right panel components self.canvas = Canvas(self.window, width=self.width, height=self.height, bg='lightblue') # Add two sides to final window info_panel.grid(column=1, row=1) self.canvas.grid(column=2, row=1, sticky="nesw") def choose_image(self): self.current_image_name = askopenfilename() if self.current_image_name.split('.')[-1] in self.image_types: self.image_name.configure( text=self.current_image_name.split('/')[-1]) self.open_image() self.clear_drawing_data() def open_image(self): if self.canvas_size is None: self.set_canvas_size() self.current_image = Image.open(self.current_image_name) self.current_image.thumbnail(self.canvas_size, Image.ANTIALIAS) current_image_tk = ImageTk.PhotoImage(self.current_image) width = current_image_tk.width() height = current_image_tk.height() self.image_width.config(text='W: ' + str(width)) self.image_height.config(text='H: ' + str(height)) self.canvas.config(width=width - 4, height=height - 4) self.canvas.create_image(round(width / 2), round(height / 2), anchor=CENTER, image=current_image_tk) self.canvas.image = current_image_tk def set_canvas_size(self): self.canvas_size = (self.canvas.winfo_width(), self.window.winfo_height()) def click(self, event): """ Clicking within the canvas. """ if self.current_image is not None: x, y = event.x, event.y if self.current_mode == 'area': if not self.corners: self.corners.append( self.canvas.create_oval(x - 2, y - 2, x + 2, y + 2, fill='white')) elif len(self.corners) == 1: self.corners.append( self.canvas.create_oval(x - 2, y - 2, x + 2, y + 2, fill='white')) x1, y1, *_ = self.canvas.coords(self.corners[0]) x2, y2, *_ = self.canvas.coords(self.corners[1]) self.get_pixel_data(x1, y1, x2, y2) else: self.clear_drawing_data() self.corners.append( self.canvas.create_oval(x - 2, y - 2, x + 2, y + 2, fill='white')) elif self.current_mode == 'pixel': self.get_pixel_data(x, y, x, y) def get_pixel_data(self, x1, y1, x2, y2): x1 = round(x1) y1 = round(y1) x2 = round(x2) y2 = round(y2) if x2 < x1: x1, x2 = x2, x1 if y2 < y1: y1, y2 = y2, y1 total_hue = 0 total_saturation = 0 total_value = 0 total_r = 0 total_g = 0 total_b = 0 c = 0 for y in range(y1, y2 + 1): for x in range(x1, x2 + 1): r, g, b, *_ = self.current_image.getpixel((x, y)) data = rgb_to_hsv(r, g, b) total_hue += data[0] total_saturation += data[1] total_value += data[2] total_r += r total_g += g total_b += b c += 1 avg_hue = round((total_hue / c), 2) avg_saturation = round((total_saturation / c) * 100, 2) avg_value = round((total_value / c), 2) avg_r = round((total_r / c), 2) avg_g = round((total_g / c), 2) avg_b = round((total_b / c), 2) self.write_pixel_data(avg_hue, avg_saturation, avg_value, avg_r, avg_g, avg_b, c) def write_pixel_data(self, hue, sat, val, r, g, b, c): self.num_pixels.configure(text='# Pixels: ' + str(c)) self.hue.configure(text='Hue: ' + str(hue)) self.saturation.configure(text='Saturation: ' + str(sat) + '%') self.value.configure(text='Value: ' + str(val)) self.r.configure(text='r: ' + str(r)) self.g.configure(text='g: ' + str(g)) self.b.configure(text='b: ' + str(b)) def leave(self, event): self.x.configure(text='x: ') self.y.configure(text='y: ') def motion(self, event): if self.current_image is not None: x, y = event.x + 1, event.y + 1 self.x.configure(text='x: ' + str(x)) self.y.configure(text='y: ' + str(y)) if len(self.corners) == 1: self.draw_sight_lines(x, y) def draw_sight_lines(self, x, y): for line in self.sight_lines: self.canvas.delete(line) lx, ly, *_ = self.canvas.coords(self.corners[0]) lx += 2 ly += 2 self.sight_lines.append( self.canvas.create_line(lx, ly, x, ly, dash=(3, 3))) self.sight_lines.append( self.canvas.create_line(lx, ly, lx, y, dash=(3, 3))) self.sight_lines.append( self.canvas.create_line(x, ly, x, y, dash=(3, 3))) self.sight_lines.append( self.canvas.create_line(lx, y, x, y, dash=(3, 3))) def pixel_mode(self): self.clear_drawing_data() self.pixel_mode_button.config(relief=SUNKEN) self.area_mode_button.config(relief=RAISED) self.current_mode = 'pixel' def area_mode(self): self.clear_drawing_data() self.area_mode_button.config(relief=SUNKEN) self.pixel_mode_button.config(relief=RAISED) self.current_mode = 'area' def clear_drawing_data(self): self.clear_drawings() self.corners = [] self.sight_lines = [] def clear_drawings(self): for line in self.sight_lines: self.canvas.delete(line) for dot in self.corners: self.canvas.delete(dot) def mainloop(self): self.window.mainloop()