Ejemplo n.º 1
0
    def __init__(self, master=None, **kwargs):
        """
        Constructor.

        Get default settings from user's IDLE configuration.
        """
        currentTheme = idleConf.CurrentTheme()
        textcf = dict(
            padx=5,
            wrap="word",
            undo="True",
            foreground=idleConf.GetHighlight(currentTheme, "normal", fgBg="fg"),
            background=idleConf.GetHighlight(currentTheme, "normal", fgBg="bg"),
            highlightcolor=idleConf.GetHighlight(currentTheme, "hilite", fgBg="fg"),
            highlightbackground=idleConf.GetHighlight(currentTheme, "hilite", fgBg="bg"),
            insertbackground=idleConf.GetHighlight(currentTheme, "cursor", fgBg="fg"),
            width=idleConf.GetOption("main", "EditorWindow", "width"),
            height=idleConf.GetOption("main", "EditorWindow", "height"),
        )
        fontWeight = "normal"
        if idleConf.GetOption("main", "EditorWindow", "font-bold", type="bool"):
            fontWeight = "bold"
        textcf["font"] = (
            idleConf.GetOption("main", "EditorWindow", "font"),
            idleConf.GetOption("main", "EditorWindow", "font-size"),
            fontWeight,
        )
        # override defaults with any user-specified settings
        textcf.update(kwargs)
        ScrolledText.__init__(self, master, **textcf)
Ejemplo n.º 2
0
    def addContactView(self):
        window = Toplevel()
        window.focus_set()
        window.title("Add Contact")
        window.resizable(width=FALSE, height=FALSE)

        Label(window, text="Name ").grid(row=0, column=0)
        name = Entry(window, width=30)
        name.grid(row=0, column=1)

        Label(window, text="Line ").grid(row=1, column=0)
        line = Entry(window, width=30)
        line.grid(row=1, column=1)

        Label(window, text="Email ").grid(row=2, column=0)
        Email = Entry(window, width=30)
        Email.grid(row=2, column=1)

        Label(window, text="Phone ").grid(row=3, column=0)
        phone = ScrolledText(window, width=37)
        phone.grid(row=3, column=1)

        okButton = Button(window, text="Finish",
                          command=lambda: self.addContact(window, name=name.get(), line=line.get(), Email=Email.get(),
                                                          Telephone=phone.get(1.0, END)))
        okButton.grid(row=4)
        cancelButton = Button(window, text="Cancel", command=window.destroy)
        cancelButton.grid(row=4, column=1, sticky=E)
 def receivePrivateChat(self, connectingUser):
     global conversationBoxList
     print("CHAT PRIVATA in arrivo con "+connectingUser)
         
     newWindow = Toplevel(self.parent)
     newWindow.title("Python Chat requested by "+connectingUser)
     newWindow.minsize(400, 475)
     newWindow.focus()
     
     def disconnectPM():
         del conversationBoxList[connectingUser]
         newWindow.destroy()
     newWindow.protocol('WM_DELETE_WINDOW', disconnectPM)
     
     #label = Label(newWindow, text="PROVA PROVA")
     #label.pack(side="top", fill="both", padx=10, pady=10)
     frame = Frame(newWindow)
     frame.pack(fill=BOTH, expand=1, side=LEFT)
     
     box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
     box.config(state=DISABLED)
     box.pack(expand="yes", fill=BOTH, side=TOP)
     
     textarea = Text(frame, width=30, height=5)
     textarea.bind("<KeyRelease-Return>", lambda event : self.getprivatetext(event, textarea, connectingUser)) 
     textarea.pack(expand="yes", fill=BOTH, side=TOP)
     
     #aggiungo alla mappa globale il box di conversazione
     conversationBoxList[connectingUser] = box
Ejemplo n.º 4
0
    def build(self, frm):
        # layout of the gui elements
        frm.grid(column=0, row=0, sticky=(tk.N, tk.W, tk.E, tk.S))
        frm.columnconfigure(0, weight=1)
        frm.columnconfigure(1, weight=2)
        frm.rowconfigure(0, weight=1)

        self.scrollmsg = ScrolledText(frm, wrap=tk.WORD, width=40)
        self.scrollmsg.grid(column=0, row=1, sticky="EW")
        self.scrollmsg.tag_config('bold', font=('Courier',10,'bold'))
        
        self.scrolldata = ScrolledText(frm, wrap=tk.WORD, width=40)
        self.scrolldata.grid(column=1, row=1, rowspan=9, sticky="NS")
        self.scrolldata.tag_config('bold', font=('Courier',10,'bold'))
        
        self.entrytext = tk.StringVar()
        self.entry = ttk.Entry(frm, textvariable=self.entrytext)
        self.entry.grid(column=0, row=3, sticky='EW')
        self.entry.bind("<Return>", self.on_press_enter)

        btn_quit = ttk.Button(frm, text="QUIT",
                            command=self.finish)
        btn_quit.grid(column=0,
                            row=9, sticky="EW")

        for child in frm.winfo_children():
            child.grid_configure(padx=5, pady=5)
            
        self.entry.focus_set() # set the focus on the entry field
Ejemplo n.º 5
0
Archivo: gui.py Proyecto: Zeffar/Elobot
    def __init__(self, master=None, **kwargs):
        """
        Initializer.

        Get default settings from user's IDLE configuration.
        """
        currentTheme = idleConf.CurrentTheme()
        textcf = {
            'padx': 5,
            'wrap': 'word',
            'undo': 'True',
            'foreground': idleConf.GetHighlight(
                currentTheme, 'normal', fgBg='fg'),
            'background': idleConf.GetHighlight(
                currentTheme, 'normal', fgBg='bg'),
            'highlightcolor': idleConf.GetHighlight(
                currentTheme, 'hilite', fgBg='fg'),
            'highlightbackground': idleConf.GetHighlight(
                currentTheme, 'hilite', fgBg='bg'),
            'insertbackground': idleConf.GetHighlight(
                currentTheme, 'cursor', fgBg='fg'),
            'width': idleConf.GetOption('main', 'EditorWindow', 'width'),
            'height': idleConf.GetOption('main', 'EditorWindow', 'height'),
        }
        fontWeight = 'normal'
        if idleConf.GetOption('main', 'EditorWindow', 'font-bold',
                              type='bool'):
            fontWeight = 'bold'
        textcf['font'] = (idleConf.GetOption('main', 'EditorWindow', 'font'),
                          idleConf.GetOption('main', 'EditorWindow',
                                             'font-size'),
                          fontWeight)
        # override defaults with any user-specified settings
        textcf.update(kwargs)
        ScrolledText.__init__(self, master, **textcf)
Ejemplo n.º 6
0
class MainUI(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master, width=600, height=480)
        self.data_directory = StringVar()
        self.data_directory.set("no data selected... please select directory of google_speech_data")
        self.directory_prompt = Label(self, textvariable = self.data_directory)
        self.directory_prompt.grid(row=0,column=0,sticky=W)
        self.select_dir = Button(self, text ="Change directory")
        self.select_dir.grid(row=0,column=1)
        self.select_dir.bind("<Button-1>",self.chdir)
        self.gru_label = Label(self, text = "GRU Size:")
        self.gru_label.grid(row=1,column=0,sticky=E)
        self.gru_entry = Entry(self)
        self.gru_entry.insert(0,"20")
        self.gru_entry.grid(row=1,column=1)
        self.words_label = Label(self,text = "Words to learns: (one line per word)")
        self.words_label.grid(row=2,column=0,sticky=W)
        self.words = ScrolledText(self)
        self.words.grid(row=3,column=0,columnspan=2)
        self.trainbtn = Button(self, text ="Train model")
        self.trainbtn.bind("<Button-1>",self.train)
        self.trainbtn.grid(row=4,column=1)
        self.pack(side=LEFT)
    def chdir(self, event):
        self.speech_data = filedialog.askdirectory()
        if self.speech_data:
            self.data_directory.set("Using speech data from: "+self.speech_data)
            os.chdir(self.speech_data)
    def train(self, event):
        filename = filedialog.asksaveasfilename(title = "Select file to checkpoint the model to",filetypes =(("uspeech model checkpoint","*.model"),))
        if filename:
            pass #TODO Implement training routine
Ejemplo n.º 7
0
 def build_widgets(self):
     "Build the various widgets that will be used in the program."
     # Create processing frame widgets.
     self.processing_frame = LabelFrame(self, text='Processing Mode:')
     self.mode_var = StringVar(self, 'encode')
     self.decode_button = Radiobutton(self.processing_frame,
                                      text='Decode Cipher-Text',
                                      command=self.handle_radiobuttons,
                                      value='decode',
                                      variable=self.mode_var)
     self.encode_button = Radiobutton(self.processing_frame,
                                      text='Encode Plain-Text',
                                      command=self.handle_radiobuttons,
                                      value='encode',
                                      variable=self.mode_var)
     self.freeze_var = BooleanVar(self, False)
     self.freeze_button = Checkbutton(self.processing_frame,
                                      text='Freeze Key & Primer',
                                      command=self.handle_checkbutton,
                                      offvalue=False,
                                      onvalue=True,
                                      variable=self.freeze_var)
     # Create encoding frame widgets.
     self.encoding_frame = LabelFrame(self, text='Encoding Options:')
     self.chain_size_label = Label(self.encoding_frame, text='Chain Size:')
     self.chain_size_entry = Entry(self.encoding_frame)
     self.plain_text_label = Label(self.encoding_frame, text='Plain-Text:')
     self.plain_text_entry = Entry(self.encoding_frame)
     # Create input frame widgets.
     self.input_frame = LabelFrame(self, text='Input Area:')
     self.input_text = ScrolledText(self.input_frame, **self.TEXT)
     # Create output frame widgets.
     self.output_frame = LabelFrame(self, text='Output Area:')
     self.output_text = ScrolledText(self.output_frame, **self.TEXT)
Ejemplo n.º 8
0
class LongTextbox(Textbox):

	def config(self, **kwargs):
		if 'height' in kwargs:
			self.sentry.config(height=kwargs['height'])
		if 'width' in kwargs:
			self.sentry.config(width=kwargs['width'])
		if 'text' in kwargs:	
			self.sentry.insert(END, kwargs['text'])
		if 'lang' in kwargs:
			self.lang = kwargs['lang']
			self.label.config(text=self.lang[self.text])
		
	def place(self, **kwargs):
		self.parent = kwargs['parent']
		self.row = kwargs['row']
		self.column = kwargs['column']

		self.label = Label(self.parent, text=self.lang[self.text])
		self.sentry = ScrolledText(self.parent, relief=SOLID)

		self.label.grid(row=self.row, column=self.column)
		self.sentry.grid(row=self.row, column=self.column+1, sticky=E)

	def getData(self):
		return self.sentry.get('1.0', END + '-1c')

	def setData(self, data):
		self.sentry.delete('1.0', END)
		self.config(text=data)
Ejemplo n.º 9
0
def main():
    global text_in
    global sock


    window = tk.Tk()
    window.wm_title('Vessel XIV')

    text_out = ScrolledText(window, state='disabled', takefocus=0)
    #text_out.configure(state='disabled')
    text_out.pack()

    text_in = tk.Entry(window, takefocus=1)
    text_in.bind("<Return>", lambda e: evaluate_in(e, text_in, text_out))
    text_in.pack()


    HOST = 'arctem.com'
    #HOST = 'localhost'
    PORT = 50001
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((HOST, PORT))

    t = threading.Thread(target=socket_thread, args=(sock, text_out))
    t.start()

    window.mainloop()
Ejemplo n.º 10
0
    def __init__(self, master=None, **kwargs):
        """
        Constructor.

        Get default settings from user's IDLE configuration.
        """
        currentTheme = idleConf.CurrentTheme()
        textcf = dict(padx=5, wrap='word', undo='True',
                      foreground=idleConf.GetHighlight(currentTheme,
                                                       'normal', fgBg='fg'),
                      background=idleConf.GetHighlight(currentTheme,
                                                       'normal', fgBg='bg'),
                      highlightcolor=idleConf.GetHighlight(currentTheme,
                                                           'hilite', fgBg='fg'),
                      highlightbackground=idleConf.GetHighlight(currentTheme,
                                                                'hilite',
                                                                fgBg='bg'),
                      insertbackground=idleConf.GetHighlight(currentTheme,
                                                             'cursor',
                                                             fgBg='fg'),
                      width=idleConf.GetOption('main', 'EditorWindow', 'width'),
                      height=idleConf.GetOption('main', 'EditorWindow',
                                                'height')
                      )
        fontWeight = 'normal'
        if idleConf.GetOption('main', 'EditorWindow', 'font-bold', type='bool'):
            fontWeight = 'bold'
        textcf['font'] = (idleConf.GetOption('main', 'EditorWindow', 'font'),
                          idleConf.GetOption('main', 'EditorWindow',
                                             'font-size'),
                          fontWeight)
        # override defaults with any user-specified settings
        textcf.update(kwargs)
        ScrolledText.__init__(self, master, **textcf)
class ReadMailWindow:
    def __init__(self, receiver='*****@*****.**', sender='*****@*****.**', topic='DefaultTopic', text='Dear:\n\nDefaultLine\nDefaultLine2\nDefaultLine3\n\nSincerely,\nDefaultUser'):
        '''
        create the ReadMailWindow.
        '''
        self.root = tk.Tk()
        self.root.title('Mail from '+sender)
        self.root.geometry('300x200')
        
        self.receiver=receiver
        self.sender=sender
        self.topic=topic
        self.text=text
        
        self.pane_for_sender = tk.PanedWindow(self.root,orient=tk.HORIZONTAL, borderwidth=5)
        self.pane_for_sender.pack(fill=tk.BOTH)
        self.lable_for_sender = tk.Label(self.pane_for_sender, text='From:', width=5, justify=tk.LEFT, anchor=tk.W)
        self.entry_for_sender = tk.Entry(self.pane_for_sender, width=10)
        self.entry_for_sender.insert(0, self.sender)
        self.entry_for_sender.config(state=tk.DISABLED)
        self.pane_for_sender.add(self.lable_for_sender)
        self.pane_for_sender.add(self.entry_for_sender)
        
        self.pane_for_topic = tk.PanedWindow(self.root, orient=tk.HORIZONTAL, borderwidth=5)
        self.pane_for_topic.pack(fill=tk.BOTH)
        self.lable_for_topic = tk.Label(self.pane_for_topic, text='Topic:', width=5, justify=tk.LEFT, anchor=tk.W)
        self.entry_for_topic = tk.Entry(self.pane_for_topic, width=10)
        self.entry_for_topic.insert(0, self.topic)
        self.entry_for_topic.config(state=tk.DISABLED)
        self.pane_for_topic.add(self.lable_for_topic)
        self.pane_for_topic.add(self.entry_for_topic)
        
        self.pane_for_content = tk.PanedWindow(self.root, orient=HORIZONTAL, borderwidth=7)
        self.pane_for_content.pack(fill=tk.BOTH, expand=1)
        self.lable_for_content = tk.Label(self.pane_for_content, text='Text:', justify=tk.LEFT, anchor=tk.W)
        self.text_for_content = ScrolledText(self.pane_for_content, width=10, height=4)
        self.text_for_content.insert(1.0, self.text)
        self.text_for_content.config(state=tk.DISABLED)
        self.pane_for_content.add(self.lable_for_content)
        self.pane_for_content.add(self.text_for_content)
        
        self.pane_for_button = tk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        self.pane_for_button.pack(fill=tk.BOTH)
        self.button_for_reply = tk.Button(self.pane_for_button, text="Reply", command=self.Reply)
        self.button_for_close = tk.Button(self.pane_for_button, text="Exit", command=self.Destroy, width=5)
        self.pane_for_button.add(self.button_for_close) 
        self.pane_for_button.add(self.button_for_reply)
        

    def Reply(self):
        with open('acpwd.txt') as file:
            for line in file:
                acpwd = line.split(':')
                self.SMW = smw.SendMailWindow(self.receiver, self.sender, acpwd[1])
        self.SMW.text_for_content.insert(1.0, '\n\n---------------\n'+self.text)
        #self.root.destroy()
    
    def Destroy(self):
        self.root.destroy() 
Ejemplo n.º 12
0
class LongTextbox(Textbox):

	def config(self, **kwargs):

		try:
			self.sentry.config(height=kwargs['height'])
		except:
			pass
			#print("the widget could not be configured")

		try:
			self.sentry.config(width=kwargs['width'])
		except:
			pass
			#print("the widget could not be configured")

		try:
			#self.text = kwargs['text']
			#self.sentry.delete(1.0, END)
			self.sentry.insert(END, kwargs['text'])
		except:
			pass
			#print("the widget could not be configured")
			
		try:
			self.lang = kwargs['lang']
			self.label.config(text=self.lang[self.text])
		except:
			pass


	def trytoplace(self, **kwargs):
		self.parent = kwargs['parent']
		self.row = kwargs['row']
		self.column = kwargs['column']


	def place(self, **kwargs):

		try:
			self.trytoplace(**kwargs)
		except:
			pass
			#print("widget could not be placed")

		self.label = Label(self.parent, text=self.lang[self.text])
		self.sentry = ScrolledText(self.parent, relief=SOLID)

		self.label.grid(row=self.row, column=self.column)
		self.sentry.grid(row=self.row, column=self.column+1, sticky=E)


	def getData(self):
		return self.sentry.get('1.0', END + '-1c')


	def setData(self, data):
		self.sentry.delete('1.0', END)
		self.config(text=data)
Ejemplo n.º 13
0
class TextFrame(ttk.LabelFrame):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._init_ui()

    def _init_ui(self):
        self.textbox = ScrolledText(self, width=70, height=10)
        self.textbox.bind("<1>", lambda event: self.textbox.focus_set())
        self.textbox.pack(expand=True, fill='both')
Ejemplo n.º 14
0
    def __init__(self, master=None, **cnf):
        # Initialize base class
        ScrolledText.__init__(self, master, **cnf)

        # Define tags for formatting styles
        self.tag_config("X", underline=1)
        self.tag_config("!", font=BOLDFONT)
        self.tag_config("_", font=ITALICFONT)

        # Set state to idle
        self.fp = None
        self.lineno = 0
Ejemplo n.º 15
0
    def __init__(self, master):
        self.master = master
        master.title("Client")
        master.geometry("600x750")

        self.chat = ScrolledText(self.master, state = "disabled", width = 72)
        self.chat.grid(padx = 4, pady = 4, columnspan = 2)

        self.chat_entry = ScrolledText(self.master, width = 55, height = 3)
        self.chat_entry.grid(row = 1, padx = 4, pady = 4)

        self.send_button = Button(self.master, text = "Send", width = 10, height = 2)
        self.send_button.grid(row = 1, column = 1, padx = 4, pady = 4)
Ejemplo n.º 16
0
def Login(entries,root):
    text=[]
    for entry in entries:
        text.append(entry[1].get())
    print(text)
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(text[0], username=text[1], password=text[2])
    stdin, stdout, stderr = ssh.exec_command(text[3])
    u=stdout.readlines()
    output = ''.join(u)
    sc=ScrolledText(root)
    sc.pack(side=LEFT)
    sc.insert(END, output)
Ejemplo n.º 17
0
    def _init_repl_frame(self, notebook):
        frame = ttk.Frame(notebook)

        self.repl_input = ScrolledText(frame, height=15, width=80)
        self.repl_input.insert(tk.END,
                '-- REPL command input\n'
                '-- Press Ctrl-Enter to run command\n'
                'client_by_name(\'OP\'):extra().superuser = true')
        self.repl_input.bind('<Control-Return>', self._repl_send)
        self.repl_input.pack()
        self.repl_output = ScrolledText(frame, height=5, width=80)
        self.repl_output.pack()

        return frame
Ejemplo n.º 18
0
	def _conButtonCmd(self):
		popwin = PopupWindow("Container Log")
		popwin.grab_set()
		popwin.focus()
		details = self.checkresult.getContainerLogs()
		stext = ScrolledText(popwin)
		stext.config(font = ("courier", 15, "normal"))
		stext.pack()
		for d in details:
			stext.insert("end",d)
		stext.see("end")
Ejemplo n.º 19
0
    def createTab(self, text, content):
        ind = self.tabIndMax
        tab = Radiobutton(self.tabs_panel, text=text,
                font=NORMAL_FONT, indicatoron=NO,
                variable=self.tabInd, value=ind,
                command=lambda:self.switchTab(ind))
        self.tabIndMax += 1
        tab.pack(side=TOP, fill=X)

        txtCtrl = ScrolledText(self.txt_panel, undo = True)
        txtCtrl.insert(1.0, content)

        self.tabs.append(tab)
        self.txtCtrls.append(txtCtrl)
        return ind
Ejemplo n.º 20
0
    def __init__(self, file=None, text="", parent=None, **kw):
        if parent is None:
            self.parent = editor
        else:
            self.parent = parent
        ScrolledText.__init__(self, parent, **kw)

        if file is None:
            self.is_untitled = True
            self._file = tempfile.NamedTemporaryFile(mode="w+t", prefix=UNTITLED)
        else:
            self.is_untitled = False
            self._file = file

        self.text = text
Ejemplo n.º 21
0
class View(Frame):
    def __init__ (self,parent=None):
        Frame.__init__(self,parent)
        self.pack()
        self.makeWidgets()
        self.scrolltext = ScrolledText(master=self)
        self.scrolltext.pack()

    def makeWidgets(self):
        btn = Button(text='Hello World',command=self.onClick)
        btn.pack(side=TOP)

    def onClick(self):
        '''Delegate event handling to Controller'''
        app.controller.handleClick()
Ejemplo n.º 22
0
	def __init__(self, parent):
		Frame.__init__(self, parent)
		self.scrolltext = ScrolledText(self, width = 120,
				font = ("", 14, "normal"), height = 30)
		self.scrolltext.config(state = "disable")

		f = Frame(self)
		self.entry = Entry(f, width = 75, font = ("", 15, "normal"))
#		self.entry.grab_set()
		self.entry.focus_set()
		self.entry.grid(row = 0, column = 0)
		self.entry.bind("<Return>", lambda event, frame = self: frame._runCommand())

		self.button1 = Button(f, text = "sumbmit", font = ("", 15, "normal"),
						command = lambda frame = self: frame._runCommand())
		self.button1.grid(row = 0, column = 1, padx = 4, pady = 2)
		self.button2 = Button(f, text = "clear", font = ("", 15, "normal"),
						command = lambda frame = self: frame._deleteText())
		self.button2.grid(row = 0, column = 2, padx = 4, pady = 2)
		f.grid(row = 1, column = 0)
		self.scrolltext.grid(row = 0, column = 0)

		with shelve.open("userconfigdb") as db:
			keys = tuple(db.keys())
		if not keys:
			configButtonCmd()
		with shelve.open("userconfigdb") as db:
			self.sshIP = db[tuple(db.keys())[0]].hostaddress
		self._configButtonCmd()
 def __init__(self, reps=3):
     self.reps = reps
     self.text = ScrolledText()
     self.text.pack()
     threadChecker(self.text)
     self.text.bind('<Button-1>',
                    lambda event: list(map(self.onEvent, range(6))))
Ejemplo n.º 24
0
    def __init__(self, master=None, **cnf):
        ScrolledText.__init__(self, master, **cnf)

        bold = Font(font=self['font']).copy()
        bold.config(weight='bold')
        italic = Font(font=self['font']).copy()
        italic.config(slant='italic')

        # Define tags for formatting styles
        self.tag_config('X', underline=1)
        self.tag_config('!', font=bold)
        self.tag_config('_', font=italic)

        # Set state to idle
        self.fp = None
        self.lineno = 0
Ejemplo n.º 25
0
	def __init__(self, peer):
		Toplevel.__init__(self, mainwindow)
		self.peer = peer
		self.recvFile = None

		self.title(peer[0] + ':' + str(peer[1]))

		#self.root = Tk()
		#self.main = Frame(self.root)
		self.main = Frame(self)
		self.main.pack(expand=True, fill=BOTH)

		self.chat_Text = ScrolledText(self.main)
		self.chat_Text.pack(expand=True, fill=BOTH)
		self.chat_Text['height'] = 10
		#print self.keys()
		#print self.chat_Text.keys()

		self.send_Frame = Frame(self.main)
		self.send_Frame.pack(fill=X)

		self.send_Text = Entry(self.send_Frame)
		self.send_Text.pack(side=LEFT, expand=True, fill=X)
		self.send_Text.bind('<Return>', self.send_Action)
		self.send_Button = Button(self.send_Frame, text='Send', command=self.send_Action)
		self.send_Button.pack(side=LEFT)
		self.holePunch_Button = Button(self.send_Frame, text='UDP punch', command=self.holePunch_Action)
		self.holePunch_Button.pack(side=LEFT)
		self.sendFile_Button = Button(self.send_Frame, text='File', command=self.sendFile_Action)
		self.sendFile_Button.pack(side=LEFT)

		self.status_Label = Label(self.main, text='Peer: ' + self.peer[0] + ':' + str(self.peer[1]))
		self.status_Label.pack()

		self.send_Text.focus()
 def __init__(self, reps=3):
     self.reps = reps # uses default Tk root
     self.text = ScrolledText() # save widget as state
     self.text.pack()
     threadChecker(self.text) # start thread check loop
     self.text.bind('<Button-1>', # 3.x need list for map, range ok
                    lambda event: list(map(self.onEvent, range(6))) )
 def __init__(self, master=None, cnf={}, **kw):
     super(GuiConsole, self).__init__(master, cnf, **kw)
     self.pack(fill=BOTH, expand=YES)
     self.console = ScrolledText(self, font=('Source Code Pro', 12, 'normal'))
     self.console.pack(side=TOP, fill=BOTH, expand=YES, padx=5, pady=5)
     self.console.focus()
     self.console.mark_set(INSERT, '1.0')
Ejemplo n.º 28
0
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)

        self.parent = parent
        self.parent.option_add('*tearOff', False)
        self.after(50, self.onAfter)

        #set this frame to expand to %100 available space
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)

        #init menu
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)

        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Save", command=self.onSave)
        fileMenu.add_command(label="Load", command=self.onLoad)
        fileMenu.add_command(label="Exit", command=self.onExit)
        menubar.add_cascade(label="File", menu=fileMenu)

        #init textbox
        self.text = ScrolledText(self, wrap='word')

        #add widgets to the layout manager
        self.text.grid(sticky=inflate)
Ejemplo n.º 29
0
    def __init__(self, master=None):
        # Avoiding to send it continuously.
        self.lock = False

        Frame.__init__(self, master)
        self.grid()
        self.master = master
        # Setting for ComboBox.
        self.url_lang_combobox_str = StringVar()
        self.url_lang_combobox_list = lang_list
        # UI components.
        self.receiver_email_text = Label(self, text="Receiver:")
        self.receiver_email_field = Entry(self, width=50)
        self.subject_text = Label(self, text='Subject:')
        self.subject_field = Entry(self, width=50)
        self.receiver_name_text = Label(self, text='Name:')
        self.receiver_name_field = Entry(self, width=50)
        self.url_lang_text = Label(self, text='Link lang:')
        self.url_lang_combobox = Combobox(self, textvariable=self.url_lang_combobox_str, values=self.url_lang_combobox_list, state='readonly')
        self.send_progressbar = Progressbar(self, orient='horizontal', length=500, mode='determinate', maximum=300)
        self.send_button = Button(self, text='Send', command=self._send_mail)
        self.quit_button = Button(self, text='Exit', command=self.__exit)
        self.log_msg_text = ScrolledText(self)
        # Attachment.
        self.mail_attachment_list = attachment_list[:]
        self.url_lang_link_title = None
        self.url_lang_link = copy.deepcopy(content_link)
        # Mailer
        self._mailer = None

        # Let Mailer can control components.
        Mailer.window_content = self

        self.__create_widgets()
Ejemplo n.º 30
0
	def onStart(self): 
		self.stdout = GUITools.TSafeRedirect()						# Create a buffer to replace stdout
		self.systemStreams = (sys.stdin, sys.stdout, sys.stderr)	# Save the system streams to replace them later
		sys.stdout = self.stdout									# Redirect writes to stdout and stderr
		sys.stderr = self.stdout
		
		newFrame = Frame(self)										# Create a display for the stdout
		self.textDisplay = ScrolledText(newFrame)
		self.textDisplay.config(state=DISABLED)						# make it read only
	
		self.container.pack_forget()								# remove the old window contents
		del self.container											# explicitly delete to destroy the elements
		
		self.mainContainer = newFrame									# Replace the windows content	
		self.progressContainer = Frame(self)
		self.progressContainer.pack(side=BOTTOM, fill=X)
		self.mainContainer.pack(expand=YES, fill=BOTH)					# Pack now to display the frame
		self.textDisplay.pack(expand=YES, fill=BOTH)
		
		self.callbackQ = Queue()									# Kick off the main worker thread to start downloading
		self.mainWorker = DownloadMaster(self, self.callbackQ, name='DownloadMaster')		
		#self.mainWorker = DryRun(self, self.callbackQ, name='DryRun')		
		self.mainWorker.start()
		
		self.after(self.WAKE_INTERVAL, self.onWake)					# Set the timer to refresh the GUI
Ejemplo n.º 31
0
class Editor:

    def __init__(self, master=None, parent=None):
        self.parent = parent        # ViewMetka
        self.master = master        # Frame
        self.img_ = parent.img_
        font = ("Helvetica", 12)    # 24
        self.st = ScrolledText(master, height=12, width=40,                         # height=10
                               font=font, bg='#777', fg='yellow', wrap=tk.WORD)     # tk.NONE
        # self.st.pack(fill=tk.BOTH, expand=True)
        # self.st.pack(fill=tk.Y, expand=False)
        self.st.focus()
        ttk.Separator(master).pack(fill=tk.X, expand=True)
        self.dirinfo = tk.StringVar()
        
        f = ttk.Frame(master)
        f.pack(side=tk.BOTTOM, fill=tk.X, expand=True)
        self.st.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        fdir = ttk.Frame(f, padding=1, relief=tk.SUNKEN)
        fdir.pack(side=tk.LEFT, fill=tk.X, expand=True)
        ttk.Label(fdir, image=self.img_['folder'], compound=tk.LEFT, textvariable=self.dirinfo,
                  width=9, padding=(2, 2)).pack(side=tk.LEFT, fill=tk.X, expand=True)
        ttk.Separator(f, orient=tk.VERTICAL).pack(side=tk.LEFT, fill=tk.Y)
        ttk.Sizegrip(f).pack(side=tk.RIGHT, padx=3)
        
        fhelp = ttk.Frame(f, padding=1, relief=tk.SUNKEN)
        fhelp.pack(side=tk.RIGHT, fill=tk.X, expand=False)
        btn_cancel = ttk.Button(fhelp, text="Отмена", image=self.img_['delete3'],
                                cursor="hand2", compound=tk.LEFT, command=self.cancel_)
        self.btn_save = ttk.Button(fhelp, text="Сохранить", image=self.img_['saveas'],
                                   cursor="hand2", compound=tk.LEFT, command=self.save_)
        self.btn_save.pack(side=tk.RIGHT, fill=tk.X, expand=False)
        btn_cancel.pack(side=tk.RIGHT, fill=tk.X, expand=False)
        self.btn_db_show = ttk.Button(fhelp, text="Просмотр", image=self.img_['pdf1'],
                                      state='disabled', cursor="hand2",
                                      compound=tk.LEFT, command=lambda: self.db_show(1))
        self.btn_db_print = ttk.Button(fhelp, text="Печать", image=self.img_['print1'],
                                      state='disabled', cursor="hand2",
                                      compound=tk.LEFT, command=lambda: self.db_show(0))
        self.btn_db_show.pack(side=tk.RIGHT, fill=tk.X, expand=False)
        self.btn_db_print.pack(side=tk.RIGHT, fill=tk.X, expand=False)

    def db_show(self, verbose, arg=None):
        """Просмотр или печать базы отметок""" 
        data = self.parent.result
        command = 'open' if verbose else 'print'
        cur_path = pathlib.Path('db_op.pdf')
        tmp_name = cur_path.joinpath(bakdir, cur_path)
        go_pdf(data, tmp_name)
        try:
            os.startfile(f'{tmp_name}', command)
            # os.startfile('db_op.pdf', command)
        except:
            pass               
       
    def gettext(self):
        """Получить текст из редактора"""
        return self.st.get('1.0', tk.END+'-1c')

    def clrtext(self):
        """Очистить редактор"""
        self.st.delete('1.0', tk.END)

    def set_info(self, msg):
        """Вывести msg в правый лабель"""
        return self.dirinfo.set(msg)
        
    def cancel_(self, arg=None):
        """Скрыть редактор"""
        self.st.delete(1.0, tk.END)
        self.parent.ed_frame.grid_remove()
        geom = self.parent.geometry().split("+")
        self.parent.geometry(f"1051x300+{geom[1]}+{geom[-1]}")
    
    def save_(self, arg=None):
        text = self.gettext()
        self.parent.save_coment(text)
Ejemplo n.º 32
0
class MY_GUI():
    def __init__(self, init_window_name):
        self.init_window_name = init_window_name
        self.max1 = ""
        self.filename = ""

    #设置窗口
    def set_init_window(self):
        # 设置输入输出框字体
        ft = tkFont.Font(family='宋体', size=15)

        self.init_window_name.title("电子病历标注工具_v1.2   ")  #窗口名
        #self.init_window_name.geometry('320x160+10+10')                         #290 160为窗口大小,+10 +10 定义窗口弹出时的默认展示位置
        self.init_window_name.geometry('1500x1000+10+10')
        #self.init_window_name["bg"] = "pink"                                    #窗口背景色,其他背景色见:blog.csdn.net/chl0000/article/details/7657887
        #self.init_window_name.attributes("-alpha",0.9)                          #虚化,值越小虚化程度越高
        #标签
        self.init_data_label = Label(self.init_window_name, text="待处理数据")
        self.init_data_label.grid(row=0, column=0)
        self.result_data_label = Label(self.init_window_name, text="输出结果")
        self.result_data_label.grid(row=0, column=12)
        self.log_label = Label(self.init_window_name, text="日志")
        self.log_label.grid(row=12, column=0)

        #文本框

        self.init_data_Text = ScrolledText(self.init_window_name,
                                           width=67,
                                           height=35,
                                           font=ft)  #原始数据录入框
        self.init_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10)
        self.result_data_Text = ScrolledText(self.init_window_name,
                                             width=70,
                                             height=49,
                                             font=ft)  #处理结果展示
        self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10)
        self.log_data_Text = Text(self.init_window_name, width=66,
                                  height=9)  # 日志框
        self.log_data_Text.grid(row=13, column=0, columnspan=10)
        self.init_data_Text.bind("<Button-1>", self.button_start)
        self.init_data_Text.bind("<ButtonRelease-1>", self.button_end)

        #按钮
        # self.str_trans_to_md5_button = Button(self.init_window_name, text="字符串转MD5", bg="lightblue", width=10,command=self.str_trans_to_md5)  # 调用内部方法  加()为直接调用
        # self.str_trans_to_md5_button.grid(row=1, column=11)
        #导入文件按钮
        self.input_button = Button(self.init_window_name,
                                   text="导入文件",
                                   bg="lightgreen",
                                   width=8,
                                   command=self.openfile)
        self.input_button.grid(row=0, column=2)
        # 输入窗口清空按钮
        self.delet_input_button = Button(self.init_window_name,
                                         text="一键清空",
                                         bg="red",
                                         width=8,
                                         command=self.delet_ofInput)
        self.delet_input_button.grid(row=0, column=3)
        #展示窗口清空按钮
        self.delet_result_button = Button(self.init_window_name,
                                          text="一键清空",
                                          bg="red",
                                          width=8,
                                          command=self.delet_ofResult)
        self.delet_result_button.grid(row=0, column=13)
        #导出文件按钮
        self.output_button = Button(self.init_window_name,
                                    text="导出文件",
                                    bg="lightgreen",
                                    width=8,
                                    command=self.outputfile)
        self.output_button.grid(row=0, column=14)
        #标记解剖部位按钮
        self.show_button = Button(self.init_window_name,
                                  text="解剖部位",
                                  bg="lightblue",
                                  width='8',
                                  command=self.show_jpbw)
        self.show_button.grid(row=2, column=11)
        # 标记症状描述按钮
        self.show_button = Button(self.init_window_name,
                                  text="症状描述",
                                  bg="lightyellow",
                                  width='8',
                                  command=self.show_zzms)
        self.show_button.grid(row=3, column=11)
        # 标记独立症状按钮
        self.show_button = Button(self.init_window_name,
                                  text="独立症状",
                                  bg="lightgreen",
                                  width='8',
                                  command=self.show_dlzz)
        self.show_button.grid(row=4, column=11)
        # 标记药物按钮
        self.show_button = Button(self.init_window_name,
                                  text="药物",
                                  bg="red",
                                  width='8',
                                  command=self.show_yw)
        self.show_button.grid(row=5, column=11)
        # 标记手术按钮
        self.show_button = Button(self.init_window_name,
                                  text="手术",
                                  bg="lightpink",
                                  width='8',
                                  command=self.show_ss)
        self.show_button.grid(row=6, column=11)
        # 恢复操作按钮
        self.recover_button = Button(self.init_window_name,
                                     text="恢复",
                                     width='8',
                                     command=self.recover)
        self.recover_button.grid(row=0, column=15)
        # 标注撤销功能ctrl+z实现
        self.back_button = Button(self.init_window_name,
                                  text="撤销",
                                  width='8',
                                  command=self.backToHistory)
        self.back_button.grid(row=0, column=16)
        self.result_data_Text.bind('<Control-Key-z>', self.backToHistory)

        self.result_data_Text.edit_separator()

    #功能函数
    def str_trans_to_md5(self):
        src = self.init_data_Text.get(1.0, END).strip().replace("\n",
                                                                "").encode()
        #print("src =",src)
        if src:
            try:
                myMd5 = hashlib.md5()
                myMd5.update(src)
                myMd5_Digest = myMd5.hexdigest()
                #print(myMd5_Digest)
                #输出到界面
                self.result_data_Text.delete(1.0, END)
                self.result_data_Text.insert(1.0, myMd5_Digest)
                self.write_log_to_Text("INFO:str_trans_to_md5 success")
            except:
                self.result_data_Text.delete(1.0, END)
                self.result_data_Text.insert(1.0, "字符串转MD5失败")
        else:
            self.write_log_to_Text("ERROR:str_trans_to_md5 failed")

    #获取鼠标选中文本
    def button_start(self, event):
        global s
        s = self.init_data_Text.index('@%s,%s' % (event.x, event.y))

        print(event.x, event.y)

    def button_end(self, event):
        global e
        e = self.init_data_Text.index('@%s,%s' % (event.x, event.y))
        print(str(e))

    #标记解剖部位
    def show_jpbw(self):
        self.result_data_Text.edit_separator()

        start_index = str(s)
        start_index = start_index[2:]
        start_index = int(start_index)

        end_index = str(e)
        end_index = end_index[2:]
        end_index = int(end_index)

        print(self.init_data_Text.selection_get() + "\t" + "解剖部位" + "\n")
        self.result_data_Text.insert(
            END,
            self.init_data_Text.selection_get() + "\t" + str(start_index) +
            "\t" + str(end_index) + "\t" + "解剖部位" + "\n")
        print(self.result_data_Text.get(END))
        self.max1 = self.result_data_Text.get('1.0', END)
        self.result_data_Text.edit_separator()

    # 标记症状描述
    def show_zzms(self, ):
        self.result_data_Text.edit_separator()
        start_index = str(s)
        start_index = start_index[2:]
        start_index = int(start_index)

        end_index = str(e)
        end_index = end_index[2:]
        end_index = int(end_index)

        print(self.init_data_Text.selection_get() + "\t" + str(start_index) +
              "\t" + str(end_index) + "症状描述" + "\n")
        self.result_data_Text.insert(
            END,
            self.init_data_Text.selection_get() + "\t" + str(start_index) +
            "\t" + str(end_index) + "\t" + "症状描述" + "\n")
        self.max1 = self.result_data_Text.get('1.0', END)
        self.result_data_Text.edit_separator()

    # 标记独立症状
    def show_dlzz(self):
        self.result_data_Text.edit_separator()
        start_index = str(s)
        start_index = start_index[2:]
        start_index = int(start_index)

        end_index = str(e)
        end_index = end_index[2:]
        end_index = int(end_index)

        print(self.init_data_Text.selection_get() + "\t" + str(start_index) +
              "\t" + str(end_index) + "独立症状" + "\n")
        self.result_data_Text.insert(
            END,
            self.init_data_Text.selection_get() + "\t" + str(start_index) +
            "\t" + str(end_index) + "\t" + "独立症状" + "\n")
        self.max1 = self.result_data_Text.get('1.0', END)
        self.result_data_Text.edit_separator()

    # 标记药物
    def show_yw(self):
        self.result_data_Text.edit_separator()
        start_index = str(s)
        start_index = start_index[2:]
        start_index = int(start_index)

        end_index = str(e)
        end_index = end_index[2:]
        end_index = int(end_index)

        print(self.init_data_Text.selection_get() + "\t" + "药物" + "\n")
        self.result_data_Text.insert(
            END,
            self.init_data_Text.selection_get() + "\t" + str(start_index) +
            "\t" + str(end_index) + "\t" + "药物" + "\n")
        self.max1 = self.result_data_Text.get('1.0', END)
        self.result_data_Text.edit_separator()

    # 标记手术
    def show_ss(self):
        self.result_data_Text.edit_separator()
        start_index = str(s)
        start_index = start_index[2:]
        start_index = int(start_index)

        end_index = str(e)
        end_index = end_index[2:]
        end_index = int(end_index)

        print(self.init_data_Text.selection_get() + "\t" + "手术" + "\n")
        self.result_data_Text.insert(
            END,
            self.init_data_Text.selection_get() + "\t" + str(start_index) +
            "\t" + str(end_index) + "\t" + "手术" + "\n")
        self.max1 = self.result_data_Text.get('1.0', END)
        self.result_data_Text.edit_separator()

    #标注操作撤销功能
    def callback(self, event):
        # 每当有字符插入的时候,就自动插入一个分割符,主要是防止每次撤销的时候会全部撤销
        self.result_data_Text.edit_separator()

    def backToHistory(self):  #撤销操作
        if len(self.result_data_Text.get('1.0', 'end')) != 0:
            self.result_data_Text.edit_undo()
        else:  #无字符时不能撤销
            return

    def recover(self):  #恢复操作
        if len(self.max1) == len(self.result_data_Text.get('1.0', END)):
            return
        self.result_data_Text.edit_redo()

    #输入窗口一键清空功能
    def delet_ofInput(self):
        self.init_data_Text.delete('1.0', 'end')

    #结果窗口一键清空功能
    def delet_ofResult(self):
        self.result_data_Text.delete('1.0', 'end')

    #打开文件功能
    def openfile(self):

        fname = filedialog.askopenfilename(title='打开文件',
                                           filetypes=[('All Files', '*')])
        self.filename = os.path.basename(fname)
        print(self.filename)

        f = open(fname, 'r', encoding='utf-8', errors='ignore')
        #对文本数据存储进数组,方便后续操作
        line = f.readline()
        data_list = []
        while line:
            num = list(map(str, line.split()))
            data_list.append(num)
            line = f.readline()
        f.close()
        data_array = np.array(data_list)

        f_contet = data_array
        self.init_data_Text.insert(END, f_contet)

    # 导出文件功能
    def outputfile(self):
        if self.filename != "":
            os.chdir(r'E:\GitTest\untitled\文本标注1.1\Annoation')
            f = open("ann" + self.filename,
                     'w',
                     encoding='utf-8',
                     errors='ignore')
            f.write(self.result_data_Text.get("1.0", "end"))
            showinfo(title="成功", message="标注文件已导出至Annoation文件夹")
        else:
            showinfo(title="错误", message="未找到指定文件")

    #获取当前时间
    def get_current_time(self):
        current_time = time.strftime('%Y-%m-%d %H:%M:%S',
                                     time.localtime(time.time()))
        return current_time

    #日志动态打印
    def write_log_to_Text(self, logmsg):
        global LOG_LINE_NUM
        current_time = self.get_current_time()
        logmsg_in = str(current_time) + " " + str(logmsg) + "\n"  #换行
        if LOG_LINE_NUM <= 7:
            self.log_data_Text.insert(END, logmsg_in)
            LOG_LINE_NUM = LOG_LINE_NUM + 1
        else:
            self.log_data_Text.delete(1.0, 2.0)
            self.log_data_Text.insert(END, logmsg_in)
Ejemplo n.º 33
0
#Recievers List
canv = Canvas(dispmails, width=700, height=220)
scrollbar = ttk.Scrollbar(dispmails, orient="vertical", command=canv.yview)
insidecanv = Frame(canv)
#IDK what the hell this part does found it on web for scroll window ._.
insidecanv.bind("<Configure>",
                lambda e: canv.configure(scrollregion=canv.bbox("all")))

canv.create_window((0, 0), window=insidecanv, anchor="nw")
canv.configure(yscrollcommand=scrollbar.set)

canv.pack(side="left", fill="both", expand=True)
scrollbar.pack(side="right", fill="y")

#Message Section
msghere = ScrolledText(messagesection, width=95, height=9)
msghere.pack()

#Footer
status = Label(footer)
status.grid(row=0, column=1, padx=20)
sendbtn = Button(footer, text="Send Mails", command=sendmails)
sendbtn.grid(row=0, column=0)

header.grid(row=0, column=0)
send.grid(row=1, column=0, pady=5, sticky=NSEW)
reci.grid(row=2, column=0, pady=5, sticky=NSEW)
dispmails.grid(row=3, column=0, pady=5, sticky=NSEW)
messagesection.grid(row=4, column=0, pady=5, sticky=NSEW)
footer.grid(row=5, column=0, pady=2)
Ejemplo n.º 34
0
class Root(Tk):

    def __init__(self):
        super(Root,self).__init__()
        self.title("Tkinter Browse")
        self.minsize(1000,600)
        self.labelFrame=ttk.Label(self,text="")
        self.labelFrame.grid(row=0,column=1)
        self.label_frame = ttk.Frame(self,height=50)
        self.label_frame.grid(row=10) # Stops child widgets of label_frame from resizing it

        self.entry=ttk.Entry(self.labelFrame,text="",width=50)
        self.entry.grid()
        self.totScore=0
        self.cosScore=[]
        self.jaccard=[]
        
##        for i in range(10):
##            b[i]=ttk.Label(self.labelFrame,text=i)
##            b[i].grid(row=50+i,colum=1)
        
        self.button()
       

    def button(self):
       
        self.button=ttk.Button(self.labelFrame,text="Browse",command=self.filedialog)
        self.button.grid(column=3,row=0)
        
        
        #self.entry1=ttk.Entry(self.label_frame,width=50)
       # self.entry1.grid(row=10)
        ## self.label1=ttk.Label(self.labelFrame,text="",width=100)
        #self.label1.grid(row=10)
    
    def filedialog(self):
        #root.filename = tkFileDialog.askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
        
        self.filename = filedialog.askopenfilename(initialdir = "/", title = "Select file")
        self.entry.insert(0,self.filename)
        ext=self.filename.split(".")[-1]
        if ext=='doc' or ext=='docx':
            self.text = docxpy.process(self.filename)
        if ext=='pdf':
            
            obj=open(self.filename,'rb')
            reader=PdfFileReader(obj)
            num=reader.numPages
            print (num)
            page=reader.getPage(0)
            self.text=page.extractText()

            obj.close()
    
        print(self.text)
        self.txt=ScrolledText(self.labelFrame, width=50, height=20)
        self.txt.grid(row=1,column=3)
        self.txt.insert(const.END,self.text)
        self.button1()
        #self.label1.config(text=self.text)
        # self.entry1.insert(0,self.text)
    def button1(self):
        self.button=ttk.Button(self.labelFrame,text="Check",command=self.urlretrieve)
        self.button.grid(column=3,row=25,sticky=W)
        
        
        return
    def urlretrieve(self):
        n=9
        total=0
        t=self.text
        self.queries = self.getQueries(t,n)
        #q = [' '.join(d) for d in queries]
        print(self.queries)
        self.myList=[]
        for s in self.queries:
            self.searchQuery(s)
        
        for i,url in enumerate(self.myList):
##            self.label=ttk.Label(self,text=url)
##            self.label.grid(row=30+i,column=1,sticky=W)
        
            self.getContent(self.myList[i])
            
            cosscr=self.finding()
            if cosscr==0:
                pass
            else:
                self.label=ttk.Label(self,text=url)
                self.label.grid(row=30+i,column=1,sticky=W)
                self.scoreLabel=ttk.Label(self,text=cosscr)
                self.scoreLabel.grid(row=30+i,column=3,sticky=W)
        for i in range(len(self.myList)):
            print("\n",self.myList[i])
            #self.getContent(self.myList[i])
        if len(self.cosScore)==0:
            total="Not plagiarized"
        else:
            for i in self.cosScore:    
                self.totScore=float(self.totScore+i)
                total=float(self.totScore/len(self.cosScore))
                
            print("total similarity = ",total)
        fontl=('times',20,'bold')
        self.labelscr=ttk.Label(self.labelFrame,text=total)
        self.labelscr.config(font=fontl)
        self.labelscr.grid(row=2)
                #self.view1()
        return

    def getQueries(self,text,n):
        
        sentenceEnders = re.compile('[.!?]')
        sentenceList = sentenceEnders.split(text)
        for x in sentenceList:
            if x=='' or x==' ':
                sentenceList.remove(x)
        return sentenceList
    def searchQuery(self,text):
        print("\n searching..")
        try:
            text = text.encode('utf-8')
        except:
            text =  text
        
        n = 3  # number of result
        query = text
        results = search(query, stop=n)  # returns a generator
    
        for result in results:
            #print(result)
            self.myList.append(result)
        if len(self.myList)==0:
            self.labelscr=ttk.Label(self.labelFrame,text="Not Plagiarised")
            self.labelscr.config(font=fontl)
            self.labelscr.grid(row=2)
            exit()
        
        return
    def getContent(self,text):
        #cos=0
        print("\n\nCONTENT\n")
        try:
            url=text
            #print(url)
            html = urllib.request.urlopen(url).read()
            self.Ntext=self.text_from_html(html)
            print(self.Ntext)
            #find=self.finding()
            #jacScore=self.jaccard(self.text,self.Ntext)
            #self.jaccard.append(jacScore)
            #self.similarity_chk(self.text,self.Ntext)
        except:
            print("connection error")
            #find=0
            
        return 
    def view1(self):
        
##        self.button=[]
##        for i in range(len(self.myList)):
##            self.button.append(ttk.Button(self.labelFrame,text=self.myList[i]))
##            self.button.grid(row=30+i,column=1,sticky=W)
##        self.click()
        self.cosScore=[]
        for i,url in enumerate(self.myList):
            self.label=ttk.Label(self,text=url)
            self.label.grid(row=30+i,column=1,sticky=W)
            self.label.bind("<Button-1>",lambda e,url=url:self.getContent(url))
        
        
        return
##    def click(self):
##        for i in range(len(self.myList)):
##            if self.button[i]:
##                self.button[i].command=self.getContent(self.button[i]['text'])
##        
    

    def tag_visible(self,element):
        if element.parent.name in ['style', 'script', 'head', 'title', 'meta', '[document]']:
            return False
        if isinstance(element, Comment):
            return False
        return True


    
    def text_from_html(self,body):
        soup = BeautifulSoup(body, 'html.parser')
        texts = soup.findAll(text=True)
        visible_texts = filter(self.tag_visible, texts)  
        return u" ".join(t.strip() for t in visible_texts)

##    def view(self):
##        labels=[]
##        for i in range(len(self.myList)):
##            labels.append(ttk.Label(self.labelFrame,text=self.myList[i]))
##            labels[i].grid(row=30+i,column=1,sticky=W)
####        
####        for i in range(len(self.myList)):
####            b=ttk.Label(self.labelFrame,textvariable=self.myList[i])
####            b.grid(row=50+i,colum=1)
##        return    
##
##    
##    
## 
##    
##        
##        return sentenceList   
    def entry(self): 
        
        self.entry=ttk.Entry(self.labelFrame,text="",width=50)
        self.entry.grid(column=1,row=6,padx=5,pady=60,ipady=3)
        return
    def get_cosine(self,vec1, vec2):
         intersection = set(vec1.keys()) & set(vec2.keys())

         #calculating numerator
         numerator = sum([vec1[x] * vec2[x] for x in intersection])

         #calculating denominator
         sum1 = sum([vec1[x]**2 for x in vec1.keys()])
         sum2 = sum([vec2[x]**2 for x in vec2.keys()])
         denominator = math.sqrt(sum1) * math.sqrt(sum2)

         #checking for divide by zero
         if denominator==0:
            return 0.0
         else:
            return float(numerator) / denominator

    #converts given text into a vector
    def text_to_vector(self,text):
         #uses the Regular expression above and gets all words
         words = WORD.findall(text)
         #returns a counter of all the words (count of number of occurences)
         return Counter(words)

    #returns cosine similarity of two words
    #uses: text_to_vector(text) and get_cosine(v1,v2)
    def cosineSim(self,text1,text2):
         vector1 = self.text_to_vector(text1)
         vector2 = self.text_to_vector(text2)
         #print ("vectors=",vector1)
         cosine = self.get_cosine(vector1, vector2)
         #self.cosScore.append(cosine)
         cosine=round(cosine*100,2 )
         print("Similarity is" ,cosine,"%")
         
         return cosine

    def jaccard(self,text1,text2):
        intersection=set(text1).intersection(set(text2))
        union=set(text1).union(set(text2))
        jac=len(intersection)/len(union)
        jac=round(jac*100,2 )
        print(jac)
        return jac
    

    
        
    def similarity(self,text1,text2):
        print(";;;;;;;;;;;similarity.............")
        tfidf=TfidfVectorizer().fit_transform(text1,text2)
        pairewise_similarity=tfidf*tfidf.T
        print(pairewise_similarity)

    def finding(self):
        num=0
        
        for pattern in self.queries:
            print('Looking for "%s" ->' % (pattern), end=' ')
            if re.search(pattern, self.Ntext):
                num=num+1
                #print("====num===",num)
            else:
                #print("In else part  ====num===",num)
                pass
        if num==0:
            print("No matches i this text...Not plagiarised")
            cos=0
##            self.labelscr=ttk.Label(self.labelFrame,text="Plagiarised")
##            self.labelscr.config(font=fontl)
##            self.labelscr.grid(row=2)
##            print("plagiarised")
            
        if num>0:
            cos=self.cosineSim(self.text,self.Ntext)
            self.cosScore.append(cos)
            #self.similarity(self.text,self.Ntext)
        
        
        return cos
Ejemplo n.º 35
0
 def add_widgets(self, master):
     self.output = ScrolledText(master=master, height=8, wrap=tk.WORD)
     self.output.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
     self.flavour = tk.Label(master=master, text='..')
     self.flavour.pack(side=tk.TOP, anchor='w')
Ejemplo n.º 36
0
    def set_init_window(self):
        # 设置输入输出框字体
        ft = tkFont.Font(family='宋体', size=15)

        self.init_window_name.title("电子病历标注工具_v1.2   ")  #窗口名
        #self.init_window_name.geometry('320x160+10+10')                         #290 160为窗口大小,+10 +10 定义窗口弹出时的默认展示位置
        self.init_window_name.geometry('1500x1000+10+10')
        #self.init_window_name["bg"] = "pink"                                    #窗口背景色,其他背景色见:blog.csdn.net/chl0000/article/details/7657887
        #self.init_window_name.attributes("-alpha",0.9)                          #虚化,值越小虚化程度越高
        #标签
        self.init_data_label = Label(self.init_window_name, text="待处理数据")
        self.init_data_label.grid(row=0, column=0)
        self.result_data_label = Label(self.init_window_name, text="输出结果")
        self.result_data_label.grid(row=0, column=12)
        self.log_label = Label(self.init_window_name, text="日志")
        self.log_label.grid(row=12, column=0)

        #文本框

        self.init_data_Text = ScrolledText(self.init_window_name,
                                           width=67,
                                           height=35,
                                           font=ft)  #原始数据录入框
        self.init_data_Text.grid(row=1, column=0, rowspan=10, columnspan=10)
        self.result_data_Text = ScrolledText(self.init_window_name,
                                             width=70,
                                             height=49,
                                             font=ft)  #处理结果展示
        self.result_data_Text.grid(row=1, column=12, rowspan=15, columnspan=10)
        self.log_data_Text = Text(self.init_window_name, width=66,
                                  height=9)  # 日志框
        self.log_data_Text.grid(row=13, column=0, columnspan=10)
        self.init_data_Text.bind("<Button-1>", self.button_start)
        self.init_data_Text.bind("<ButtonRelease-1>", self.button_end)

        #按钮
        # self.str_trans_to_md5_button = Button(self.init_window_name, text="字符串转MD5", bg="lightblue", width=10,command=self.str_trans_to_md5)  # 调用内部方法  加()为直接调用
        # self.str_trans_to_md5_button.grid(row=1, column=11)
        #导入文件按钮
        self.input_button = Button(self.init_window_name,
                                   text="导入文件",
                                   bg="lightgreen",
                                   width=8,
                                   command=self.openfile)
        self.input_button.grid(row=0, column=2)
        # 输入窗口清空按钮
        self.delet_input_button = Button(self.init_window_name,
                                         text="一键清空",
                                         bg="red",
                                         width=8,
                                         command=self.delet_ofInput)
        self.delet_input_button.grid(row=0, column=3)
        #展示窗口清空按钮
        self.delet_result_button = Button(self.init_window_name,
                                          text="一键清空",
                                          bg="red",
                                          width=8,
                                          command=self.delet_ofResult)
        self.delet_result_button.grid(row=0, column=13)
        #导出文件按钮
        self.output_button = Button(self.init_window_name,
                                    text="导出文件",
                                    bg="lightgreen",
                                    width=8,
                                    command=self.outputfile)
        self.output_button.grid(row=0, column=14)
        #标记解剖部位按钮
        self.show_button = Button(self.init_window_name,
                                  text="解剖部位",
                                  bg="lightblue",
                                  width='8',
                                  command=self.show_jpbw)
        self.show_button.grid(row=2, column=11)
        # 标记症状描述按钮
        self.show_button = Button(self.init_window_name,
                                  text="症状描述",
                                  bg="lightyellow",
                                  width='8',
                                  command=self.show_zzms)
        self.show_button.grid(row=3, column=11)
        # 标记独立症状按钮
        self.show_button = Button(self.init_window_name,
                                  text="独立症状",
                                  bg="lightgreen",
                                  width='8',
                                  command=self.show_dlzz)
        self.show_button.grid(row=4, column=11)
        # 标记药物按钮
        self.show_button = Button(self.init_window_name,
                                  text="药物",
                                  bg="red",
                                  width='8',
                                  command=self.show_yw)
        self.show_button.grid(row=5, column=11)
        # 标记手术按钮
        self.show_button = Button(self.init_window_name,
                                  text="手术",
                                  bg="lightpink",
                                  width='8',
                                  command=self.show_ss)
        self.show_button.grid(row=6, column=11)
        # 恢复操作按钮
        self.recover_button = Button(self.init_window_name,
                                     text="恢复",
                                     width='8',
                                     command=self.recover)
        self.recover_button.grid(row=0, column=15)
        # 标注撤销功能ctrl+z实现
        self.back_button = Button(self.init_window_name,
                                  text="撤销",
                                  width='8',
                                  command=self.backToHistory)
        self.back_button.grid(row=0, column=16)
        self.result_data_Text.bind('<Control-Key-z>', self.backToHistory)

        self.result_data_Text.edit_separator()
Ejemplo n.º 37
0
class MainForm:

    def __init__(self, gui_config: GuiConfig, icon_path: str):
        # >>> Initialize class <<<
        self.num_total_task, self.num_task_finished, self.num_task_succeed = 0, 0, 0
        self.fuz_license, self.fuz_config_pack, self.fuz_url_info, self.fuz_file_items = None, None, None, None

        self.__gui_config = gui_config
        I18nUtil.set_language(gui_config['language'])
        self.__should_restart_me = False

        # >>> Initialize Queue, Timer and threading utils <<<
        self.download_thread_pool: Optional[ThreadPoolExecutor] = None
        self.descramble_thread_pool: Optional[ThreadPoolExecutor] = None
        self.local_http_util: threading.local = None
        self.queue: "Queue[DelegatedTask]" = Queue()

        # >>> Initialize GUI <<<
        self.win = tk.Tk()
        self.win.grid_columnconfigure(0, weight=1)
        self.win.title(tr('Comic FUZ Manga Downloader GUI'))
        self.win.minsize(width=700, height=400)

        if icon_path:
            self.win.iconbitmap(icon_path)

        menu = tk.Menu()

        # Language menu
        submenu = tk.Menu(tearoff=0)
        for i in LANGUAGES:
            submenu.add_command(label=i, command=functools.partial(self.switch_language, to=i))
        menu.add_cascade(label=tr('Langauge'), menu=submenu)

        # About menu
        submenu = tk.Menu(tearoff=0)
        submenu.add_command(label=tr('About'), command=self.about_me)
        menu.add_cascade(label=tr('Help'), menu=submenu)
        self.win['menu'] = menu

        frame = ttk.LabelFrame(self.win, text=tr('Download Settings'), padding=(10, 5, 10, 5))
        frame.grid(row=0, column=0, sticky='we', padx=15, pady=10)
        frame.grid_columnconfigure(1, weight=1)
        for row_index in range(5):
            frame.grid_rowconfigure(row_index, pad=3)

        # Row
        label = ttk.Label(frame, text=tr('Manga URL:'))
        label.grid(row=0, column=0, sticky='e')
        self.manga_url = tk.StringVar(value=gui_config['manga_url'])
        ttk.Entry(frame, textvariable=self.manga_url).grid(row=0, column=1, sticky='we', padx=10)

        # Row
        label = ttk.Label(frame, text=tr('Cookies.txt path:'))
        label.grid(row=1, column=0, sticky='e')
        self.cookie_path = tk.StringVar(value=gui_config['cookie_txt_path'])
        self.txt_cookie_path = ttk.Entry(frame, textvariable=self.cookie_path)
        self.txt_cookie_path.grid(row=1, column=1, sticky='we', padx=10)
        btn = ttk.Button(frame, text=tr('Browse...'), command=self.browse_cookie_path)
        btn.grid(row=1, column=2)

        # Row
        label = ttk.Label(frame, text=tr('Save to:'))
        label.grid(row=2, column=0, sticky='e')
        self.output_path = tk.StringVar(value=gui_config['save_to_path'])
        self.txt_output_path = ttk.Entry(frame, textvariable=self.output_path)
        self.txt_output_path.grid(row=2, column=1, sticky='we', padx=10)
        btn = ttk.Button(frame, text=tr('Browse...'), command=self.browse_output_path)
        btn.grid(row=2, column=2)

        # Row
        label = ttk.Label(frame, text=tr('Proxy:'))
        label.grid(row=3, column=0, sticky='e')
        sub_frame = ttk.Frame(frame)
        sub_frame.grid(row=3, column=1, sticky='w', padx=10)
        self.proxy_state = tk.StringVar(value='disabled')
        ttk.Radiobutton(
            sub_frame, text=tr('[Proxy] Disabled'), value='disabled',
            variable=self.proxy_state, command=self.proxy_radiobutton_clicked,
        ).grid(row=0, column=0)
        ttk.Radiobutton(
            sub_frame, text=tr('[Proxy] HTTP'), value='http',
            variable=self.proxy_state, command=self.proxy_radiobutton_clicked,
        ).grid(row=0, column=1)
        ttk.Radiobutton(
            sub_frame, text=tr('[Proxy] SOCKS5'), value='socks5',
            variable=self.proxy_state, command=self.proxy_radiobutton_clicked,
        ).grid(row=0, column=2, padx=(0, 20))
        self.proxy_host = tk.StringVar()
        self.proxy_host_txt = ttk.Entry(sub_frame, textvariable=self.proxy_host, state='disabled')
        self.proxy_host_txt.grid(row=0, column=3)
        ttk.Label(sub_frame, text=':').grid(row=0, column=4)
        self.proxy_port = tk.StringVar()
        self.proxy_port_txt = ttk.Entry(sub_frame, textvariable=self.proxy_port, width=6, state='disabled')
        self.proxy_port_txt.grid(row=0, column=5)

        # Row
        label = ttk.Label(frame, text=tr('Threads num:'))
        label.grid(row=4, column=0, sticky='e')
        self.spin_threads = ttk.Spinbox(
            frame, values=tuple(range(1, MAX_THREAD_LIMIT + 1)), width=15, validate='all'
        )
        self.spin_threads.set(gui_config['thread_num'])
        self.spin_threads.grid(row=4, column=1, sticky='w', padx=10, pady=(3, 0))

        # Row
        frame = ttk.Frame(self.win, padding=(15, 0, 15, 10))
        frame.grid(row=1, column=0, sticky='we')
        frame.grid_columnconfigure(0, weight=1)

        self.manga_info_frame = ttk.LabelFrame(frame, text=tr('Manga Info'), padding=(10, 5, 10, 10))
        self.manga_info_frame.grid(row=1, column=0, sticky='news', padx=(0, 15), pady=0)
        self.manga_info_frame.grid_columnconfigure(1, weight=1)

        ttk.Label(self.manga_info_frame, text=tr('Title:')).grid(row=0, column=0, sticky='e', padx=(0, 5))
        self.manga_title = ttk.Label(self.manga_info_frame, width=60)
        self.manga_title.grid(row=0, column=1, sticky='w')

        ttk.Label(self.manga_info_frame, text=tr('Page num:')).grid(row=1, column=0, sticky='e', padx=(0, 5))
        self.manga_page_num = ttk.Label(self.manga_info_frame, width=10)
        self.manga_page_num.grid(row=1, column=1, sticky='w')

        self.download_option_frame = ttk.LabelFrame(frame, text=tr('Download Options'), padding=(10, 5, 10, 10))
        self.download_option_frame.grid(row=1, column=1, sticky='news')

        ttk.Label(
            self.download_option_frame, text=tr('[Download Options] Range:')
        ).grid(row=0, column=0, sticky='e', padx=(0, 5))
        self.range_option = tk.StringVar(value='all')
        ttk.Radiobutton(
            self.download_option_frame, text=tr('[Download Options] All'), variable=self.range_option, value='all',
            command=self.range_option_clicked,
        ).grid(row=0, column=1)
        ttk.Radiobutton(
            self.download_option_frame, text=tr('[Download Options] Partition'), variable=self.range_option,
            value='part',
            command=self.range_option_clicked,
        ).grid(row=0, column=2)
        ttk.Label(
            self.download_option_frame, text=tr('[Download Options] Pages:')
        ).grid(row=1, column=0, sticky='e', padx=(0, 5))
        self.download_page_range = tk.StringVar()
        self.txt_download_page_range = ttk.Entry(
            self.download_option_frame, textvariable=self.download_page_range, state='disabled')
        self.txt_download_page_range.grid(row=1, column=1, columnspan=2, sticky='we')

        # Row
        frame = ttk.Frame(self.win)
        frame.grid(row=2, column=0, sticky='we', padx=15, pady=0)
        frame.grid_columnconfigure(0, weight=1)

        self.progress_indicator = tk.IntVar()
        progress_bar = ttk.Progressbar(
            frame, mode='determinate', orient=tk.HORIZONTAL, variable=self.progress_indicator)
        progress_bar.grid(row=0, column=0, sticky='news', pady=1, padx=(0, 10))
        self.fetch_btn = ttk.Button(frame, text=tr('Fetch'), command=self.fetch_btn_clicked)
        self.fetch_btn.grid(row=0, column=1, padx=(0, 5))
        self.download_btn = ttk.Button(frame, text=tr('Download'), state='disabled', command=self.download_btn_clicked)
        self.download_btn.grid(row=0, column=2, padx=(0, 5))
        self.cancel_btn = ttk.Button(frame, text=tr('Cancel'), state='disabled', command=self.cancel_btn_clicked)
        self.cancel_btn.grid(row=0, column=3)

        self.scroll_text = ScrolledText(self.win, height=10, state='disabled')
        self.scroll_text.grid(row=3, column=0, sticky='news', padx=15, pady=(10, 15))

        self.win.grid_rowconfigure(3, weight=1)

        # >>> Initialize logging system <<<
        self.scroll_text.tag_config('verbose', foreground='#808080')
        self.scroll_text.tag_config('info', foreground='#449944')
        self.scroll_text.tag_config('error', foreground='#e25252')

        # Initial log, to solve the `Invalid index` issue
        self.scroll_text.insert(tk.INSERT, tr('Welcome to use the downloader.'), 'verbose')

    def about_me(self):
        tkmsg.showinfo(title=tr('[MessageBox] About'), message=tr('[MessageBox] [About Message]'), parent=self.win)

    def main_loop(self) -> Tuple[GuiConfig, bool]:
        """
        Launch the main loop.
        return: (gui_config, should_restart_me)
            - The first element records latest GUI config.
            - The second element indicates requesting outer code to show a new form instead of exit program.
        """
        # Start delegation queue
        self.win.after(QUEUE_CHECKING_DELAY, self.regularly_check_queue)

        self.win.mainloop()

        # Remember settings
        self.__gui_config['cookie_txt_path'] = self.cookie_path.get().strip()
        self.__gui_config['manga_url'] = self.manga_url.get().strip()
        self.__gui_config['save_to_path'] = self.output_path.get().strip()

        return self.__gui_config, self.__should_restart_me

    def __log(self, x: str, log_type: str):
        """
        log_type: one of `verbose`, `info`, `error`.
        """
        self.scroll_text['state'] = 'normal'
        self.scroll_text.insert(tk.END, x + '\n', log_type)
        self.scroll_text['state'] = 'disabled'
        self.scroll_text.see(tk.END)

    def log_verbose(self, x: str) -> None:
        self.__log(x, 'verbose')

    def log_info(self, x: str) -> None:
        self.__log(x, 'info')

    def log_error(self, x: str) -> None:
        self.__log(x, 'error')

    def regularly_check_queue(self) -> None:
        while True:
            try:
                task = self.queue.get_nowait()
            except QueueEmptyError:
                break

            task.func(*task.args, **task.kwargs)

        self.win.after(QUEUE_CHECKING_DELAY, self.regularly_check_queue)

    def proxy_radiobutton_clicked(self) -> None:
        if self.proxy_state.get() == 'disabled':
            self.proxy_host_txt['state'] = 'disabled'
            self.proxy_port_txt['state'] = 'disabled'
        else:
            self.proxy_host_txt['state'] = 'normal'
            self.proxy_port_txt['state'] = 'normal'

    def cookie_path_change(self):
        self.__gui_config['cookie_txt_path'] = self.cookie_path.get()

    def browse_cookie_path(self):
        result = filedialog.askopenfilename(
            parent=self.win,
            title=tr('Select cookies.txt...'),
            filetypes=[(tr('Text files'), '*.txt')],
        )
        if result:
            result = str(Path(result).resolve(strict=False))
            self.cookie_path.set(result)

    def browse_output_path(self):
        result = filedialog.askdirectory(
            parent=self.win,
            title=tr('Select output directory...'),
        )
        if result:
            result = str(Path(result).resolve(strict=False))
            self.output_path.set(result)

    def range_option_clicked(self):
        state_mapping = {
            'all': 'disabled',
            'part': 'normal',
        }
        self.txt_download_page_range['state'] = state_mapping[self.range_option.get()]

    def switch_language(self, to: str) -> None:
        if self.__gui_config['language'] == to:
            return

        self.__should_restart_me = True
        self.__gui_config['language'] = to
        self.win.destroy()

    def check_fetch_settings(self) -> bool:
        self.get_and_correct_spin_thread_num()

        if validate_url(self.manga_url.get()) is not True:
            self.log_and_show_error(tr('The URL in the Manga URL field is invalid.'))
            return False

        if not Path(self.cookie_path.get()).exists():
            self.log_and_show_error(tr('The cookies.txt does not exist at the given path.'))
            return False

        if self.proxy_state.get() != 'disabled':
            if self.proxy_host.get().strip() == '':
                self.log_and_show_error(tr('Invalid proxy host name.'))
                return False

            try:
                proxy_port = int(self.proxy_port.get())
                if proxy_port > 65535 or proxy_port < 1:
                    raise RuntimeError()
            except:
                self.log_and_show_error(tr('Invalid proxy port.'))
                return False

        return True

    def is_download_range_correct(self) -> bool:
        download_range = self.download_page_range.get()
        download_range = RE_SPACE.sub('', download_range)
        return bool(RE_PAGE_RANGE.fullmatch(download_range))

    def check_download_settings(self) -> bool:
        if not self.check_fetch_settings():
            return False

        if self.output_path.get().strip() == '':
            self.log_and_show_error(tr('The download directory is not specified.'))
            return False

        if self.range_option.get() == 'part' and not self.is_download_range_correct():
            self.log_and_show_error(tr('You chose to download part of mangas, '
                                       'but you did not specify correct page ranges.'))
            return False

        return True

    def get_and_correct_spin_thread_num(self) -> int:
        try:
            thread_num = int(self.spin_threads.get())
            if thread_num < 1:
                thread_num = 1
            elif thread_num > MAX_THREAD_LIMIT:
                thread_num = MAX_THREAD_LIMIT
        except:
            thread_num = DEFAULT_THREAD_NUM

        self.spin_threads.set(thread_num)
        return thread_num

    def log_and_show_error(self, error_msg: str) -> None:
        self.log_error(error_msg)
        tkmsg.showerror(title=tr('[MessageBox] Error'), message=error_msg[:MESSAGE_BOX_MAX_LENGTH], parent=self.win)

    def get_proxy_url(self):
        proxy_scheme = self.proxy_state.get().strip()
        if proxy_scheme == 'disabled':
            return ''

        return f'{proxy_scheme}://{self.proxy_host.get().strip()}:{self.proxy_port.get().strip()}'

    def clear_manga_info(self):
        self.manga_title['text'] = ''
        self.manga_page_num['text'] = ''
        self.fetch_btn['state'] = 'disabled'
        self.download_btn['state'] = 'disabled'

    def cancel_btn_clicked(self) -> None:
        self.clear_manga_info()
        if self.download_thread_pool is not None:
            self.log_verbose(tr('Canceling...'))
            self.reset_download_state()

        self.cancel_btn['state'] = 'disabled'

    def fetch_btn_clicked(self) -> None:
        if not self.check_fetch_settings():
            return

        self.log_verbose(tr('Fetching manga info...'))
        try:
            url_info = ComicFuzUrlParser.parse(self.manga_url.get())
        except:
            traceback.print_exc()
            self.log_and_show_error(
                tr('Unable to parse Comic FUZ URL. You should specify the URL of the page that reads manga.'))
            return

        self.clear_manga_info()

        self.fuz_url_info = url_info
        Thread(
            target=self.thr_fetch_manga_info,
            args=(HttpUtil(Path(self.cookie_path.get()), self.get_proxy_url()), self.fuz_url_info),
            name='FetchMangaInfo',
        ).start()

    def fetch_manga_info_finished(
            self, license: ComicFuzLicense, config_pack: Mapping[str, Any], file_items: Sequence[ComicFuzFileItem],
    ):
        self.fuz_license = license
        self.fuz_config_pack = config_pack
        self.fuz_file_items = file_items

        self.manga_title['text'] = self.fuz_url_info.manga_name
        self.manga_page_num['text'] = len(file_items)

        self.download_btn['state'] = 'normal'
        self.fetch_btn['state'] = 'normal'

        self.log_info(tr('Manga info fetched. Ready to download.'))

    def thr_fetch_manga_info_failed(self, reason: str):
        self.log_and_show_error(tr('Failed to fetch manga info. The traceback is listed below.\n{}').format(reason))
        self.fetch_btn['state'] = 'normal'

    def thr_fetch_manga_info(
            self, http_util: HttpUtil, manga_url_info: ComicFuzUrlInfo
    ) -> None:
        try:
            license, config_pack = ComicFuzService.get_license_and_cfg_pack(manga_url_info, http_util)
            file_items = CfgPackParser.parse(config_pack, manga_url_info.cid)
        except:
            traceback.print_exc()
            self.queue.put(DelegatedTask(
                func=self.thr_fetch_manga_info_failed,
                args=(traceback.format_exc(),)
            ))
            return

        self.queue.put(DelegatedTask(
            func=self.fetch_manga_info_finished,
            args=(license, config_pack, file_items),
        ))

    def get_save_to_path(self) -> Path:
        save_to_path = Path(self.output_path.get().strip())
        if save_to_path.exists():
            if not save_to_path.is_dir():
                raise RuntimeError('The save_to_path exists but is not a directory.')
        else:
            os.makedirs(save_to_path, exist_ok=True)

        return save_to_path

    def parse_download_range(self) -> Sequence[Tuple[int, int]]:
        range_option = self.range_option.get()
        if range_option == 'all':
            return [(1, len(self.fuz_file_items) + 1)]

        page_range_str = self.download_page_range.get()
        page_ranges = RangeUtil.parse_range_string(
            page_range_str, right_open=False, bounding_range=(1, len(self.fuz_file_items) + 1))
        page_ranges = RangeUtil.merge_ranges(page_ranges)

        return page_ranges

    def thr_download_image(self, task: ImageDownloadTask):
        try:
            http_util = getattr(self.local_http_util, 'http_util', None)
            if http_util is None:
                http_util = HttpUtil(*task.http_util_param)
                self.local_http_util.http_util = http_util

            task.save_image_file = (task.save_to_path / f'{task.file_item.file_disk_name}.png')
            if task.save_image_file.exists():
                self.queue.put(DelegatedTask(
                    func=self.download_image_finished, args=(True, task.page_num)
                ))
                return

            task.image_bytes = ComicFuzService.get_image(task.file_item.file_path, task.license, http_util)
            self.descramble_thread_pool.submit(
                self.thr_descramble_image, task
            )
        except:
            traceback.print_exc()
            self.queue.put(DelegatedTask(
                func=self.download_image_finished, args=(False, task.page_num)
            ))

    def thr_descramble_image(
            self, task: ImageDownloadTask,
    ) -> None:
        try:
            pattern = ScrambleCalculator.pattern(task.file_item)
            descrambled = ImageDescrambler.descramble_image(task.image_bytes, pattern, task.file_item.dummy_pixels)
            task.save_image_file.write_bytes(descrambled)

            self.queue.put(DelegatedTask(
                func=self.download_image_finished, args=(True, task.page_num)
            ))
        except:
            traceback.print_exc()
            self.queue.put(DelegatedTask(
                func=self.download_image_finished, args=(False, task.page_num)
            ))

    def download_image_finished(self, succeed: bool, page_num: int):
        self.num_task_finished += 1
        if succeed:
            self.num_task_succeed += 1

        if self.num_total_task == 0:
            progress = 0
        else:
            progress = int(self.num_task_finished / self.num_total_task * 100)
        self.progress_indicator.set(progress)

        if succeed:
            self.log_verbose(tr('Page {page} successfully downloaded.').format(page=page_num))
        else:
            self.log_error(tr('Failed to download page {page}.').format(page=page_num))

        if self.num_task_finished >= self.num_total_task:
            self.reset_download_state()

            self.log_info(tr('Manga download finished. {succeed} succeed and {failed} failed.').format(
                succeed=self.num_task_succeed, failed=self.num_total_task - self.num_task_succeed
            ))

    def thr_reset_download_state(self):
        self.download_thread_pool.shutdown(wait=True, cancel_futures=True)
        self.download_thread_pool = None
        self.descramble_thread_pool.shutdown(wait=True, cancel_futures=True)
        self.descramble_thread_pool = None
        self.local_http_util = None

        self.queue.put(DelegatedTask(
            func=self.reset_download_state_finished,
        ))

    def reset_download_state_finished(self):
        self.spin_threads['state'] = 'normal'
        self.fetch_btn['state'] = 'normal'
        self.download_btn['state'] = 'normal'
        self.cancel_btn['state'] = 'disabled'

    def reset_download_state(self):
        Thread(target=self.thr_reset_download_state, name='Shutdown-thread-pool').start()

    def download_btn_clicked(self) -> None:
        if not self.check_download_settings():
            return

        try:
            save_to_path = self.get_save_to_path()
        except:
            traceback.print_exc()
            self.log_and_show_error(tr('The images can not be saved to the specified path.'))
            return

        download_range = self.parse_download_range()
        self.num_total_task, self.num_task_finished, self.num_task_succeed = 0, 0, 0
        for a, b in download_range:
            self.num_total_task += b - a

        self.download_thread_pool = ThreadPoolExecutor(max_workers=int(self.spin_threads.get()))
        self.descramble_thread_pool = ThreadPoolExecutor(max_workers=max(MAX_CPU_THREAD, os.cpu_count()))
        self.local_http_util = threading.local()

        for a, b in download_range:
            for i in range(a, b):
                task = ImageDownloadTask(
                    file_item=self.fuz_file_items[i - 1],
                    license=self.fuz_license,
                    http_util_param=(Path(self.cookie_path.get()), self.get_proxy_url()),
                    save_to_path=save_to_path,
                    save_image_file=None,
                    page_num=i,
                    image_bytes=None,
                )
                self.download_thread_pool.submit(
                    self.thr_download_image, task
                )

        self.spin_threads['state'] = 'disabled'
        self.fetch_btn['state'] = 'disabled'
        self.download_btn['state'] = 'disabled'
        self.cancel_btn['state'] = 'normal'
        self.log_verbose(tr('Download begins'))
Ejemplo n.º 38
0
 def __init__(self, master, **option):
     option.setdefault('text', '答え(改行区切り)')
     super().__init__(master, **option)
     self.answerText = ScrolledText(self, height=5, undo=True)
     self.answerText.pack()
Ejemplo n.º 39
0
class Bank(Frame):
    def __init__(self, master=None):
        self.main()
        self.chances = 3

    def main(self):
        mainDesign(master, self)
        mainMenu(master, self)

        Label(self,
              text="WELCOME TO THE UNIVERSITY OF IBADAN ATM OUTLET",
              fg="blue",
              relief=RAISED,
              bg="black",
              borderwidth=10,
              height=2,
              padx=3,
              pady=3,
              width=46,
              font="Calibri").grid()

        Button(self,
               text="Click To Enter As Admin",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               command=self.AdminStart,
               activeforeground="red").grid(sticky=W + S, pady=10, padx=5)

        Button(self,
               text="Click To Enter As User",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               command=self.UserStart,
               activeforeground="red").grid(sticky=W + S, padx=5)

    def UserStart(self):
        """Start of User-Account Activities"""
        def toggle():
            #toggles the show-password checkbox on or off
            self.e.configure(
                show="") if self.cVar.get() == 1 else self.e.configure(
                    show="*")

        userDesign(master, self)
        mainMenu(master, self)
        """checking number of wrong trials,if number of wrong trials exceeds
        three,then the system automatically generates a new pin for the user
        """
        if self.chances > 0:
            if self.chances == 1:
                messagebox.showinfo("log-in trial", "Last log-in trial....")
            if self.chances == 2:
                messagebox.showinfo("log-in trial",
                                    "Only 2 more log-in trials allowed....")

            self.name = StringVar()
            self.pin = StringVar()

            Label(self,
                  text="Acct. Name :",
                  fg="white",
                  bg="blue",
                  width=10,
                  justify=LEFT).grid(sticky=E + S + N + W, pady=10, padx=5)
            self.e1 = Entry(self,
                            bg="pink",
                            fg="blue",
                            width=15,
                            textvariable=self.name,
                            exportselection=0)
            self.e1.grid(row=1,
                         column=1,
                         sticky=W + N + S + E,
                         pady=10,
                         padx=5)

            Label(self,
                  text="Acct. No :",
                  fg="white",
                  bg="blue",
                  width=10,
                  justify=LEFT).grid(sticky=E + S + N + W, padx=5)
            self.e = Entry(self,
                           bg="pink",
                           fg="blue",
                           width=15,
                           textvariable=self.pin,
                           exportselection=0,
                           show="*")
            self.e.grid(row=2, column=1, sticky=W + N + S + E, padx=5)

            self.cVar = IntVar()
            Checkbutton(self,
                        text="show password",
                        variable=self.cVar,
                        command=toggle,
                        bg="blue",
                        activebackground="blue").grid(sticky=N + W + S + E,
                                                      column=1)

            Button(self, text="Log-In", command=self.NameCheck).grid()
        else:
            pin = random.choice(
                rnd
            )  #choose a random 4-digit pin from a list of generated numbers
            acct = BankAcct.ResetPin(self.name.get(), pin)
            if acct:
                messagebox.showinfo(
                    "CHANGED", "Your Pin Has Been Changed Automatically\
                                \nDue To Failure To Provide Correct Pin\nExiting Now ..."
                )
                self.master.quit()
            else:
                messagebox.showinfo("EXIT", "Exiting Now...")
                self.master.quit()

    def NameCheck(self):
        #checks if user's acct. name exists.if it does,
        #proceeds to check pin
        name = self.name.get()
        name = name.lower()
        acct = BankAcct.CheckName(name)

        if acct:
            result = self.CheckPin()  #checking user's pin
            if result:
                if self.k == 1234:
                    self.ChangePin()
                else:
                    self.UserOption()
            else:
                self.chances -= 1
                self.UserStart()
        else:
            messagebox.showerror("InValid Credentials",
                                 "Invalid Log-in credential !!")

    def CheckPin(self):
        """Function to check pin"""
        try:
            int(self.pin.get())
        except ValueError:
            messagebox.showerror("ERROR", "password can only be in integer")
            return

        self.k = int(self.pin.get())
        if isinstance(self.k, int) or isinstance(self.k, float):
            acct = BankAcct(self.k)
            ac = acct.CheckPin(self.name.get())
            del acct
            if ac: return True
            else:
                messagebox.showerror("InValid Credentials",
                                     "Invalid Account Pin !!")
                return False

    def User(self, str):
        userDesign(master, self, str)
        userMenu(master, self)

    def UserOption(self):
        """User's options selection menu"""

        userDesign(master, self)
        userMenu(master, self)

        Button(self,
               text="Deposit Cash",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.Deposit).grid(columnspan=100)
        Button(self,
               text="Withdraw Cash",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.Withdraw).grid(columnspan=100)

        Button(self,
               text="Balance Inquiry",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.balance).grid(columnspan=100)
        Button(self,
               text="Transfer Cash",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.Transfer).grid(columnspan=100)

        Button(self,
               text="Change Pin",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.ChangePin).grid(columnspan=100)
        Button(self,
               text="Delete Account",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.DelAccount).grid(columnspan=100)

        Button(self,
               text="Return Card",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.Cancel).grid(columnspan=100)

    def Deposit(self):
        """deposition of cash to acct."""
        def dep():
            try:
                amnt = int(self.amnt.get())
                if not amnt % 1000 == 0:
                    messagebox.showinfo(
                        "Error",
                        "Amount Should Be In Multiples Of Thousands!!.")
                    return
                if amnt < 0:
                    messagebox.showinfo(
                        "Error", "Amount should be greater than zero.!!")
                    return
            except ValueError:
                messagebox.showwarning("ERROR",
                                       "Anount Can Only Be In Integers")
                return

            acct = BankAcct(self.k)
            result = acct.Deposit(amnt)
            del acct
            self.Result("Deposition", result)

        self.User("DEPOSIT FUNDS")
        self.amnt = StringVar()

        Label(self,
              text="Amount Can Only be In Multiples Of Thousands...",
              fg="white",
              bg="blue",
              justify=LEFT).grid(columnspan=50,
                                 sticky=E + S + N + W,
                                 pady=10,
                                 padx=5)

        Label(self,
              text="Amount :",
              fg="white",
              bg="blue",
              width=10,
              justify=LEFT).grid(row=2,
                                 column=0,
                                 sticky=E + S + N + W,
                                 pady=10,
                                 padx=5)
        Entry(self,
              bg="pink",
              fg="blue",
              width=15,
              textvariable=self.amnt,
              exportselection=0).grid(row=2,
                                      column=1,
                                      sticky=W + N + S + E,
                                      pady=10,
                                      padx=5)

        Button(self, text="Deposit", command=dep).grid()

    def Withdraw(self):
        """Withdrawal of funds from acct.If amount entered or selected is more than amnt
        in user's acct,gives an error message signifying "Insufficient balance"""
        def WithDrawal(amnt):
            acct = BankAcct(self.k)
            result = acct.WithDraw(amnt)
            del acct
            self.Result("Withdrawal", result)

        def AmountCheck():
            #function to check if amount is a multiple of #1000
            try:
                amnt = int(self.amnt.get())
                if not amnt % 1000 == 0:
                    messagebox.showinfo(
                        "Error",
                        "Amount Should Be In Multiples Of Thousands!!.")
                    return
                if amnt < 0:
                    messagebox.showinfo("Error",
                                        "Amount should be greater than zero.")
                    return
            except ValueError:
                messagebox.showwarning("ERROR",
                                       "Anount Can Only Be In Integers")
                return
            WithDrawal(amnt)

        def Others():
            self.User("WITHDRAW CASH")
            self.amnt = StringVar()

            Label(self,
                  text="Amount Can Only be In Multiples Of Thousands...",
                  fg="white",
                  bg="blue",
                  justify=LEFT).grid(columnspan=50,
                                     sticky=E + S + N + W,
                                     pady=10,
                                     padx=5)

            Label(self,
                  text="Amount :",
                  fg="white",
                  bg="blue",
                  width=10,
                  justify=LEFT).grid(row=2,
                                     column=0,
                                     sticky=E + S + N + W,
                                     pady=10,
                                     padx=5)
            Entry(self,
                  bg="pink",
                  fg="blue",
                  width=15,
                  textvariable=self.amnt,
                  exportselection=0).grid(row=2,
                                          column=1,
                                          sticky=W + N + S + E,
                                          pady=10,
                                          padx=5)

            Button(self, text="Withdraw", command=AmountCheck).grid()

        self.User("WITHDRAW CASH")
        Label(self,
              text="Select The Amount You Want To Withdraw:",
              fg="white",
              bg="blue").grid(columnspan=50,
                              sticky=E + S + N + W,
                              pady=10,
                              padx=5)

        Button(self,
               bg="pink",
               fg="blue",
               text="1,000",
               command=lambda: WithDrawal(1000),
               activeforeground="red",
               width=20).grid(row=2, column=0, sticky=E + S + N + W, padx=10)
        Button(self,
               bg="pink",
               fg="blue",
               text="2,000",
               command=lambda: WithDrawal(2000),
               activeforeground="red",
               width=20).grid(row=2, column=1, sticky=E + S + N + W, padx=5)

        Button(self,
               bg="pink",
               fg="blue",
               text="5,000",
               command=lambda: WithDrawal(5000),
               activeforeground="red",
               width=20).grid(row=3,
                              column=0,
                              sticky=E + S + N + W,
                              padx=10,
                              pady=10)
        Button(self,
               bg="pink",
               fg="blue",
               text="10,000",
               command=lambda: WithDrawal(10000),
               activeforeground="red",
               width=20).grid(row=3,
                              column=1,
                              sticky=E + S + N + W,
                              padx=5,
                              pady=10)

        Button(self,
               bg="pink",
               fg="blue",
               text="20,000",
               command=lambda: WithDrawal(20000),
               activeforeground="red",
               width=20).grid(row=4,
                              column=0,
                              sticky=E + S + N + W,
                              padx=10,
                              pady=10)
        Button(self,
               bg="pink",
               fg="blue",
               text="Select Others",
               command=Others,
               activeforeground="red",
               width=20).grid(row=4,
                              column=1,
                              sticky=E + S + N + W,
                              padx=5,
                              pady=10)

    def balance(self):
        #Checks User's account balance
        self.User("BALANCE INQUIRY")
        acct = BankAcct(self.k)
        bal = acct.GetBalance()
        bal = self.strAmnt(bal)
        del acct
        var = "Your Account Balance Is  #{}".format(bal)
        messagebox.showinfo("BALANCE", var)
        self.UserOption()

    def Transfer(self):
        """transfer funds to another acct. through recipient's acct. No."""
        def Trans():
            self.User("TRANSFER FUNDS")
            self.amnt = StringVar()

            Label(self,
                  text="Amount Can Only be In Multiples Of Thousands...",
                  fg="white",
                  bg="blue",
                  justify=LEFT).grid(columnspan=50,
                                     sticky=E + S + N + W,
                                     pady=10,
                                     padx=5)

            Label(self,
                  text="Amount To Transfer :",
                  fg="white",
                  bg="blue",
                  width=20,
                  justify=LEFT).grid(row=2,
                                     column=0,
                                     sticky=E + S + N + W,
                                     padx=5)
            Entry(self,
                  bg="pink",
                  fg="blue",
                  width=15,
                  textvariable=self.amnt,
                  exportselection=0).grid(row=2,
                                          column=1,
                                          sticky=W + N + S + E,
                                          padx=5)

            Button(self, text="Transfer", command=AmountCheck).grid()

        def AmountCheck():
            #checks to see if amount is a valid entry(multiple of #1000)
            try:
                amnt = int(self.amnt.get())
                if not amnt % 1000 == 0:
                    messagebox.showinfo(
                        "Error",
                        "Amount Should Be In Multiples Of Thousands!!.")
                    return
                if amnt < 0:
                    messagebox.showinfo(
                        "Error", "Amount should be greater than zero.!!")
                    return
            except ValueError:
                messagebox.showwarning("ERROR",
                                       "Anount Can Only Be In Integers")
                return
            acct = BankAcct(self.k)
            result = acct.Transfer(int(self.acctNo.get()), amnt)
            del acct
            self.Result("Transfer", result)

        def CheckAcctNo():
            #confirms if entered recipient's acct No. is a valid one
            try:
                int(self.acctNo.get())
                if not len(self.acctNo.get()) == 6:
                    messagebox.showwarning("Invalid Acct. Number",
                                           "Type In A Valid Account Number")
                    return
                else:
                    Trans()
            except ValueError:
                messagebox.showwarning(
                    "Error", "Please Type In A Valid Account Number!!")
                return

        self.User("TRANSFER FUNDS")
        self.acctNo = StringVar()

        Label(self,
              text="Recipient's Acct No:",
              fg="white",
              bg="blue",
              width=20,
              justify=LEFT).grid(sticky=E + S + N + W, pady=10, padx=5)
        Entry(self,
              bg="pink",
              fg="blue",
              width=15,
              textvariable=self.acctNo,
              exportselection=0).grid(row=1,
                                      column=1,
                                      sticky=W + N + S + E,
                                      pady=10,
                                      padx=5)

        Button(self, text="continue", command=CheckAcctNo).grid()

    def strAmnt(self, amnt):
        #function used to convert amounts(in digits) to strings having a comma
        #separated value of three's
        n = str(int(amnt))
        sAmnt = ""
        try:
            for i in range(-1, -(len(n) + 1), -1):
                sAmnt += n[i]
                if i % -3 == 0 and n[i - 1]:
                    sAmnt += ","
        except IndexError:
            pass
        return sAmnt[::-1]

    def Result(self, message, result):
        if result:
            amnt = self.strAmnt(result[1])
            messagebox.showinfo(
                "SUCCESS", "{} Of Money Was Successful.\
                                \nYour New Acct. Balance Is  #{}".format(
                    message, amnt))
        else:
            messagebox.showinfo(
                "FAIL", "{} Of Money Was Not Successful.".format(message))
        self.UserOption()

    def ChangePin(self):
        """change acct's log-in pin"""
        def checkNewPin():
            #confirms if new pin is valid(4-digit)
            try:
                int(self.new_pin.get())
                if not len(self.new_pin.get()) == 4:
                    messagebox.showwarning("ERROR",
                                           "pin must be four digits...")
                    return
            except ValueError:
                messagebox.showwarning("ERROR",
                                       "pin can only be in integers !!..")
                return

            if int(self.new_pin.get()) < 0:
                messagebox.showinfo("Error",
                                    "Pin should not be a negative number.!!")
                return
            acct = BankAcct(self.k)
            result = acct.ChangePin(int(self.new_pin.get()), self.name.get())
            del acct
            if result:
                messagebox.showinfo(
                    "SUCCESS", "Your Pin Has Been Changed Successfully.\
                                    \nExiting Now To Save Changes....")
                time.sleep(2)
                self.quit()
            else:
                messagebox.showerror("ERROR",
                                     "Change Of Pin Was Not Successful")

        if self.k == 1234:
            userDesign(master, self)
            mainMenu(master, self)
        else:
            self.User("CHANGE PIN")
        self.new_pin = StringVar()
        Label(self,
              text="Input New Pin :",
              fg="white",
              bg="blue",
              width=10,
              justify=LEFT).grid(sticky=E + S + N + W, pady=10, padx=5)
        Entry(self,
              bg="pink",
              fg="blue",
              width=15,
              textvariable=self.new_pin,
              exportselection=0).grid(row=1,
                                      column=1,
                                      sticky=W + N + S + E,
                                      pady=10,
                                      padx=5)

        Button(self, text="change pin", command=checkNewPin).grid()

    def DelAccount(self):
        self.User("DELETE ACCOUNT")
        if messagebox.askyesno(
                "DELETE ACCOUNT",
                "Are You Sure You Want To Delete Your Account ?"):
            acct = BankAcct(self.k)
            result = acct.DelAcct(self.name.get())
            del acct
            if result:
                messagebox.showinfo(
                    "SUCCESS", "Account Was Deleted Successfully.\
                                    \nExiting Now...")
                self.quit()
            else:
                messagebox.showinfo(
                    "FAILURE", "Account Was Not Deleted Successfully.\
                                    \nExiting Now...")
                self.quit()

    def Cancel(self):
        if messagebox.askyesno("QUIT", "Do You Really Want To Exit ?"):
            messagebox.showinfo("EXITING", "Thanks For Banking With Us.")
            master.quit()

    def Exit(self):
        if messagebox.askyesno("QUIT", "Do You Really Want To Exit ?"):
            self.master.quit()

    def AdminStart(self):
        """start of Admin-Related Activities"""
        def toggle():
            self.e1.configure(
                show="") if self.cVar.get() == 1 else self.e1.configure(
                    show="*")

        adminDesign(master, self)
        mainMenu(master, self)

        self.adminPin = StringVar()
        Label(self,
              text="Admin Pin :",
              fg="white",
              bg="blue",
              width=10,
              justify=LEFT).grid(sticky=E + S + N + W, pady=5, padx=5)
        self.e1 = Entry(self,
                        bg="pink",
                        fg="blue",
                        width=15,
                        textvariable=self.adminPin,
                        exportselection=0,
                        show="*")
        self.e1.grid(row=1,
                     column=1,
                     columnspan=5,
                     sticky=W + N + S + E,
                     pady=5,
                     padx=5)

        self.cVar = IntVar()
        Checkbutton(self,
                    text="show pin",
                    variable=self.cVar,
                    command=toggle,
                    bg="blue",
                    activebackground="blue").grid(sticky=N + W + S + E,
                                                  column=1)
        Button(self, text="Log-In", command=self.AdminPinCheck).grid()

    def AdminPinCheck(self):
        """checks if admin-pin is valid,if valid,proceed and if not,exit back
        to main menu
        """

        try:
            int(self.adminPin.get())
        except ValueError:
            messagebox.showerror("ERROR", "Please Type A Valid Pin...")
            return
        pin = int(self.adminPin.get())
        if len(str(pin)) == 4:
            acct = Admin(pin)
            if acct.CheckPin():
                self.adminPin = pin
                self.AdminOption()
            else:
                messagebox.showerror(
                    "INCORRECT PIN", "Invalid Admin Pin,Exiting Admin Mode !!")
                self.destroy()
                self.main()
        else:
            messagebox.showerror("INCORRECT PIN",
                                 "Invalid Amin Pin,Exiting Admin Mode !!")
            self.destroy()
            self.main()

    def Admin(self):
        adminDesign(master, self)
        adminMenu(master, self)

    def AdminOption(self):
        """Admin's  main-menu options"""

        self.Admin()
        Button(self,
               text="Deposit Cash In ATM",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.AdminDeposit).grid(columnspan=100, pady=6)
        Button(self,
               text="Check Balance In ATM",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.AdminBalance).grid(columnspan=100, pady=6)
        Button(self,
               text="Register New User",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.register_new_user).grid(columnspan=100, pady=6)
        Button(self,
               text="Users' Info",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.usersInfo).grid(columnspan=100, pady=6)
        Button(self,
               text="View All Users' Cash",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.view_all_cash).grid(columnspan=100, pady=6)
        Button(self,
               text="Delete User Account",
               bg="pink",
               fg="blue",
               width=40,
               height=2,
               activeforeground="red",
               command=self.delete_user_account).grid(columnspan=100, pady=6)

    def AdminBalance(self):
        """checks balance in atm system"""

        self.Admin()
        acct = Admin(self.adminPin)
        balance = acct.GetBalance()
        del acct
        balance = self.strAmnt(balance)
        var = "Balance In ATM Is  #{}".format(balance)
        messagebox.showinfo("BALANCE", var)
        messagebox.showinfo("EXIT", "Exiting Admin Mode...")
        self.destroy()
        self.main()

    def AdminDeposit(self):
        """Deposit Funds into atm"""
        def dep():
            try:
                amnt = int(self.amnt.get())
                if not amnt % 1000 == 0:
                    messagebox.showinfo("Error",
                                        "Please Type In A Valid Amount!!.")
                    return
                if amnt < 0:
                    messagebox.showinfo(
                        "Error", "Amount shouldn't be a negative number.!!")
                    return
            except ValueError:
                messagebox.showwarning("ERROR", "Amount Should Be In Integers")
                return

            acct = Admin(self.adminPin)
            result = acct.Deposit(amnt)
            del acct
            balance = result[1]
            balance = self.strAmnt(balance)
            messagebox.showinfo(
                "SUCCESS", "Deposition Of Money In ATM Was Successful,\
                                \nTotal Cash In ATM is now  #{}.".format(
                    balance))
            messagebox.showinfo("EXIT", "Exiting Admin Mode...")
            self.destroy()
            self.main()

        self.Admin()
        self.amnt = StringVar()

        Label(self,
              text="Amount Can Only be In Multiples Of Thousands...",
              fg="white",
              bg="blue",
              justify=LEFT).grid(columnspan=50,
                                 sticky=E + S + N + W,
                                 pady=10,
                                 padx=5)

        Label(self,
              text="Amount To Deposit In ATM :",
              fg="white",
              bg="blue",
              width=25,
              justify=LEFT).grid(row=2,
                                 column=0,
                                 sticky=E + S + N + W,
                                 pady=10,
                                 padx=5)
        Entry(self,
              bg="pink",
              fg="blue",
              width=15,
              textvariable=self.amnt,
              exportselection=0).grid(row=2,
                                      column=1,
                                      sticky=W + N + S + E,
                                      pady=10,
                                      padx=5)

        Button(self, text="Deposit", command=dep).grid()

    def register_new_user(self):
        """REGISTERS A NEW USER INTO THE BANK'S DATABASE WITH DEFAULT PASSWORD OF 1234"""
        def create():
            new_username = self.new_username.get()
            if new_username:
                result = Admin.register_user(new_username)
                if result:
                    messagebox.showinfo(
                        "SUCCESS",
                        "Creation Of New User-Account Was Successful..\
                                        \nExiting Admin Mode...")
                    self.destroy()
                    self.main()
                else:
                    messagebox.showinfo(
                        "SUCCESS",
                        "Creation Of New User-Account Was Successful..\
                                        \nExiting Admin Mode...")
                    self.destroy()
                    self.main()
            else:
                return

        self.Admin()
        if messagebox.askyesno(
                "CREATE NEW USER-ACCOUNT",
                "Are You Sure You Want To Create A new User Account ?"):
            self.new_username = StringVar()
            Label(self,
                  text="Log-In Name Is Case-Sensitive",
                  fg="white",
                  bg="blue",
                  justify=LEFT).grid(columnspan=50,
                                     sticky=E + S + N + W,
                                     padx=5)

            Label(self,
                  text="New Account's Log-in Name :",
                  fg="white",
                  bg="blue",
                  width=25,
                  justify=LEFT).grid(row=2,
                                     column=0,
                                     sticky=E + S + N + W,
                                     pady=10,
                                     padx=5)
            Entry(self,
                  bg="pink",
                  fg="blue",
                  width=15,
                  textvariable=self.new_username,
                  exportselection=0).grid(row=2,
                                          column=1,
                                          sticky=W + N + S + E,
                                          pady=10,
                                          padx=5)
            Button(self, text="Create", command=create).grid()

    def usersInfo(self):
        def done():
            messagebox.showinfo("DONE", "Exiting Admin Mode...")
            self.destroy()
            self.main()

        self.Admin()
        acct = Admin(self.adminPin)
        database = acct.UserInfo()
        del acct

        self.text = ScrolledText(self,
                                 width=44,
                                 borderwidth=10,
                                 relief=SUNKEN,
                                 height=16,
                                 bg="pink",
                                 fg="blue")
        self.text.grid(pady=5)
        Button(self,
               text="OK",
               command=done,
               width=52,
               borderwidth=5,
               relief=RAISED).grid()

        headings = "s/n | Acct. Name   | Acct. No.| Acct. Bal(#)\n"
        dots = "----|--------------|----------|-------------\n"
        self.text.insert(1.0, headings)
        self.text.insert(2.0, dots)

        index = 1
        text_index = 3.0
        for key, value in database.items():
            if value[0] != "admin":
                balance = self.strAmnt(value[2])
                if index > 9:
                    n = " " + str(index) + " | "
                else:
                    n = " " + str(index) + "  | "
                n += str(value[0]).ljust(13) + "| "
                n += str(key) + "   | " + balance.rjust(12) + "\n"
                self.text.insert(text_index, n)
                index += 1
                text_index += 1
        self.text.config(state=DISABLED)

    def view_all_cash(self):
        def done():
            messagebox.showinfo("DONE", "Exiting Admin Mode...")
            self.destroy()
            self.main()

        self.Admin()
        acct = Admin(self.adminPin)
        database = acct.UserInfo()
        del acct

        self.text = ScrolledText(self,
                                 width=44,
                                 borderwidth=10,
                                 relief=SUNKEN,
                                 height=16,
                                 bg="pink",
                                 fg="blue")
        self.text.grid(pady=5)
        Button(self,
               text="OK",
               command=done,
               width=52,
               borderwidth=5,
               relief=RAISED).grid()

        total = 0
        for key, value in database.items():
            if value[0] != "admin":
                total += value[2]
        total = self.strAmnt(total)
        word = "Total Cash Of All users Is  #{}".format(total)
        self.text.insert(1.0, word)
        self.text.config(state=DISABLED)

    def delete_user_account(self):
        def proceed2():
            try:
                self.account_number = int(self.account_number.get())
            except ValueError:
                messagebox.showerror("ERROR",
                                     "Account Number Can Only Be In Digits!!")
                return
            acct = Admin(self.adminPin)
            result = acct.delete_user_account(self.account_number,
                                              self.account_name)
            del acct
            if result:
                messagebox.showinfo(
                    "SUCCESS", "Account Was Deleted Successfully.\
                                    \nExiting Admin Mode...")
                self.destroy()
                self.main()
            else:
                messagebox.showinfo(
                    "FAILURE", "Account Was Not Deleted Successfully.\
                                    \nExiting Admin Mode...")
                self.destroy()
                self.main()

        def proceed():
            self.Admin()
            self.account_number = StringVar()
            self.account_name = self.account_name.get()
            Label(self,
                  text="User's Account No. :",
                  fg="white",
                  bg="blue",
                  width=25,
                  justify=LEFT).grid(sticky=E + S + N + W, pady=10, padx=5)
            Entry(self,
                  bg="pink",
                  fg="blue",
                  width=15,
                  textvariable=self.account_number,
                  exportselection=0).grid(row=1,
                                          column=1,
                                          sticky=E + S + N + W,
                                          pady=10,
                                          padx=5)
            Button(self, text="Proceed", command=proceed2).grid()

        self.Admin()
        self.account_name = StringVar()

        Label(self,
              text="User's Account Name :",
              fg="white",
              bg="blue",
              width=25,
              justify=LEFT).grid(column=0,
                                 sticky=E + S + N + W,
                                 pady=10,
                                 padx=5)
        Entry(self,
              bg="pink",
              fg="blue",
              width=15,
              textvariable=self.account_name,
              exportselection=0).grid(row=1,
                                      column=1,
                                      sticky=E + S + N + W,
                                      pady=10,
                                      padx=5)
        Button(self, text="Continue", command=proceed).grid()
Ejemplo n.º 40
0
    work_sheet.merge_cells(start_row=start_rows + 3, start_column=2, end_row=start_rows + 8, end_column=2)
    work_sheet.cell(start_rows, 1, value=org)
    work_sheet.merge_cells(start_row=start_rows, start_column=1, end_row=start_rows + 12, end_column=1)


def main():
    logs.grid(row=0, column=0, rowspan=6)

    Button(root, text='选择文件夹', command=select_folder).grid(row=0, column=1)
    Entry(root, textvariable=pathFolder).grid(row=1, column=1)
    # Button(root, text='选择模板文件', command=select_file).grid(row=1, column=1)
    # Entry(root, textvariable=pathFile).grid(row=1, column=2)
    # Label(root, text='汇总文件名称', ).grid(row=2, column=1)
    # Entry(root, textvariable=target_file).grid(row=2, column=2)

    Button(root, text='合并文件', command=begin_copy_work).grid(row=3, column=1, columnspan=1)
    Button(root, text='合并汇总文件', command=begin_merge_work).grid(row=4, column=1, columnspan=1)
    Button(root, text='开始', command=begin_work).grid(row=5, column=1, columnspan=1)
    # Label(root, text='需要另存为xlsx格式\n需按摘取字段排序好\n空行过多需先清除内容后删除', ).grid(row=5, column=2, columnspan=1)
    root.mainloop()


root = Tk()
root.wm_title('督导得分汇总')
logs = ScrolledText(root, width=40, height=30)
pathFolder = StringVar()
pathFile = StringVar()
target_file = StringVar()
if __name__ == '__main__':
    main()
Ejemplo n.º 41
0
    def create_widgets(self):
        toplevel_frame = ttk.Frame(self, padding='0.1i')

        (self.toolslist, selected_item) = self.get_tools_list()
        self.tools_frame = ttk.LabelFrame(toplevel_frame,
                                          text="{} Available Tools".format(
                                              len(self.toolslist)),
                                          padding='0.1i')
        self.toolnames = tk.StringVar(value=self.toolslist)
        self.tools_listbox = tk.Listbox(self.tools_frame,
                                        height=22,
                                        listvariable=self.toolnames)
        self.tools_listbox.bind("<<ListboxSelect>>", self.update_tool_help)
        self.tools_listbox.grid(row=0, column=0, sticky=tk.NSEW)
        self.tools_listbox.columnconfigure(0, weight=10)
        self.tools_listbox.rowconfigure(0, weight=1)
        s = ttk.Scrollbar(self.tools_frame,
                          orient=tk.VERTICAL,
                          command=self.tools_listbox.yview)
        s.grid(row=0, column=1, sticky=(tk.N, tk.S))
        self.tools_listbox['yscrollcommand'] = s.set
        self.tools_frame.grid(row=0, column=0, sticky=tk.NSEW)
        self.tools_frame.columnconfigure(0, weight=10)
        self.tools_frame.columnconfigure(1, weight=1)
        self.tools_frame.rowconfigure(0, weight=1)

        overall_frame = ttk.Frame(toplevel_frame, padding='0.1i')

        # json_str = '{"default_value": null, "description": "Directory containing data files.", "flags": ["--wd"], "name": "Working Directory", "optional": true, "parameter_type": "Directory"}'
        # self.wd = FileSelector(json_str, overall_frame)
        # self.wd.grid(row=0, column=0, sticky=tk.NSEW)

        current_tool_frame = ttk.Frame(overall_frame, padding='0.1i')
        self.current_tool_lbl = ttk.Label(
            current_tool_frame,
            text="Current Tool: {}".format(self.tool_name),
            justify=tk.LEFT)  # , font=("Helvetica", 12, "bold")
        self.current_tool_lbl.grid(row=0, column=0, sticky=tk.W)
        self.view_code_button = ttk.Button(current_tool_frame,
                                           text="View Code",
                                           width=12,
                                           command=self.view_code)
        self.view_code_button.grid(row=0, column=1, sticky=tk.E)
        current_tool_frame.grid(row=1, column=0, sticky=tk.NSEW)
        current_tool_frame.columnconfigure(0, weight=1)
        current_tool_frame.columnconfigure(1, weight=1)

        tool_args_frame = ttk.Frame(overall_frame, padding='0.0i')
        self.tool_args_frame = ttk.Frame(overall_frame, padding='0.0i')
        self.tool_args_frame.grid(row=2, column=0, sticky=tk.NSEW)
        self.tool_args_frame.columnconfigure(0, weight=1)

        # args_frame = ttk.Frame(overall_frame, padding='0.1i')
        # self.args_label = ttk.Label(args_frame, text="Tool Arguments:", justify=tk.LEFT)
        # self.args_label.grid(row=0, column=0, sticky=tk.W)
        # args_frame2 = ttk.Frame(args_frame, padding='0.0i')
        # self.args_value = tk.StringVar()
        # self.args_text = ttk.Entry(args_frame2, width=45, justify=tk.LEFT, textvariable=self.args_value)
        # self.args_text.grid(row=0, column=0, sticky=tk.NSEW)
        # self.args_text.columnconfigure(0, weight=1)
        # self.clearButton = ttk.Button(args_frame2, text="Clear", width=4, command=self.clear_args_box)
        # self.clearButton.pack(pady=10, padx=10)
        # self.clearButton.grid(row=0, column=1, sticky=tk.E)
        # self.clearButton.columnconfigure(0, weight=1)
        # args_frame2.grid(row=1, column=0, sticky=tk.NSEW)
        # args_frame2.columnconfigure(0, weight=10)
        # args_frame2.columnconfigure(1, weight=1)
        # args_frame.grid(row=2, column=0, sticky=tk.NSEW)
        # args_frame.columnconfigure(0, weight=1)

        # # Add the bindings
        # if _platform == "darwin":
        #     self.args_text.bind("<Command-Key-a>", self.args_select_all)
        # else:
        #     self.args_text.bind("<Control-Key-a>", self.args_select_all)

        buttonsFrame = ttk.Frame(overall_frame, padding='0.1i')
        self.run_button = ttk.Button(buttonsFrame,
                                     text="Run",
                                     width=8,
                                     command=self.run_tool)
        # self.run_button.pack(pady=10, padx=10)
        self.run_button.grid(row=0, column=0)
        self.quitButton = ttk.Button(buttonsFrame,
                                     text="Cancel",
                                     width=8,
                                     command=self.cancel_operation)
        self.quitButton.grid(row=0, column=1)
        buttonsFrame.grid(row=3, column=0, sticky=tk.E)

        output_frame = ttk.Frame(overall_frame, padding='0.1i')
        outlabel = ttk.Label(output_frame, text="Output:", justify=tk.LEFT)
        outlabel.grid(row=0, column=0, sticky=tk.NW)
        k = wbt.tool_help(self.tool_name)
        self.out_text = ScrolledText(output_frame,
                                     width=63,
                                     height=10,
                                     wrap=tk.NONE,
                                     padx=7,
                                     pady=7)
        self.out_text.insert(tk.END, k)
        self.out_text.grid(row=1, column=0, sticky=tk.NSEW)
        self.out_text.columnconfigure(0, weight=1)
        output_frame.grid(row=4, column=0, sticky=tk.NSEW)
        output_frame.columnconfigure(0, weight=1)

        # Add the binding
        if _platform == "darwin":
            self.out_text.bind("<Command-Key-a>", self.select_all)
            # self.out_text.bind("<Command-Key-A>", self.select_all)
        else:
            self.out_text.bind("<Control-Key-a>", self.select_all)

        progress_frame = ttk.Frame(overall_frame, padding='0.1i')
        self.progress_label = ttk.Label(progress_frame,
                                        text="Progress:",
                                        justify=tk.LEFT)
        self.progress_label.grid(row=0, column=0, sticky=tk.E, padx=5)
        self.progress_var = tk.DoubleVar()
        self.progress = ttk.Progressbar(progress_frame,
                                        orient="horizontal",
                                        variable=self.progress_var,
                                        length=200,
                                        maximum=100)
        self.progress.grid(row=0, column=1, sticky=tk.E)
        progress_frame.grid(row=5, column=0, sticky=tk.E)

        overall_frame.grid(row=0, column=1, sticky=tk.NSEW)

        overall_frame.columnconfigure(0, weight=1)
        toplevel_frame.columnconfigure(0, weight=1)
        toplevel_frame.columnconfigure(1, weight=4)
        # self.pack(fill=tk.BOTH, expand=1)
        # toplevel_frame.columnconfigure(0, weight=1)
        # toplevel_frame.rowconfigure(0, weight=1)

        toplevel_frame.grid(row=0, column=0, sticky=tk.NSEW)

        # Select the appropriate tool, if specified, otherwise the first tool
        self.tools_listbox.select_set(selected_item)
        self.tools_listbox.event_generate("<<ListboxSelect>>")
        self.tools_listbox.see(selected_item)

        menubar = tk.Menu(self)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Set Working Directory",
                             command=self.set_directory)
        filemenu.add_command(label="Locate WhiteboxTools exe",
                             command=self.select_exe)
        filemenu.add_command(label="Refresh Tools", command=self.refresh_tools)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.quit)
        menubar.add_cascade(label="File", menu=filemenu)

        editmenu = tk.Menu(menubar, tearoff=0)
        editmenu.add_command(
            label="Cut",
            command=lambda: self.focus_get().event_generate("<<Cut>>"))
        editmenu.add_command(
            label="Copy",
            command=lambda: self.focus_get().event_generate("<<Copy>>"))
        editmenu.add_command(
            label="Paste",
            command=lambda: self.focus_get().event_generate("<<Paste>>"))

        menubar.add_cascade(label="Edit ", menu=editmenu)

        helpmenu = tk.Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", command=self.help)

        helpmenu.add_command(label="License", command=self.license)

        menubar.add_cascade(label="Help ", menu=helpmenu)

        self.master.config(menu=menubar)
Ejemplo n.º 42
0
#Creation of ui elements
# Left
uidLabel = Label(leftBox, text='UID')
uidEntry = Entry(leftBox, width=100)

subjectLabel = Label(leftBox, text='Subject')
subjectEntry = Entry(leftBox, width=100)

fromLabel = Label(leftBox, text='From')
fromEntry = Entry(leftBox, width=100)

timeEmailLabel = Label(leftBox, text='Time')
timeEmailEntry = Entry(leftBox, width=100)

bodyLabel = Label(leftBox, text='Body')
bodyScrolledText = ScrolledText(leftBox, height=30, width=100, undo=True)
# Right
parseButton = Button(rightBox, text="Parse", width=25, command=lambda: start_process())

titleLabel = Label(rightBox, text='Title')
titleEntry = Entry(rightBox, width=50)

groupLabel = Label(rightBox, text='Group')
groupEntry = Entry(rightBox, width=50)

locationLabel = Label(rightBox, text='Location')
locationEntry = Entry(rightBox, width=50)

dateLabel = Label(rightBox, text='Date')
dateEntry = Entry(rightBox, width=50)
from tkinter import *
try:
    from tkinter.scrolledtext import ScrolledText

    def say_message():
        import pyttsx3
        engine = pyttsx3.init()
        engine.say(message.get())
        engine.runAndWait()

    top = Tk()
    top.title("读出文字")
    top.geometry('500x30')
    label = Label(text='请输入文字:').pack(side=LEFT)
    c = ScrolledText()
    message = Entry()
    message.pack(side=LEFT, expand=True, fill=X)
    Button(text='朗读', command=say_message).pack(side=RIGHT)
    mainloop()
except:
    pass
Ejemplo n.º 44
0
import tkinter
from tkinter import *
from tkinter.scrolledtext import ScrolledText
import tkinter.filedialog as filedialog
import tkinter.messagebox as messagebox

root = tkinter.Tk(className=" Just another Text Editor")
textPad = ScrolledText(root, width=100, height=80)

# create a menu & define functions for each menu item


def open_command():
    file = filedialog.askopenfile(parent=root,
                                  mode='rb',
                                  title='Select a file')
    if file is not None:
        contents = file.read()
        textPad.insert('1.0', contents)
        file.close()


def save_command(self):
    file = filedialog.asksaveasfile(mode='w')
    if file is not None:
        # slice off the last character from get, as an extra return is added
        data = self.textPad.get('1.0', END + '-1c')
        file.write(data)
        file.close()

Ejemplo n.º 45
0
    def __init__(self):
        self.window = tk.Tk()
        dr.get_global_param()
        self.targetDB_path = dr.targetDB

        # ================================================================================ #
        # ============================== WIDGET BUILDING ================================= #
        # ================================================================================ #

        self.title = tk.Label(self.window,
                              height=2,
                              text='TargetDB',
                              bg='#00cc99',
                              font='Helvetica 16 bold')

        self.mode = tk.StringVar()

        self.mode.set('list')
        self.mode_label = tk.Label(self.window,
                                   text='Mode',
                                   relief="raised",
                                   bg='#e6e6e6')
        self.mode_single = tk.Radiobutton(self.window,
                                          text="Single mode",
                                          variable=self.mode,
                                          value='single')
        self.mode_list = tk.Radiobutton(self.window,
                                        text="List mode",
                                        variable=self.mode,
                                        value='list')
        self.mode_spider = tk.Radiobutton(self.window,
                                          text="Spider plot only",
                                          variable=self.mode,
                                          value='spider')

        self.target_input_label = tk.Label(self.window,
                                           text='Targets list',
                                           relief="raised",
                                           bg='#e6e6e6')
        self.message_target = tk.StringVar()
        self.message_target.set(
            """Please enter the list of targets. You can either enter a list of gene names directly from excel or a list of comma separated values (eg. "DYRK1A,CYP3D6")"""
        )
        self.target_message = tk.Message(self.window,
                                         textvariable=self.message_target,
                                         justify="center")
        self.input_text = ScrolledText(self.window)

        self.settings_button = tk.Button(self.window,
                                         text='Settings',
                                         bg='#b7b7b7',
                                         command=self.get_settings,
                                         font='Helvetica 10 bold')
        self.go_button = tk.Button(self.window,
                                   text='Start',
                                   bg='#00cc99',
                                   command=self.launch,
                                   font='Helvetica 12 bold')

        self.close = tk.Button(self.window,
                               text='Exit',
                               fg='red',
                               command=self.window.destroy,
                               font='Helvetica 12 bold')

        # ================================================================================ #
        # =========================== GRID CONSTRUCTION ================================== #
        # ================================================================================ #

        self.title.grid(row=0, column=0, columnspan=4, sticky="ew")
        self.mode_label.grid(row=1, column=0, ipadx=10, pady=10, sticky="w")
        self.mode_single.grid(row=1, column=1, pady=10)
        self.mode_list.grid(row=1, column=2, pady=10)
        self.mode_spider.grid(row=1, column=3, pady=10)

        self.target_input_label.grid(row=3, column=0, ipadx=10, sticky="wne")
        self.target_message.grid(row=4, column=0, rowspan=2, sticky='nw')
        self.settings_button.grid(row=6, column=0, sticky='nwe', ipadx=10)
        self.input_text.grid(row=3, column=1, columnspan=3, rowspan=4)

        self.go_button.grid(row=8,
                            column=1,
                            columnspan=2,
                            sticky="ew",
                            pady=10,
                            padx=10)
        self.close.grid(row=8,
                        column=3,
                        sticky='ew',
                        ipadx=20,
                        pady=10,
                        padx=10)

        # ================================================================================ #
        # =========================== LAUNCHING THE APP ================================== #
        # ================================================================================ #
        self.window.mainloop()
Ejemplo n.º 46
0
class App(tk.Frame):  # pylint: disable=too-many-ancestors
    """Configures the main window

    Attributes:

        parent: The parent class, which in this case is an instance of Tk

        width: Minimum possible window width
        height: Minimum possible window height

        note: The notebook interface
        tab1: General tab
        tab2: Cipher tab

        output_area: Outputs diagnostic results of encryption
        initial_value: Initial value of the encrypt/decrypt dropdown menu

    """
    def __init__(self, parent: tk.Tk, **kw: object) -> None:
        # Suggested in the Frame docs
        # Inherit the properties of the parent class
        super().__init__(**kw)

        # Configure additional properties
        self.parent = parent

        # Minimum Dimensions are in pixels
        self.width = 400
        self.height = 200

        # Create the tabs
        self.note = ttk.Notebook(self.parent)
        self.tab1 = ttk.Frame(self.note)
        self.tab2 = ttk.Frame(self.note)

        # Assign tab titles
        self.note.add(self.tab1, text="General")
        self.note.add(self.tab2, text="Settings")

        self.note.pack(fill=tk.BOTH, expand=True)

        # Allows user to input plaintext and receive ciphertext
        # The following properties are not in the "add widgets" method
        # This is since it needs to be accessed by other methods
        self.output_area = ScrolledText(self.tab1, wrap=tk.WORD)

        # Choose between encrypt and decrypt and which cipher
        # Based off http://effbot.org/tkinterbook/optionmenu.htm
        self.initial_crypt = tk.StringVar(self.tab1)
        self.initial_cipher = tk.StringVar(self.tab2)

        # Password Input
        self.password_entry = ttk.Entry(self.tab1, show="*")
        self.password_entry.grid(
            row=0, column=1, columnspan=3, sticky="WE"
        )  # Seperate grid prevents password_entry from being None

        # Methods to arrange the app
        self.configure_app()
        self.add_widgets_tab1()
        self.add_widgets_tab2()

    def configure_app(self) -> None:
        """Sets up properties of the main window"""
        self.parent.title("kintercrypt")
        self.parent.geometry(f"{self.width + 100}x{self.height + 100}"
                             )  # 100x100 bigger than minimum size
        self.parent.minsize(self.width, self.height)

        # Allows the window to be resizable
        # The range denotes the number of columns and rows
        for axis in range(2):
            self.tab1.rowconfigure(axis, weight=1)
            self.tab1.columnconfigure(axis, weight=1)

            self.tab2.rowconfigure(axis, weight=1)
            self.tab2.columnconfigure(axis, weight=1)

        self.tab1.grid_columnconfigure(
            0, minsize=110)  # Prevents buttons from being squashed
        self.tab1.grid_rowconfigure(
            0, minsize=40)  # Prevents password area from being squashed

    def add_widgets_tab1(self) -> None:
        """Sets up widgets for the general tab"""

        # Password Label
        ttk.Label(self.tab1, text="Password:"******"Start",
                   command=self.start_cipher).grid(row=0,
                                                   column=0,
                                                   pady=10,
                                                   sticky='new')

        self.initial_crypt.set("Encrypt")
        # Encrypt twice since otherwise, decypt is the only option
        option_menu = ttk.OptionMenu(button_area, self.initial_crypt,
                                     "Encrypt", "Encrypt", "Decrypt")
        option_menu.grid(
            row=0, column=1, sticky='new',
            pady=10)  # Separate grid so that the widget isn't assigned as None

        ttk.Label(self.tab1, text="Enter text:").grid(row=1, column=0)
        self.output_area.grid(row=1, column=1, sticky="WE")

    def add_widgets_tab2(self) -> None:
        """Sets up widgets for the cipher tab"""
        ttk.Label(self.tab2, text="Choose Cipher:").grid(row=0, column=0)
        self.initial_cipher.set("XOR")

        option_menu = ttk.OptionMenu(self.tab2, self.initial_cipher, "XOR",
                                     "XOR")
        option_menu.grid(
            row=0, column=1
        )  # Separate grid so that the widget isn't assigned as None

    def start_cipher(self) -> None:
        """Performs various checks before encryption begins

        After performing the checks, it retrieves the encrypted/decrypted text
        It then writes it to a new file

        """

        # Text inputted by the user
        # First parameter indicates to read from the first line
        # Second parameter removes the last character, which is an undesired newline
        user_text = self.output_area.get("1.0", 'end-1c')

        # Various errors that can occur
        if not user_text:
            showerror('kintercrypt', "No text entered!")
            return

        user_password = self.password_entry.get()

        if not user_password:
            showerror('kintercrypt', "Password not set!")
            return

        crypt_choice = (self.initial_crypt.get()
                        )  # Whether the user wants to encrypt or decrypt

        # User's choice of encryption algorithm
        cipher_choice = (self.initial_cipher.get())

        # Determines the ciphertext/plaintext
        final_result = main_cipher(user_text, user_password, cipher_choice,
                                   crypt_choice)

        # Removes the user's input
        self.output_area.delete('1.0', tk.END)

        # Inserts the encrypted/decrypted output
        self.output_area.insert(tk.INSERT, final_result)
Ejemplo n.º 47
0
class WbRunner(tk.Frame):
    def __init__(self, tool_name=None, master=None):
        if platform.system() == 'Windows':
            self.ext = '.exe'
        else:
            self.ext = ''

        exe_name = "whitebox_tools{}".format(self.ext)

        self.exe_path = path.dirname(path.abspath(__file__))
        os.chdir(self.exe_path)
        for filename in glob.iglob('**/*', recursive=True):
            if filename.endswith(exe_name):
                self.exe_path = path.dirname(path.abspath(filename))
                break

        wbt.set_whitebox_dir(self.exe_path)

        ttk.Frame.__init__(self, master)
        self.script_dir = os.path.dirname(os.path.realpath(__file__))
        self.grid()
        self.tool_name = tool_name
        self.master.title("WhiteboxTools Runner")
        # widthpixels = 800
        # heightpixels = 600
        # self.master.geometry('{}x{}'.format(widthpixels, heightpixels))
        # self.master.resizable(0, 0)
        # self.master.lift()
        if _platform == "darwin":
            os.system(
                '''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' '''
            )
        self.create_widgets()
        self.working_dir = str(Path.home())

    def create_widgets(self):
        toplevel_frame = ttk.Frame(self, padding='0.1i')

        (self.toolslist, selected_item) = self.get_tools_list()
        self.tools_frame = ttk.LabelFrame(toplevel_frame,
                                          text="{} Available Tools".format(
                                              len(self.toolslist)),
                                          padding='0.1i')
        self.toolnames = tk.StringVar(value=self.toolslist)
        self.tools_listbox = tk.Listbox(self.tools_frame,
                                        height=22,
                                        listvariable=self.toolnames)
        self.tools_listbox.bind("<<ListboxSelect>>", self.update_tool_help)
        self.tools_listbox.grid(row=0, column=0, sticky=tk.NSEW)
        self.tools_listbox.columnconfigure(0, weight=10)
        self.tools_listbox.rowconfigure(0, weight=1)
        s = ttk.Scrollbar(self.tools_frame,
                          orient=tk.VERTICAL,
                          command=self.tools_listbox.yview)
        s.grid(row=0, column=1, sticky=(tk.N, tk.S))
        self.tools_listbox['yscrollcommand'] = s.set
        self.tools_frame.grid(row=0, column=0, sticky=tk.NSEW)
        self.tools_frame.columnconfigure(0, weight=10)
        self.tools_frame.columnconfigure(1, weight=1)
        self.tools_frame.rowconfigure(0, weight=1)

        overall_frame = ttk.Frame(toplevel_frame, padding='0.1i')

        # json_str = '{"default_value": null, "description": "Directory containing data files.", "flags": ["--wd"], "name": "Working Directory", "optional": true, "parameter_type": "Directory"}'
        # self.wd = FileSelector(json_str, overall_frame)
        # self.wd.grid(row=0, column=0, sticky=tk.NSEW)

        current_tool_frame = ttk.Frame(overall_frame, padding='0.1i')
        self.current_tool_lbl = ttk.Label(
            current_tool_frame,
            text="Current Tool: {}".format(self.tool_name),
            justify=tk.LEFT)  # , font=("Helvetica", 12, "bold")
        self.current_tool_lbl.grid(row=0, column=0, sticky=tk.W)
        self.view_code_button = ttk.Button(current_tool_frame,
                                           text="View Code",
                                           width=12,
                                           command=self.view_code)
        self.view_code_button.grid(row=0, column=1, sticky=tk.E)
        current_tool_frame.grid(row=1, column=0, sticky=tk.NSEW)
        current_tool_frame.columnconfigure(0, weight=1)
        current_tool_frame.columnconfigure(1, weight=1)

        tool_args_frame = ttk.Frame(overall_frame, padding='0.0i')
        self.tool_args_frame = ttk.Frame(overall_frame, padding='0.0i')
        self.tool_args_frame.grid(row=2, column=0, sticky=tk.NSEW)
        self.tool_args_frame.columnconfigure(0, weight=1)

        # args_frame = ttk.Frame(overall_frame, padding='0.1i')
        # self.args_label = ttk.Label(args_frame, text="Tool Arguments:", justify=tk.LEFT)
        # self.args_label.grid(row=0, column=0, sticky=tk.W)
        # args_frame2 = ttk.Frame(args_frame, padding='0.0i')
        # self.args_value = tk.StringVar()
        # self.args_text = ttk.Entry(args_frame2, width=45, justify=tk.LEFT, textvariable=self.args_value)
        # self.args_text.grid(row=0, column=0, sticky=tk.NSEW)
        # self.args_text.columnconfigure(0, weight=1)
        # self.clearButton = ttk.Button(args_frame2, text="Clear", width=4, command=self.clear_args_box)
        # self.clearButton.pack(pady=10, padx=10)
        # self.clearButton.grid(row=0, column=1, sticky=tk.E)
        # self.clearButton.columnconfigure(0, weight=1)
        # args_frame2.grid(row=1, column=0, sticky=tk.NSEW)
        # args_frame2.columnconfigure(0, weight=10)
        # args_frame2.columnconfigure(1, weight=1)
        # args_frame.grid(row=2, column=0, sticky=tk.NSEW)
        # args_frame.columnconfigure(0, weight=1)

        # # Add the bindings
        # if _platform == "darwin":
        #     self.args_text.bind("<Command-Key-a>", self.args_select_all)
        # else:
        #     self.args_text.bind("<Control-Key-a>", self.args_select_all)

        buttonsFrame = ttk.Frame(overall_frame, padding='0.1i')
        self.run_button = ttk.Button(buttonsFrame,
                                     text="Run",
                                     width=8,
                                     command=self.run_tool)
        # self.run_button.pack(pady=10, padx=10)
        self.run_button.grid(row=0, column=0)
        self.quitButton = ttk.Button(buttonsFrame,
                                     text="Cancel",
                                     width=8,
                                     command=self.cancel_operation)
        self.quitButton.grid(row=0, column=1)
        buttonsFrame.grid(row=3, column=0, sticky=tk.E)

        output_frame = ttk.Frame(overall_frame, padding='0.1i')
        outlabel = ttk.Label(output_frame, text="Output:", justify=tk.LEFT)
        outlabel.grid(row=0, column=0, sticky=tk.NW)
        k = wbt.tool_help(self.tool_name)
        self.out_text = ScrolledText(output_frame,
                                     width=63,
                                     height=10,
                                     wrap=tk.NONE,
                                     padx=7,
                                     pady=7)
        self.out_text.insert(tk.END, k)
        self.out_text.grid(row=1, column=0, sticky=tk.NSEW)
        self.out_text.columnconfigure(0, weight=1)
        output_frame.grid(row=4, column=0, sticky=tk.NSEW)
        output_frame.columnconfigure(0, weight=1)

        # Add the binding
        if _platform == "darwin":
            self.out_text.bind("<Command-Key-a>", self.select_all)
            # self.out_text.bind("<Command-Key-A>", self.select_all)
        else:
            self.out_text.bind("<Control-Key-a>", self.select_all)

        progress_frame = ttk.Frame(overall_frame, padding='0.1i')
        self.progress_label = ttk.Label(progress_frame,
                                        text="Progress:",
                                        justify=tk.LEFT)
        self.progress_label.grid(row=0, column=0, sticky=tk.E, padx=5)
        self.progress_var = tk.DoubleVar()
        self.progress = ttk.Progressbar(progress_frame,
                                        orient="horizontal",
                                        variable=self.progress_var,
                                        length=200,
                                        maximum=100)
        self.progress.grid(row=0, column=1, sticky=tk.E)
        progress_frame.grid(row=5, column=0, sticky=tk.E)

        overall_frame.grid(row=0, column=1, sticky=tk.NSEW)

        overall_frame.columnconfigure(0, weight=1)
        toplevel_frame.columnconfigure(0, weight=1)
        toplevel_frame.columnconfigure(1, weight=4)
        # self.pack(fill=tk.BOTH, expand=1)
        # toplevel_frame.columnconfigure(0, weight=1)
        # toplevel_frame.rowconfigure(0, weight=1)

        toplevel_frame.grid(row=0, column=0, sticky=tk.NSEW)

        # Select the appropriate tool, if specified, otherwise the first tool
        self.tools_listbox.select_set(selected_item)
        self.tools_listbox.event_generate("<<ListboxSelect>>")
        self.tools_listbox.see(selected_item)

        menubar = tk.Menu(self)
        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Set Working Directory",
                             command=self.set_directory)
        filemenu.add_command(label="Locate WhiteboxTools exe",
                             command=self.select_exe)
        filemenu.add_command(label="Refresh Tools", command=self.refresh_tools)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.quit)
        menubar.add_cascade(label="File", menu=filemenu)

        editmenu = tk.Menu(menubar, tearoff=0)
        editmenu.add_command(
            label="Cut",
            command=lambda: self.focus_get().event_generate("<<Cut>>"))
        editmenu.add_command(
            label="Copy",
            command=lambda: self.focus_get().event_generate("<<Copy>>"))
        editmenu.add_command(
            label="Paste",
            command=lambda: self.focus_get().event_generate("<<Paste>>"))

        menubar.add_cascade(label="Edit ", menu=editmenu)

        helpmenu = tk.Menu(menubar, tearoff=0)
        helpmenu.add_command(label="About", command=self.help)

        helpmenu.add_command(label="License", command=self.license)

        menubar.add_cascade(label="Help ", menu=helpmenu)

        self.master.config(menu=menubar)

        # self.get_toolboxes()

    def help(self):
        self.print_to_output(wbt.version())

    def license(self):
        self.print_to_output(wbt.license())

    def set_directory(self):
        try:
            self.working_dir = filedialog.askdirectory(
                initialdir=self.exe_path)
            wbt.set_working_dir(self.working_dir)
        except:
            messagebox.showinfo(
                "Warning", "Could not find WhiteboxTools executable file.")

    def select_exe(self):
        try:
            filename = filedialog.askopenfilename(initialdir=self.exe_path)
            self.exe_path = path.dirname(path.abspath(filename))
            wbt.set_whitebox_dir(self.exe_path)
            self.refresh_tools()
        except:
            messagebox.showinfo(
                "Warning", "Could not find WhiteboxTools executable file.")

    def run_tool(self):
        # wd_str = self.wd.get_value()
        wbt.set_working_dir(self.working_dir)
        # args = shlex.split(self.args_value.get())

        args = []
        for widget in self.tool_args_frame.winfo_children():
            v = widget.get_value()
            if v:
                args.append(v)
            elif not widget.optional:
                messagebox.showinfo(
                    "Error", "Non-optional tool parameter not specified.")
                return

        self.print_line_to_output("")
        # self.print_line_to_output("Tool arguments:{}".format(args))
        # self.print_line_to_output("")
        # Run the tool and check the return value for an error
        if wbt.run_tool(self.tool_name, args, self.custom_callback) == 1:
            print("Error running {}".format(self.tool_name))

        else:
            self.run_button["text"] = "Run"
            self.progress_var.set(0)
            self.progress_label['text'] = "Progress:"
            self.progress.update_idletasks()

    def print_to_output(self, value):
        self.out_text.insert(tk.END, value)
        self.out_text.see(tk.END)

    def print_line_to_output(self, value):
        self.out_text.insert(tk.END, value + "\n")
        self.out_text.see(tk.END)

    def cancel_operation(self):
        wbt.cancel_op = True
        self.print_line_to_output("Cancelling operation...")
        self.progress.update_idletasks()

    def view_code(self):
        webbrowser.open_new_tab(wbt.view_code(self.tool_name).strip())

    def update_tool_help(self, event):
        selection = self.tools_listbox.curselection()
        self.tool_name = self.tools_listbox.get(selection[0])
        self.out_text.delete('1.0', tk.END)
        for widget in self.tool_args_frame.winfo_children():
            widget.destroy()

        k = wbt.tool_help(self.tool_name)
        self.print_to_output(k)

        j = json.loads(wbt.tool_parameters(self.tool_name))
        param_num = 0
        for p in j['parameters']:
            json_str = json.dumps(p,
                                  sort_keys=True,
                                  indent=2,
                                  separators=(',', ': '))
            pt = p['parameter_type']
            if 'ExistingFileOrFloat' in pt:
                ff = FileOrFloat(json_str, self, self.tool_args_frame)
                ff.grid(row=param_num, column=0, sticky=tk.NSEW)
                param_num = param_num + 1
            elif ('ExistingFile' in pt or 'NewFile' in pt
                  or 'Directory' in pt):
                fs = FileSelector(json_str, self, self.tool_args_frame)
                fs.grid(row=param_num, column=0, sticky=tk.NSEW)
                param_num = param_num + 1
            elif 'FileList' in pt:
                b = MultifileSelector(json_str, self, self.tool_args_frame)
                b.grid(row=param_num, column=0, sticky=tk.W)
                param_num = param_num + 1
            elif 'Boolean' in pt:
                b = BooleanInput(json_str, self.tool_args_frame)
                b.grid(row=param_num, column=0, sticky=tk.W)
                param_num = param_num + 1
            elif 'OptionList' in pt:
                b = OptionsInput(json_str, self.tool_args_frame)
                b.grid(row=param_num, column=0, sticky=tk.W)
                param_num = param_num + 1
            elif ('Float' in pt or 'Integer' in pt or 'String' in pt
                  or 'StringOrNumber' in pt or 'StringList' in pt
                  or 'VectorAttributeField' in pt):
                b = DataInput(json_str, self.tool_args_frame)
                b.grid(row=param_num, column=0, sticky=tk.NSEW)
                param_num = param_num + 1
            else:
                messagebox.showinfo(
                    "Error", "Unsupported parameter type: {}.".format(pt))

        self.update_args_box()
        self.out_text.see("%d.%d" % (1, 0))

    def update_args_box(self):
        s = ""
        self.current_tool_lbl['text'] = "Current Tool: {}".format(
            self.tool_name)
        # self.spacer['width'] = width=(35-len(self.tool_name))
        for item in wbt.tool_help(self.tool_name).splitlines():
            if item.startswith("-"):
                k = item.split(" ")
                if "--" in k[1]:
                    value = k[1].replace(",", "")
                else:
                    value = k[0].replace(",", "")

                if "flag" in item.lower():
                    s = s + value + " "
                else:
                    if "file" in item.lower():
                        s = s + value + "='{}' "
                    else:
                        s = s + value + "={} "

        # self.args_value.set(s.strip())

    def clear_args_box(self):
        self.args_value.set("")

    def args_select_all(self, event):
        self.args_text.select_range(0, tk.END)
        return 'break'

    def custom_callback(self, value):
        ''' A custom callback for dealing with tool output.
        '''
        if "%" in value:
            try:
                str_array = value.split(" ")
                label = value.replace(str_array[len(str_array) - 1],
                                      "").strip()
                progress = float(str_array[len(str_array) - 1].replace(
                    "%", "").strip())
                self.progress_var.set(int(progress))
                self.progress_label['text'] = label
            except ValueError as e:
                print("Problem converting parsed data into number: ", e)
            except Exception as e:
                print(e)
        else:
            self.print_line_to_output(value)

        self.update(
        )  # this is needed for cancelling and updating the progress bar

    def select_all(self, event):
        self.out_text.tag_add(tk.SEL, "1.0", tk.END)
        self.out_text.mark_set(tk.INSERT, "1.0")
        self.out_text.see(tk.INSERT)
        return 'break'

    def get_tools_list(self):
        list = []
        selected_item = -1
        for item in wbt.list_tools().keys():
            if item:
                value = to_camelcase(item)
                list.append(value)
                if value == self.tool_name:
                    selected_item = len(list) - 1
        if selected_item == -1:
            selected_item = 0
            self.tool_name = list[0]

        return (list, selected_item)

    def get_toolboxes(self):
        toolboxes = set()
        for item in wbt.toolbox().splitlines(
        ):  # run wbt.toolbox with no tool specified--returns all
            if item:
                tb = item.split(":")[1].strip()
                toolboxes.add(tb)

        for v in sorted(toolboxes):
            # print(v)
            self.print_line_to_output(v)

    def refresh_tools(self):
        (self.toolslist, selected_item) = self.get_tools_list()
        self.tools_listbox.delete(0, len(self.toolslist))
        for item in sorted(self.toolslist):
            self.tools_listbox.insert(len(self.toolslist), item)

        self.tools_frame["text"] = "{} Available Tools".format(
            len(self.toolslist))
Ejemplo n.º 48
0
    def __init__(self, master):

        #GET SIZE OF THE WINDOW
        frame = Tk()
        RWidth = frame.winfo_screenwidth()  #-40*frame.winfo_screenwidth()/100
        RHeight = frame.winfo_screenheight(
        )  # -40 *frame.winfo_screenheight()/100
        frame.destroy()

        #DEFAULT VALUES
        self.initComplete = 0
        self.id_origen = -1
        self.coord_origin = []
        self.id_desti = -1
        self.coord_destination = []
        self.typePreference = -1
        self.connections = {}
        self.names = []
        self.flag_redundant = 1
        self.filenameMetro = StringVar()
        # self.filenameConnections = StringVar()
        self.filenameTimeStations = StringVar()
        self.filenameInfoVelocity = StringVar()
        #self.filenameInfoTransfers= StringVar()

        self.filenameMetro.set(
            os.path.join(os.path.dirname(__file__), "..", "CityInformation",
                         "Lyon_smallCity", "Stations.txt"))
        #self.filenameConnections.set(os.path.join(os.path.dirname(__file__),"..","CityInformation","Lyon_smallCity","Connections.txt"))
        self.filenameTimeStations.set(
            os.path.join(os.path.dirname(__file__), "..", "CityInformation",
                         "Lyon_smallCity", "Time.txt"))
        self.filenameInfoVelocity.set(
            os.path.join(os.path.dirname(__file__), "..", "CityInformation",
                         "Lyon_smallCity", "InfoVelocity.txt"))
        #self.filenameInfoTransfers.set(os.path.join(os.path.dirname(__file__),"..","CityInformation","Lyon_smallCity","InfoTransfers.txt"))

        #WINDOW DEFINITION
        frame = Frame(master, width=RWidth, height=RHeight)
        frame.pack()
        self.master = master
        self.x, self.y, self.w, self.h = -1, -1, -1, -1
        self.master.title("PUBLIC - TRANS")

        # CALCULATE BUTTON DEFINITION
        self.Button_Calculate = Button(self.master,
                                       text="Calcular Ruta",
                                       relief="raised",
                                       width="15")
        self.Button_Calculate.place(x=552. / 1300 * RWidth,
                                    y=770. / 900 * RHeight,
                                    width=117,
                                    height=28)

        self.Button_Calculate.bind("<ButtonRelease-1>",
                                   self.Button_Calculate_Click)

        #QUIT BUTTON DEFINITION
        self.Button_Quit = Button(frame,
                                  text="Sortir",
                                  width="15",
                                  command=frame.quit)
        self.Button_Quit.place(x=732. / 1300 * RWidth,
                               y=770. / 900 * RHeight,
                               width=117,
                               height=28)
        self.Button_Quit.bind("<ButtonRelease-1>", self.Button_Quit_Click)

        #GLOBAL BOXES
        OriginDestinationFrame = LabelFrame(self.master,
                                            text="Dades de la consulta")
        OriginDestinationFrame.pack(fill="both", expand="yes")
        OriginDestinationFrame.place(x=20. / 1300 * RWidth,
                                     y=30,
                                     width=1200. / 1300 * RWidth,
                                     height=350. / 900 * RHeight)
        ResultsFrame = LabelFrame(self.master, text="Resultats")
        ResultsFrame.pack(fill="both", expand="yes")
        ResultsFrame.place(x=20. / 1300 * RWidth,
                           y=400. / 900 * RHeight,
                           width=1200. / 1300 * RWidth,
                           height=350. / 900 * RHeight)

        #TITLES
        self.Label1 = Label(self.master, text="ORIGEN : ")
        self.Label1.place(x=300. / 1300 * RWidth, y=280. / 900 * RHeight)
        self.Label_3 = Label(self.master, text="DESTI : ")
        self.Label_3.place(x=550. / 1300 * RWidth, y=280. / 900 * RHeight)
        self.Label_4 = Label(self.master, text="RUTA TROBADA:")
        self.Label_4.place(x=650. / 1300 * RWidth,
                           y=420. / 900 * RHeight,
                           width=112. / 1300 * RWidth)
        self.Information_Origin_Selection = Label(
            self.master,
            text="Selecciona Estacio Metro ORIGEN :",
            justify=LEFT)
        self.Information_Origin_Selection.place(x=300. / 1300 * RWidth,
                                                y=80. / 900 * RHeight)
        self.Information_Destination_Selection = Label(
            self.master, text="Selecciona Estacio Metro DESTI :", justify=LEFT)
        self.Information_Destination_Selection.place(x=560. / 1300 * RWidth,
                                                     y=80. / 900 * RHeight)
        self.Information_Origin_Selection = Label(
            self.master,
            text="Tambe pots indicar les teves coordenades :",
            justify=LEFT)
        self.Information_Origin_Selection.place(x=310. / 1300 * RWidth,
                                                y=300. / 900 * RHeight)
        self.Information_Preferences = Label(self.master,
                                             text="Selecciona Preferencies : ",
                                             justify=LEFT)
        self.Information_Preferences.place(x=900. / 1300 * RWidth,
                                           y=80. / 900 * RHeight)
        self.Label_x_origin = Label(self.master, text="x = ", justify=LEFT)
        self.Label_x_origin.place(x=350. / 1300 * RWidth,
                                  y=330. / 900 * RHeight)
        self.Label_y_origin = Label(self.master, text="y = ", justify=LEFT)
        self.Label_y_origin.place(x=420. / 1300 * RWidth,
                                  y=330. / 900 * RHeight)
        self.Label_x_destination = Label(self.master,
                                         text="x = ",
                                         justify=LEFT)
        self.Label_x_destination.place(x=620. / 1300 * RWidth,
                                       y=330. / 900 * RHeight)
        self.Label_y_destination = Label(self.master,
                                         text="y = ",
                                         justify=LEFT)
        self.Label_y_destination.place(x=700. / 1300 * RWidth,
                                       y=330. / 900 * RHeight)
        self.LabelFilenameMetro = Label(self.master,
                                        text="Fitxer de la ciutat: ",
                                        justify=LEFT)
        self.LabelFilenameMetro.place(x=70. / 1300 * RWidth,
                                      y=60. / 900 * RHeight)
        self.Text_filenameMetro = Entry(self.master,
                                        textvariable=self.filenameMetro)
        self.Text_filenameMetro.place(x=70. / 1300 * RWidth,
                                      y=80. / 900 * RHeight,
                                      width=230,
                                      height=20)
        #self.LabelFilenameCorrespondences = Label(self.master, text="Matriu d'adjacencia :", justify=LEFT)
        #self.LabelFilenameCorrespondences.place(x=70./1300*RWidth, y=110./900*RHeight)
        #self.Text_filenameConnections = Entry(self.master, textvariable=self.filenameConnections)
        #self.Text_filenameConnections.place(x=70./1300*RWidth, y=130./900*RHeight, width=230, height=20)
        self.LabelFilenameTimeStations = Label(self.master,
                                               text="Costos Reals (temps):",
                                               justify=LEFT)
        self.LabelFilenameTimeStations.place(x=70. / 1300 * RWidth,
                                             y=150. / 900 * RHeight)
        self.Text_filenameTimeStations = Entry(
            self.master, textvariable=self.filenameTimeStations)
        self.Text_filenameTimeStations.place(x=70. / 1300 * RWidth,
                                             y=170. / 900 * RHeight,
                                             width=230,
                                             height=20)
        self.LabelFilenameVelocity = Label(self.master,
                                           text="Informacio velocitats:",
                                           justify=LEFT)
        self.LabelFilenameVelocity.place(x=70. / 1300 * RWidth,
                                         y=190. / 900 * RHeight)
        self.Text_filenameVelocity = Entry(
            self.master, textvariable=self.filenameInfoVelocity)
        self.Text_filenameVelocity.place(x=70. / 1300 * RWidth,
                                         y=210. / 900 * RHeight,
                                         width=230,
                                         height=20)
        #self.LabelFilenameTransfers= Label(self.master, text="Informacio Transbordaments:", justify=LEFT)
        #self.LabelFilenameTransfers.place(x=70./1300*RWidth, y=230./900*RHeight)
        #self.Text_filenameTransfers = Entry(self.master, textvariable=self.filenameInfoTransfers)
        #self.Text_filenameTransfers.place(x=70./1300*RWidth, y=250./900*RHeight, width=230, height=20)

        # OUTPUTS TITLES
        self.Label_5 = Label(self.master,
                             text="Temps Total: ",
                             image="",
                             width="15",
                             justify=LEFT,
                             anchor=W)
        self.Label_5.place(x=80. / 1300 * RWidth,
                           y=450. / 900 * RHeight,
                           width=150,
                           height=23)
        self.Label_6 = Label(self.master,
                             text="Distancia :",
                             image="",
                             width="15",
                             justify=LEFT,
                             anchor=W)
        self.Label_6.place(x=80. / 1300 * RWidth,
                           y=500. / 900 * RHeight,
                           width=150,
                           height=23)
        self.Label_7 = Label(self.master,
                             text="Transbords : ",
                             width="15",
                             justify=LEFT,
                             anchor=W)
        self.Label_7.place(x=80. / 1300 * RWidth,
                           y=550. / 900 * RHeight,
                           width=150,
                           height=23)
        self.Label_8 = Label(self.master,
                             text="Parades : ",
                             image="",
                             width="15",
                             justify=LEFT,
                             anchor=W)
        self.Label_8.place(x=80. / 1300 * RWidth,
                           y=600. / 900 * RHeight,
                           width=150,
                           height=23)
        self.Label_9 = Label(self.master,
                             text="Nodes Expandits : ",
                             image="",
                             width="15",
                             justify=LEFT,
                             anchor=W)
        self.Label_9.place(x=80. / 1300 * RWidth,
                           y=650. / 900 * RHeight,
                           width=150,
                           height=23)
        self.Label_10 = Label(self.master,
                              text="Llista Nodes Visitats",
                              width="15",
                              justify=LEFT)
        self.Label_10.place(x=300. / 1300 * RWidth,
                            y=450. / 900 * RHeight,
                            width=120,
                            height=27)
        self.Label_11 = Label(self.master,
                              text=" Prof. Solucio : ",
                              image="",
                              width="15",
                              justify=LEFT,
                              anchor=W)
        self.Label_11.place(x=80. / 1300 * RWidth,
                            y=700. / 900 * RHeight,
                            width=113,
                            height=23)

        # OUTPUT MESSAGES
        self.text_expandedNodes = StringVar(
        )  # Will contain the amount of expanded nodes in the search
        self.text_time = StringVar()  # Will contain the travel times it takes
        self.text_distance = StringVar(
        )  # Will contain the travel distance it takes
        self.text_transfers = StringVar(
        )  # Will contain the connections times it takes
        self.text_stopStations = StringVar()  # Will contain the stops it takes
        self.text_depth = StringVar(
        )  # will containt the depth of the optimal solution

        #DEFAULT VALUES FOR OUTPUT MESSAGES
        self.text_expandedNodes.set("0")
        self.text_time.set("0")
        self.text_distance.set("0")
        self.text_transfers.set("0")
        self.text_stopStations.set("0")
        self.text_depth.set("0")

        #OUTPUT MESSAGES - DEFINITION
        self.sms_time = Message(self.master,
                                textvariable=self.text_time,
                                aspect=200)
        self.sms_time.place(x=200. / 1300 * RWidth,
                            y=450. / 900 * RHeight,
                            width=150,
                            height=23)
        self.sms_distance = Message(self.master,
                                    textvariable=self.text_distance,
                                    aspect=300)
        self.sms_distance.place(x=200. / 1300 * RWidth,
                                y=500. / 900 * RHeight,
                                width=150,
                                height=23)
        self.sms_connections = Message(self.master,
                                       textvariable=self.text_transfers)
        self.sms_connections.place(x=200. / 1300 * RWidth,
                                   y=550. / 900 * RHeight,
                                   width=150,
                                   height=23)
        self.sms_stopStations = Message(self.master,
                                        textvariable=self.text_stopStations)
        self.sms_stopStations.place(x=200. / 1300 * RWidth,
                                    y=600. / 900 * RHeight,
                                    width=150,
                                    height=23)
        self.sms_expandedNodes = Message(self.master,
                                         textvariable=self.text_expandedNodes)
        self.sms_expandedNodes.place(x=200. / 1300 * RWidth,
                                     y=650. / 900 * RHeight,
                                     width=150,
                                     height=23)
        self.sms_depth = Message(self.master, textvariable=self.text_depth)
        self.sms_depth.place(x=200. / 1300 * RWidth,
                             y=700. / 900 * RHeight,
                             width=150,
                             height=23)

        # ORIGIN STATIONS LIST
        lbframe = Frame(self.master)
        self.Origin_Listbox_frame = lbframe
        scrollbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Origin_Listbox = Listbox(lbframe,
                                      width="15",
                                      selectmode="extended",
                                      yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.Origin_Listbox.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.Origin_Listbox.pack(side=LEFT, fill=BOTH, expand=1)
        self.Origin_Listbox_frame.place(x=300. / 1300 * RWidth,
                                        y=104. / 900 * RHeight,
                                        width=250. / 1300 * RWidth,
                                        height=170. / 900 * RHeight)
        self.Origin_Listbox.bind("<ButtonRelease-1>",
                                 self.Origin_Listbox_Click)

        # DESTINATION STATIONS LIST
        lbframe = Frame(self.master)
        self.Destination_Listbox_frame = lbframe
        scrollbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Destination_Listbox = Listbox(lbframe,
                                           width="15",
                                           selectmode="extended",
                                           yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.Destination_Listbox.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.Destination_Listbox.pack(side=LEFT, fill=BOTH, expand=1)
        self.Destination_Listbox_frame.place(x=560. / 1300 * RWidth,
                                             y=104. / 900 * RHeight,
                                             width=250. / 1300 * RWidth,
                                             height=170. / 900 * RHeight)
        self.Destination_Listbox.bind("<ButtonRelease-1>",
                                      self.Destination_Listbox_Click)

        # PREFERENCES - MINIMUM DISTANCE
        self.Check_Button_Distance_Radiobutton = Radiobutton(
            self.master,
            text="Minim Temps",
            variable=self.typePreference,
            value=1,
            justify=LEFT)
        self.Check_Button_Distance_Radiobutton.place(x=900. / 1300 * RWidth,
                                                     y=130. / 900 * RHeight)
        self.RadioGroup1_StringVar = StringVar()
        self.RadioGroup1_StringVar.set("check_button_distance")
        self.RadioGroup1_StringVar_traceName = self.RadioGroup1_StringVar.trace_variable(
            "w", self.RadioGroup1_StringVar_Callback)
        self.Check_Button_Distance_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        # PREFERENCES - MINIMUM STOP STATIONS
        self.Check_Button_StopStations_Radiobutton = Radiobutton(
            self.master,
            text="Minima Distancia",
            variable=self.typePreference,
            value=2,
            justify=LEFT)
        self.Check_Button_StopStations_Radiobutton.place(
            x=900. / 1300 * RWidth, y=160. / 900 * RHeight)
        self.Check_Button_StopStations_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        # PREFERENCES - MINIMUM TIME
        self.Check_Button_Time_Radiobutton = Radiobutton(
            self.master,
            text="Minim Transbords",
            variable=self.typePreference,
            value=3,
            justify=LEFT)
        self.Check_Button_Time_Radiobutton.place(x=900. / 1300 * RWidth,
                                                 y=190. / 900 * RHeight)
        self.Check_Button_Time_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        # PREFERENCES - MINIMUM CONNECTIONS
        self.Check_Button_Connections_Radiobutton = Radiobutton(
            self.master,
            text="Minim Nombre de Parades",
            variable=self.typePreference,
            value=4,
            justify=LEFT)
        self.Check_Button_Connections_Radiobutton.place(x=900. / 1300 * RWidth,
                                                        y=220. / 900 * RHeight)
        self.Check_Button_Connections_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        # EXPANDED NODES OUTPUT MESSAGE
        self.Text_NodeList = ScrolledText(self.master)
        self.Text_NodeList.pack(side=LEFT, fill=BOTH, expand=1)
        self.Text_NodeList.place(x=330. / 1300 * RWidth,
                                 y=500. / 900 * RHeight,
                                 width=250. / 1300 * RWidth,
                                 height=200. / 900 * RHeight)

        # OPTIMAL PATH OUTPUT MESSAGE
        self.Route_Text = ScrolledText(self.master)
        self.Route_Text.pack(side=LEFT, fill=BOTH, expand=1)
        self.Route_Text.place(x=650. / 1300 * RWidth,
                              y=450. / 900 * RHeight,
                              width=550. / 1300 * RWidth,
                              height=280. / 900 * RHeight)
        self.master.resizable(
            0, 0)  # Linux may crash in this line. In this case, just comment

        # ORIGIN AND DESTINATION SELECTED
        self.v_origin = StringVar()
        self.v_destination = StringVar()
        self.origen_message = Label(self.master, textvariable=self.v_origin)
        self.origen_message.place(x=370. / 1300 * RWidth,
                                  y=280. / 900 * RHeight)
        self.desti_message = Label(self.master,
                                   textvariable=self.v_destination)
        self.desti_message.place(x=620. / 1300 * RWidth,
                                 y=280. / 900 * RHeight)
        self.v_origin.set("")
        self.v_destination.set("")

        # COORDINATES BOXES - X ORIGIN
        self.string_origin_position_x = StringVar()
        self.string_origin_position_x.set("")
        self.Text_x_origin = Entry(self.master,
                                   textvariable=self.string_origin_position_x)
        self.Text_x_origin.place(x=380. / 1300 * RWidth,
                                 y=330. / 900 * RHeight,
                                 width=40,
                                 height=20)

        # COORDINATES BOXES - Y ORIGIN
        self.string_origin_position_y = StringVar()
        self.string_origin_position_y.set("")
        self.Text_y_origin = Entry(self.master,
                                   textvariable=self.string_origin_position_y)
        self.Text_y_origin.place(x=450. / 1300 * RWidth,
                                 y=330. / 900 * RHeight,
                                 width=40,
                                 height=20)

        # COORDINATES BOXES - X DESTINATION
        self.string_destination_position_x = StringVar()
        self.string_destination_position_x.set("")
        self.Text_x_destination = Entry(
            self.master, textvariable=self.string_destination_position_x)
        self.Text_x_destination.place(x=650. / 1300 * RWidth,
                                      y=330. / 900 * RHeight,
                                      width=40,
                                      height=20)

        # COORDINATES BOXES - Y DESTINATION
        self.string_destination_position_y = StringVar()
        self.string_destination_position_y.set("")
        self.Text_y_destination = Entry(
            self.master, textvariable=self.string_destination_position_y)
        self.Text_y_destination.place(x=730. / 1300 * RWidth,
                                      y=330. / 900 * RHeight,
                                      width=40,
                                      height=20)

        # COORDINATES SEARCH BUTTON
        self.Button_Calculate = Button(self.master,
                                       text="Establir coordenades",
                                       relief="raised")
        self.Button_Calculate.place(x=800. / 1300 * RWidth,
                                    y=330. / 900 * RHeight,
                                    width=117,
                                    height=28)
        self.Button_Calculate.bind("<ButtonRelease-1>",
                                   self.Button_Update_Position)

        # UPDATE CITY INFORMATION BUTTON
        self.Button_Update_City = Button(self.master,
                                         text="Actualitzar informacio ciutat",
                                         relief="raised",
                                         width="15",
                                         command=self.Button_Update_City)
        self.Button_Update_City.place(x=55. / 1300 * RWidth,
                                      y=340. / 900 * RHeight,
                                      width=200,
                                      height=28)
        #self.Button_Update_City.bind("<ButtonRelease-1>", self.Button_Update_City())

        #FILENAMES BOXES SETTING: FILENAMES DEFAULT VALUES
        self.filenameMetro.set(self.filenameMetro.get())
        #self.filenameConnections.set(self.filenameConnections.get())
        self.filenameTimeStations.set(self.filenameTimeStations.get())

        #CONNECTION WITH SUBWAYMAP.PY -> Update Station Information
        self.stationList = readStationInformation(self.filenameMetro.get())
        #self.connections = readCostTable(self.filenameConnections.get())
        #self.stationList = setNextStations(self.stationList, self.connections)
        #self.timeTransfers = readCostTable(self.filenametimeTransfers.get())
        self.timeStations = readCostTable(self.filenameTimeStations.get())
        #self.stationList=setNextStations(self.stationList, self.timeStations)
        infoVelocity = readInformation(self.filenameInfoVelocity.get())
        #infoTransfers=readInformation(self.filenameInfoTransfers.get())

        self.city = CityInfo(infoVelocity, self.stationList, self.timeStations)
        self.stationList = self.city.StationList

        #READING CITY INFORMATION
        ids = 0
        indexes = []
        for i in self.stationList:
            ids = ids + 1
            if i.name not in self.names:  # Do not consider as different station two entries with the same name
                indexes.append(ids)
                self.names.append(i.name)

        self.names, self.order_names = zip(
            *sorted(zip(self.names, indexes))
        )  # Sort alphabetically the list of stations. Keep the index order

        # INSERT PREVIOUS INFORMATION READ INTO THE LISTBOXES
        for i in self.names:
            self.Destination_Listbox.insert(END, i)

        for i in self.names:
            self.Origin_Listbox.insert(END, i)
Ejemplo n.º 49
0
class ConsoleUi:
    """Poll messages from a logging queue and display them in a scrolled text widget"""
    def __init__(self, frame):
        self.frame = frame

        # Create a ScrolledText wdiget
        self.scrolled_text = ScrolledText(frame, state='normal', height=5)
        self.scrolled_text.place(relx=0.01,
                                 rely=0.01,
                                 relheight=0.97,
                                 relwidth=0.98)
        self.scrolled_text.configure(wrap=NONE)
        self.scrolled_text.configure(font='TkFixedFont')
        self.scrolled_text.tag_config('INFO', foreground='black')
        self.scrolled_text.tag_config('DEBUG', foreground='gray')
        self.scrolled_text.tag_config('WARNING', foreground='orange')
        self.scrolled_text.tag_config('ERROR', foreground='red')
        self.scrolled_text.tag_config('CRITICAL',
                                      foreground='red',
                                      underline=1)
        # Create a logging handler using a queue
        self.log_queue = queue.Queue()
        self.queue_handler = QueueHandler(self.log_queue)
        formatter = logging.Formatter('%(asctime)s: %(message)s')
        self.queue_handler.setFormatter(formatter)
        logger.addHandler(self.queue_handler)
        # Start polling messages from the queue
        self.frame.after(100, self.poll_log_queue)

    def display(self, record):
        msg = self.queue_handler.format(record)
        self.scrolled_text.configure(state='normal')
        self.scrolled_text.insert(tk.END, msg + '\n', record.levelname)
        self.scrolled_text.configure(state='disabled')
        # Autoscroll to the bottom
        self.scrolled_text.yview(tk.END)

    def poll_log_queue(self):
        # Check every 100ms if there is a new message in the queue to display
        while True:
            try:
                record = self.log_queue.get(block=False)
            except queue.Empty:
                break
            else:
                self.display(record)
        self.frame.after(100, self.poll_log_queue)
Ejemplo n.º 50
0
class _Astargui:
    # __init__ contains the window design, including default values.
    def __init__(self, master):

        #GET SIZE OF THE WINDOW
        frame = Tk()
        RWidth = frame.winfo_screenwidth()  #-40*frame.winfo_screenwidth()/100
        RHeight = frame.winfo_screenheight(
        )  # -40 *frame.winfo_screenheight()/100
        frame.destroy()

        #DEFAULT VALUES
        self.initComplete = 0
        self.id_origen = -1
        self.coord_origin = []
        self.id_desti = -1
        self.coord_destination = []
        self.typePreference = -1
        self.connections = {}
        self.names = []
        self.flag_redundant = 1
        self.filenameMetro = StringVar()
        # self.filenameConnections = StringVar()
        self.filenameTimeStations = StringVar()
        self.filenameInfoVelocity = StringVar()
        #self.filenameInfoTransfers= StringVar()

        self.filenameMetro.set(
            os.path.join(os.path.dirname(__file__), "..", "CityInformation",
                         "Lyon_smallCity", "Stations.txt"))
        #self.filenameConnections.set(os.path.join(os.path.dirname(__file__),"..","CityInformation","Lyon_smallCity","Connections.txt"))
        self.filenameTimeStations.set(
            os.path.join(os.path.dirname(__file__), "..", "CityInformation",
                         "Lyon_smallCity", "Time.txt"))
        self.filenameInfoVelocity.set(
            os.path.join(os.path.dirname(__file__), "..", "CityInformation",
                         "Lyon_smallCity", "InfoVelocity.txt"))
        #self.filenameInfoTransfers.set(os.path.join(os.path.dirname(__file__),"..","CityInformation","Lyon_smallCity","InfoTransfers.txt"))

        #WINDOW DEFINITION
        frame = Frame(master, width=RWidth, height=RHeight)
        frame.pack()
        self.master = master
        self.x, self.y, self.w, self.h = -1, -1, -1, -1
        self.master.title("PUBLIC - TRANS")

        # CALCULATE BUTTON DEFINITION
        self.Button_Calculate = Button(self.master,
                                       text="Calcular Ruta",
                                       relief="raised",
                                       width="15")
        self.Button_Calculate.place(x=552. / 1300 * RWidth,
                                    y=770. / 900 * RHeight,
                                    width=117,
                                    height=28)

        self.Button_Calculate.bind("<ButtonRelease-1>",
                                   self.Button_Calculate_Click)

        #QUIT BUTTON DEFINITION
        self.Button_Quit = Button(frame,
                                  text="Sortir",
                                  width="15",
                                  command=frame.quit)
        self.Button_Quit.place(x=732. / 1300 * RWidth,
                               y=770. / 900 * RHeight,
                               width=117,
                               height=28)
        self.Button_Quit.bind("<ButtonRelease-1>", self.Button_Quit_Click)

        #GLOBAL BOXES
        OriginDestinationFrame = LabelFrame(self.master,
                                            text="Dades de la consulta")
        OriginDestinationFrame.pack(fill="both", expand="yes")
        OriginDestinationFrame.place(x=20. / 1300 * RWidth,
                                     y=30,
                                     width=1200. / 1300 * RWidth,
                                     height=350. / 900 * RHeight)
        ResultsFrame = LabelFrame(self.master, text="Resultats")
        ResultsFrame.pack(fill="both", expand="yes")
        ResultsFrame.place(x=20. / 1300 * RWidth,
                           y=400. / 900 * RHeight,
                           width=1200. / 1300 * RWidth,
                           height=350. / 900 * RHeight)

        #TITLES
        self.Label1 = Label(self.master, text="ORIGEN : ")
        self.Label1.place(x=300. / 1300 * RWidth, y=280. / 900 * RHeight)
        self.Label_3 = Label(self.master, text="DESTI : ")
        self.Label_3.place(x=550. / 1300 * RWidth, y=280. / 900 * RHeight)
        self.Label_4 = Label(self.master, text="RUTA TROBADA:")
        self.Label_4.place(x=650. / 1300 * RWidth,
                           y=420. / 900 * RHeight,
                           width=112. / 1300 * RWidth)
        self.Information_Origin_Selection = Label(
            self.master,
            text="Selecciona Estacio Metro ORIGEN :",
            justify=LEFT)
        self.Information_Origin_Selection.place(x=300. / 1300 * RWidth,
                                                y=80. / 900 * RHeight)
        self.Information_Destination_Selection = Label(
            self.master, text="Selecciona Estacio Metro DESTI :", justify=LEFT)
        self.Information_Destination_Selection.place(x=560. / 1300 * RWidth,
                                                     y=80. / 900 * RHeight)
        self.Information_Origin_Selection = Label(
            self.master,
            text="Tambe pots indicar les teves coordenades :",
            justify=LEFT)
        self.Information_Origin_Selection.place(x=310. / 1300 * RWidth,
                                                y=300. / 900 * RHeight)
        self.Information_Preferences = Label(self.master,
                                             text="Selecciona Preferencies : ",
                                             justify=LEFT)
        self.Information_Preferences.place(x=900. / 1300 * RWidth,
                                           y=80. / 900 * RHeight)
        self.Label_x_origin = Label(self.master, text="x = ", justify=LEFT)
        self.Label_x_origin.place(x=350. / 1300 * RWidth,
                                  y=330. / 900 * RHeight)
        self.Label_y_origin = Label(self.master, text="y = ", justify=LEFT)
        self.Label_y_origin.place(x=420. / 1300 * RWidth,
                                  y=330. / 900 * RHeight)
        self.Label_x_destination = Label(self.master,
                                         text="x = ",
                                         justify=LEFT)
        self.Label_x_destination.place(x=620. / 1300 * RWidth,
                                       y=330. / 900 * RHeight)
        self.Label_y_destination = Label(self.master,
                                         text="y = ",
                                         justify=LEFT)
        self.Label_y_destination.place(x=700. / 1300 * RWidth,
                                       y=330. / 900 * RHeight)
        self.LabelFilenameMetro = Label(self.master,
                                        text="Fitxer de la ciutat: ",
                                        justify=LEFT)
        self.LabelFilenameMetro.place(x=70. / 1300 * RWidth,
                                      y=60. / 900 * RHeight)
        self.Text_filenameMetro = Entry(self.master,
                                        textvariable=self.filenameMetro)
        self.Text_filenameMetro.place(x=70. / 1300 * RWidth,
                                      y=80. / 900 * RHeight,
                                      width=230,
                                      height=20)
        #self.LabelFilenameCorrespondences = Label(self.master, text="Matriu d'adjacencia :", justify=LEFT)
        #self.LabelFilenameCorrespondences.place(x=70./1300*RWidth, y=110./900*RHeight)
        #self.Text_filenameConnections = Entry(self.master, textvariable=self.filenameConnections)
        #self.Text_filenameConnections.place(x=70./1300*RWidth, y=130./900*RHeight, width=230, height=20)
        self.LabelFilenameTimeStations = Label(self.master,
                                               text="Costos Reals (temps):",
                                               justify=LEFT)
        self.LabelFilenameTimeStations.place(x=70. / 1300 * RWidth,
                                             y=150. / 900 * RHeight)
        self.Text_filenameTimeStations = Entry(
            self.master, textvariable=self.filenameTimeStations)
        self.Text_filenameTimeStations.place(x=70. / 1300 * RWidth,
                                             y=170. / 900 * RHeight,
                                             width=230,
                                             height=20)
        self.LabelFilenameVelocity = Label(self.master,
                                           text="Informacio velocitats:",
                                           justify=LEFT)
        self.LabelFilenameVelocity.place(x=70. / 1300 * RWidth,
                                         y=190. / 900 * RHeight)
        self.Text_filenameVelocity = Entry(
            self.master, textvariable=self.filenameInfoVelocity)
        self.Text_filenameVelocity.place(x=70. / 1300 * RWidth,
                                         y=210. / 900 * RHeight,
                                         width=230,
                                         height=20)
        #self.LabelFilenameTransfers= Label(self.master, text="Informacio Transbordaments:", justify=LEFT)
        #self.LabelFilenameTransfers.place(x=70./1300*RWidth, y=230./900*RHeight)
        #self.Text_filenameTransfers = Entry(self.master, textvariable=self.filenameInfoTransfers)
        #self.Text_filenameTransfers.place(x=70./1300*RWidth, y=250./900*RHeight, width=230, height=20)

        # OUTPUTS TITLES
        self.Label_5 = Label(self.master,
                             text="Temps Total: ",
                             image="",
                             width="15",
                             justify=LEFT,
                             anchor=W)
        self.Label_5.place(x=80. / 1300 * RWidth,
                           y=450. / 900 * RHeight,
                           width=150,
                           height=23)
        self.Label_6 = Label(self.master,
                             text="Distancia :",
                             image="",
                             width="15",
                             justify=LEFT,
                             anchor=W)
        self.Label_6.place(x=80. / 1300 * RWidth,
                           y=500. / 900 * RHeight,
                           width=150,
                           height=23)
        self.Label_7 = Label(self.master,
                             text="Transbords : ",
                             width="15",
                             justify=LEFT,
                             anchor=W)
        self.Label_7.place(x=80. / 1300 * RWidth,
                           y=550. / 900 * RHeight,
                           width=150,
                           height=23)
        self.Label_8 = Label(self.master,
                             text="Parades : ",
                             image="",
                             width="15",
                             justify=LEFT,
                             anchor=W)
        self.Label_8.place(x=80. / 1300 * RWidth,
                           y=600. / 900 * RHeight,
                           width=150,
                           height=23)
        self.Label_9 = Label(self.master,
                             text="Nodes Expandits : ",
                             image="",
                             width="15",
                             justify=LEFT,
                             anchor=W)
        self.Label_9.place(x=80. / 1300 * RWidth,
                           y=650. / 900 * RHeight,
                           width=150,
                           height=23)
        self.Label_10 = Label(self.master,
                              text="Llista Nodes Visitats",
                              width="15",
                              justify=LEFT)
        self.Label_10.place(x=300. / 1300 * RWidth,
                            y=450. / 900 * RHeight,
                            width=120,
                            height=27)
        self.Label_11 = Label(self.master,
                              text=" Prof. Solucio : ",
                              image="",
                              width="15",
                              justify=LEFT,
                              anchor=W)
        self.Label_11.place(x=80. / 1300 * RWidth,
                            y=700. / 900 * RHeight,
                            width=113,
                            height=23)

        # OUTPUT MESSAGES
        self.text_expandedNodes = StringVar(
        )  # Will contain the amount of expanded nodes in the search
        self.text_time = StringVar()  # Will contain the travel times it takes
        self.text_distance = StringVar(
        )  # Will contain the travel distance it takes
        self.text_transfers = StringVar(
        )  # Will contain the connections times it takes
        self.text_stopStations = StringVar()  # Will contain the stops it takes
        self.text_depth = StringVar(
        )  # will containt the depth of the optimal solution

        #DEFAULT VALUES FOR OUTPUT MESSAGES
        self.text_expandedNodes.set("0")
        self.text_time.set("0")
        self.text_distance.set("0")
        self.text_transfers.set("0")
        self.text_stopStations.set("0")
        self.text_depth.set("0")

        #OUTPUT MESSAGES - DEFINITION
        self.sms_time = Message(self.master,
                                textvariable=self.text_time,
                                aspect=200)
        self.sms_time.place(x=200. / 1300 * RWidth,
                            y=450. / 900 * RHeight,
                            width=150,
                            height=23)
        self.sms_distance = Message(self.master,
                                    textvariable=self.text_distance,
                                    aspect=300)
        self.sms_distance.place(x=200. / 1300 * RWidth,
                                y=500. / 900 * RHeight,
                                width=150,
                                height=23)
        self.sms_connections = Message(self.master,
                                       textvariable=self.text_transfers)
        self.sms_connections.place(x=200. / 1300 * RWidth,
                                   y=550. / 900 * RHeight,
                                   width=150,
                                   height=23)
        self.sms_stopStations = Message(self.master,
                                        textvariable=self.text_stopStations)
        self.sms_stopStations.place(x=200. / 1300 * RWidth,
                                    y=600. / 900 * RHeight,
                                    width=150,
                                    height=23)
        self.sms_expandedNodes = Message(self.master,
                                         textvariable=self.text_expandedNodes)
        self.sms_expandedNodes.place(x=200. / 1300 * RWidth,
                                     y=650. / 900 * RHeight,
                                     width=150,
                                     height=23)
        self.sms_depth = Message(self.master, textvariable=self.text_depth)
        self.sms_depth.place(x=200. / 1300 * RWidth,
                             y=700. / 900 * RHeight,
                             width=150,
                             height=23)

        # ORIGIN STATIONS LIST
        lbframe = Frame(self.master)
        self.Origin_Listbox_frame = lbframe
        scrollbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Origin_Listbox = Listbox(lbframe,
                                      width="15",
                                      selectmode="extended",
                                      yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.Origin_Listbox.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.Origin_Listbox.pack(side=LEFT, fill=BOTH, expand=1)
        self.Origin_Listbox_frame.place(x=300. / 1300 * RWidth,
                                        y=104. / 900 * RHeight,
                                        width=250. / 1300 * RWidth,
                                        height=170. / 900 * RHeight)
        self.Origin_Listbox.bind("<ButtonRelease-1>",
                                 self.Origin_Listbox_Click)

        # DESTINATION STATIONS LIST
        lbframe = Frame(self.master)
        self.Destination_Listbox_frame = lbframe
        scrollbar = Scrollbar(lbframe, orient=VERTICAL)
        self.Destination_Listbox = Listbox(lbframe,
                                           width="15",
                                           selectmode="extended",
                                           yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.Destination_Listbox.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.Destination_Listbox.pack(side=LEFT, fill=BOTH, expand=1)
        self.Destination_Listbox_frame.place(x=560. / 1300 * RWidth,
                                             y=104. / 900 * RHeight,
                                             width=250. / 1300 * RWidth,
                                             height=170. / 900 * RHeight)
        self.Destination_Listbox.bind("<ButtonRelease-1>",
                                      self.Destination_Listbox_Click)

        # PREFERENCES - MINIMUM DISTANCE
        self.Check_Button_Distance_Radiobutton = Radiobutton(
            self.master,
            text="Minim Temps",
            variable=self.typePreference,
            value=1,
            justify=LEFT)
        self.Check_Button_Distance_Radiobutton.place(x=900. / 1300 * RWidth,
                                                     y=130. / 900 * RHeight)
        self.RadioGroup1_StringVar = StringVar()
        self.RadioGroup1_StringVar.set("check_button_distance")
        self.RadioGroup1_StringVar_traceName = self.RadioGroup1_StringVar.trace_variable(
            "w", self.RadioGroup1_StringVar_Callback)
        self.Check_Button_Distance_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        # PREFERENCES - MINIMUM STOP STATIONS
        self.Check_Button_StopStations_Radiobutton = Radiobutton(
            self.master,
            text="Minima Distancia",
            variable=self.typePreference,
            value=2,
            justify=LEFT)
        self.Check_Button_StopStations_Radiobutton.place(
            x=900. / 1300 * RWidth, y=160. / 900 * RHeight)
        self.Check_Button_StopStations_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        # PREFERENCES - MINIMUM TIME
        self.Check_Button_Time_Radiobutton = Radiobutton(
            self.master,
            text="Minim Transbords",
            variable=self.typePreference,
            value=3,
            justify=LEFT)
        self.Check_Button_Time_Radiobutton.place(x=900. / 1300 * RWidth,
                                                 y=190. / 900 * RHeight)
        self.Check_Button_Time_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        # PREFERENCES - MINIMUM CONNECTIONS
        self.Check_Button_Connections_Radiobutton = Radiobutton(
            self.master,
            text="Minim Nombre de Parades",
            variable=self.typePreference,
            value=4,
            justify=LEFT)
        self.Check_Button_Connections_Radiobutton.place(x=900. / 1300 * RWidth,
                                                        y=220. / 900 * RHeight)
        self.Check_Button_Connections_Radiobutton.configure(
            variable=self.RadioGroup1_StringVar)

        # EXPANDED NODES OUTPUT MESSAGE
        self.Text_NodeList = ScrolledText(self.master)
        self.Text_NodeList.pack(side=LEFT, fill=BOTH, expand=1)
        self.Text_NodeList.place(x=330. / 1300 * RWidth,
                                 y=500. / 900 * RHeight,
                                 width=250. / 1300 * RWidth,
                                 height=200. / 900 * RHeight)

        # OPTIMAL PATH OUTPUT MESSAGE
        self.Route_Text = ScrolledText(self.master)
        self.Route_Text.pack(side=LEFT, fill=BOTH, expand=1)
        self.Route_Text.place(x=650. / 1300 * RWidth,
                              y=450. / 900 * RHeight,
                              width=550. / 1300 * RWidth,
                              height=280. / 900 * RHeight)
        self.master.resizable(
            0, 0)  # Linux may crash in this line. In this case, just comment

        # ORIGIN AND DESTINATION SELECTED
        self.v_origin = StringVar()
        self.v_destination = StringVar()
        self.origen_message = Label(self.master, textvariable=self.v_origin)
        self.origen_message.place(x=370. / 1300 * RWidth,
                                  y=280. / 900 * RHeight)
        self.desti_message = Label(self.master,
                                   textvariable=self.v_destination)
        self.desti_message.place(x=620. / 1300 * RWidth,
                                 y=280. / 900 * RHeight)
        self.v_origin.set("")
        self.v_destination.set("")

        # COORDINATES BOXES - X ORIGIN
        self.string_origin_position_x = StringVar()
        self.string_origin_position_x.set("")
        self.Text_x_origin = Entry(self.master,
                                   textvariable=self.string_origin_position_x)
        self.Text_x_origin.place(x=380. / 1300 * RWidth,
                                 y=330. / 900 * RHeight,
                                 width=40,
                                 height=20)

        # COORDINATES BOXES - Y ORIGIN
        self.string_origin_position_y = StringVar()
        self.string_origin_position_y.set("")
        self.Text_y_origin = Entry(self.master,
                                   textvariable=self.string_origin_position_y)
        self.Text_y_origin.place(x=450. / 1300 * RWidth,
                                 y=330. / 900 * RHeight,
                                 width=40,
                                 height=20)

        # COORDINATES BOXES - X DESTINATION
        self.string_destination_position_x = StringVar()
        self.string_destination_position_x.set("")
        self.Text_x_destination = Entry(
            self.master, textvariable=self.string_destination_position_x)
        self.Text_x_destination.place(x=650. / 1300 * RWidth,
                                      y=330. / 900 * RHeight,
                                      width=40,
                                      height=20)

        # COORDINATES BOXES - Y DESTINATION
        self.string_destination_position_y = StringVar()
        self.string_destination_position_y.set("")
        self.Text_y_destination = Entry(
            self.master, textvariable=self.string_destination_position_y)
        self.Text_y_destination.place(x=730. / 1300 * RWidth,
                                      y=330. / 900 * RHeight,
                                      width=40,
                                      height=20)

        # COORDINATES SEARCH BUTTON
        self.Button_Calculate = Button(self.master,
                                       text="Establir coordenades",
                                       relief="raised")
        self.Button_Calculate.place(x=800. / 1300 * RWidth,
                                    y=330. / 900 * RHeight,
                                    width=117,
                                    height=28)
        self.Button_Calculate.bind("<ButtonRelease-1>",
                                   self.Button_Update_Position)

        # UPDATE CITY INFORMATION BUTTON
        self.Button_Update_City = Button(self.master,
                                         text="Actualitzar informacio ciutat",
                                         relief="raised",
                                         width="15",
                                         command=self.Button_Update_City)
        self.Button_Update_City.place(x=55. / 1300 * RWidth,
                                      y=340. / 900 * RHeight,
                                      width=200,
                                      height=28)
        #self.Button_Update_City.bind("<ButtonRelease-1>", self.Button_Update_City())

        #FILENAMES BOXES SETTING: FILENAMES DEFAULT VALUES
        self.filenameMetro.set(self.filenameMetro.get())
        #self.filenameConnections.set(self.filenameConnections.get())
        self.filenameTimeStations.set(self.filenameTimeStations.get())

        #CONNECTION WITH SUBWAYMAP.PY -> Update Station Information
        self.stationList = readStationInformation(self.filenameMetro.get())
        #self.connections = readCostTable(self.filenameConnections.get())
        #self.stationList = setNextStations(self.stationList, self.connections)
        #self.timeTransfers = readCostTable(self.filenametimeTransfers.get())
        self.timeStations = readCostTable(self.filenameTimeStations.get())
        #self.stationList=setNextStations(self.stationList, self.timeStations)
        infoVelocity = readInformation(self.filenameInfoVelocity.get())
        #infoTransfers=readInformation(self.filenameInfoTransfers.get())

        self.city = CityInfo(infoVelocity, self.stationList, self.timeStations)
        self.stationList = self.city.StationList

        #READING CITY INFORMATION
        ids = 0
        indexes = []
        for i in self.stationList:
            ids = ids + 1
            if i.name not in self.names:  # Do not consider as different station two entries with the same name
                indexes.append(ids)
                self.names.append(i.name)

        self.names, self.order_names = zip(
            *sorted(zip(self.names, indexes))
        )  # Sort alphabetically the list of stations. Keep the index order

        # INSERT PREVIOUS INFORMATION READ INTO THE LISTBOXES
        for i in self.names:
            self.Destination_Listbox.insert(END, i)

        for i in self.names:
            self.Origin_Listbox.insert(END, i)

        #Button_Update_City : Button "Actualitzar informacio Ciutat" calls this function.
        #                     It reads the corresponding files and update the City Information into the variables.

    def Button_Update_City(self):
        pass
        # Get filenames
        self.filenameMetro.set(self.filenameMetro.get())
        #self.filenameConnections.set(self.filenameConnections.get())

        #Update City Information
        self.stationList = readStationInformation(self.filenameMetro.get())
        #self.connections = readCostTable(self.filenameConnections.get())
        #self.stationList = setNextStations(self.stationList, self.connections)
        #self.timeTransfers = readCostTable(self.filenametimeTransfers.get())
        self.timeStations = readCostTable(self.filenameTimeStations.get())
        #self.stationList=setNextStations(self.stationList, self.timeStations)
        #self.stationList=setNextStations(self.stationList, self.timeConnections)

        infoVelocity = readInformation(self.filenameInfoVelocity.get())

        self.city = CityInfo(infoVelocity, self.stationList, self.timeStations)
        self.stationList = self.city.StationList

        #Delete current station lists
        self.Destination_Listbox.delete(0, END)
        self.Origin_Listbox.delete(0, END)

        self.names = []
        ids = 0
        indexes = []

        #Reading city Information
        ids = 0
        indexes = []
        for i in self.stationList:
            ids = ids + 1
            if i.name not in self.names:  # Do not consider as different station two entries with the same name
                indexes.append(ids)
                self.names.append(i.name)

        self.names, self.order_names = zip(
            *sorted(zip(self.names, indexes))
        )  # Sort alphabetically the list of stations. Keep the index order

        # Insert previous information read into the listBoxes
        for i in self.names:
            self.Destination_Listbox.insert(END, i)

        for i in self.names:
            self.Origin_Listbox.insert(END, i)

        #Button_Update_City : Button "Calcular Ruta" calls this function.
        #                     It Execute AStar Algorithm [from CercaInformada.py] and shows the optimal idoptimalpath found.

    def Button_Calculate_Click(self, event):
        pass
        #Delete current NodeList Information from previous seraches
        self.Text_NodeList.delete('0.0', END)
        #Delete current Path Information from previous seraches
        self.Route_Text.delete('0.0', END)

        if self.id_origen != -1:  # If an origin is selected, continue
            if self.id_desti != -1:  # If a destination is selected, continue
                if self.typePreference != -1:  # If a preference is selected, run ASTAR algorithm and show the Optimal Path
                    time, distance, transfers, stopStations, expanded_nodes, num_depth, visited_nodes, idoptimalpath, min_distance_origin, min_distance_destination = AstarAlgorithm(
                        self.coord_origin, self.coord_destination,
                        self.typePreference, self.city, self.flag_redundant)
                    self.Update_Resultant_Path(
                        time, distance, transfers, stopStations,
                        expanded_nodes, visited_nodes, idoptimalpath,
                        min_distance_origin, min_distance_destination,
                        self.coord_origin, self.coord_destination, num_depth)
                else:
                    self.Update_Resultant_Path(
                        [], [], [], [], [], [],
                        " NO HAS SELECCIONAT CAP PREFERENCIA", [], [], [], [],
                        [])
            else:
                self.Update_Resultant_Path([], [], [], [], [], [],
                                           " NO HAS SELECCIONAT CAP DESTI", [],
                                           [], [], [], [])
        else:
            self.Update_Resultant_Path([], [], [], [], [], [],
                                       " NO HAS SELECCIONAT CAP ORIGEN", [],
                                       [], [], [], [])

        #Button_Update_Position : Button "Establir Coordenades" calls this function.
        #                     It Update Coordinates values from the boxes

    def Button_Update_Position(self, event):
        self.string_destination_position_x.set(
            self.string_destination_position_x.get())
        self.string_destination_position_y.set(
            self.string_destination_position_y.get())
        self.string_origin_position_x.set(self.string_origin_position_x.get())
        self.string_origin_position_y.set(self.string_origin_position_y.get())
        self.coord_destination = [
            int(self.string_destination_position_x.get())
        ]
        self.coord_destination.append(
            int(self.string_destination_position_y.get()))
        self.coord_origin = [int(self.string_origin_position_x.get())]
        self.coord_origin.append(int(self.string_origin_position_y.get()))
        self.v_origin.set("")
        self.v_destination.set("")
        self.id_desti = 0  # To know that an origin is selected
        self.id_origen = 0  # To know that a destination is selected

    #Button_Quit_Click : Button "Sortir" calls this function.
    #                     It closes the application
    def Button_Quit_Click(self, event):
        pass

    #Update_Resultant_Path : It update the output messages [Information] to the GUI
    def Update_Resultant_Path(self, time, distance, transfers, stopStations,
                              expanded_nodes, visited_nodes, idoptimalpath,
                              min_distance_origin, min_distance_destination,
                              coord_origin, coord_destinationnation,
                              num_depth):
        pass
        from decimal import Decimal, ROUND_DOWN

        if time != []:
            distance = Decimal(str(distance)).quantize(Decimal('.01'),
                                                       rounding=ROUND_DOWN)
            time = Decimal(str(time)).quantize(Decimal('.01'),
                                               rounding=ROUND_DOWN)
            self.text_expandedNodes.set(str(expanded_nodes))
            self.text_time.set(str(time))
            self.text_distance.set(str(distance))
            self.text_transfers.set(str(transfers))
            self.text_stopStations.set(str(stopStations))
            self.Text_NodeList.insert(END, str(visited_nodes))
            self.text_depth.set(str(num_depth))
            self.Route_Text.insert(
                END,
                Print_path(idoptimalpath, self.stationList,
                           min_distance_origin, min_distance_destination,
                           coord_origin, coord_destinationnation))
        else:
            self.Route_Text.insert(END, Print_Error(idoptimalpath))

            #Origin_Listbox_Click : Origin Listbox calls this function.
        #                     It updates the origin selected

    def Origin_Listbox_Click(self, event):
        pass

        self.id_origen = self.order_names[int(
            self.Origin_Listbox.curselection()[0])]
        #print("origin " + str(self.id_origen))

        self.v_origin.set(str(self.stationList[self.id_origen - 1].name))
        self.string_origin_position_x.set(
            str(self.stationList[self.id_origen - 1].x))
        self.string_origin_position_y.set(
            str(self.stationList[self.id_origen - 1].y))
        self.coord_origin = (int(self.stationList[self.id_origen - 1].x),
                             int(self.stationList[self.id_origen - 1].y))

        #Destination_Listbox_Click : Destination Listbox calls this function.

    #                     It updates the destination selected
    def Destination_Listbox_Click(self, event):
        pass

        self.id_desti = self.order_names[int(
            self.Destination_Listbox.curselection()[0])]
        #print "destination " + str(self.id_desti)
        self.v_destination.set(str(self.stationList[self.id_desti - 1].name))
        self.string_destination_position_x.set(
            str(self.stationList[self.id_desti - 1].x))
        self.string_destination_position_y.set(
            str(self.stationList[self.id_desti - 1].y))
        self.coord_destination = (int(self.stationList[self.id_desti - 1].x),
                                  int(self.stationList[self.id_desti - 1].y))

    #RadioGroup1_StringVar_Callback : CheckList calls this function.
    #                                 It updates the preference selected by the user
    def RadioGroup1_StringVar_Callback(self, varName, index, mode):
        pass

        self.typePreference = self.RadioGroup1_StringVar.get()
Ejemplo n.º 51
0
    def __init__(self):
        self.root = Tk(className="EDITOR")

        self.python_files = PythonFiles(self)

        self.root.geometry("%dx%d+%d+%d" % (
            self.root.winfo_screenwidth() * 0.5,
            self.root.winfo_screenheight() * 0.4,
            # self.root.winfo_screenwidth() * 0.1, self.root.winfo_screenheight() * 0.1
            0,
            0))

        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

        self.base_title = "PyEditor v%s" % __version__
        self.root.title(self.base_title)

        self.text_frame = Frame(master=self.root)

        self.text = ScrolledText(master=self.root, background="white")
        self.text.bind("<Tab>", self.tab_event)
        self.text.grid(row=0, column=0, sticky=NSEW)

        #TODO: find a right height
        self.exec_output = ScrolledText(master=self.root,
                                        height=10,
                                        state=DISABLED,
                                        background="#dddddd")

        # for information text like load/save/run:
        self.exec_output.tag_config(
            "info",
            foreground="#0000ff",
            #background="#eeeeee"
        )

        self.exec_output.grid(row=1, column=0, sticky=NSEW)

        self.text.focus_set()

        # self.script_list = ScriptList(self)

        p = Percolator(self.text)
        d = ColorDelegator()
        p.insertfilter(d)

        # add statusbar to window
        self.init_statusbar()

        # add menu to window
        self.init_menu()

        # Add special RPi/Minecraft features, if available
        self.rpi = MinecraftSpecials(self)

        if self.rpi.mcpi_available:
            # minecraft is available
            self.set_content(DEFAULT_MCPI_SCRIPT)
            if not self.rpi.is_running:
                self.rpi.startup_minecraft()
        else:
            # no minecraft available
            self.set_content(DEFAULT_SCRIPT)

        self.root.update()
Ejemplo n.º 52
0
    def __init__(self, gui_config: GuiConfig, icon_path: str):
        # >>> Initialize class <<<
        self.num_total_task, self.num_task_finished, self.num_task_succeed = 0, 0, 0
        self.fuz_license, self.fuz_config_pack, self.fuz_url_info, self.fuz_file_items = None, None, None, None

        self.__gui_config = gui_config
        I18nUtil.set_language(gui_config['language'])
        self.__should_restart_me = False

        # >>> Initialize Queue, Timer and threading utils <<<
        self.download_thread_pool: Optional[ThreadPoolExecutor] = None
        self.descramble_thread_pool: Optional[ThreadPoolExecutor] = None
        self.local_http_util: threading.local = None
        self.queue: "Queue[DelegatedTask]" = Queue()

        # >>> Initialize GUI <<<
        self.win = tk.Tk()
        self.win.grid_columnconfigure(0, weight=1)
        self.win.title(tr('Comic FUZ Manga Downloader GUI'))
        self.win.minsize(width=700, height=400)

        if icon_path:
            self.win.iconbitmap(icon_path)

        menu = tk.Menu()

        # Language menu
        submenu = tk.Menu(tearoff=0)
        for i in LANGUAGES:
            submenu.add_command(label=i, command=functools.partial(self.switch_language, to=i))
        menu.add_cascade(label=tr('Langauge'), menu=submenu)

        # About menu
        submenu = tk.Menu(tearoff=0)
        submenu.add_command(label=tr('About'), command=self.about_me)
        menu.add_cascade(label=tr('Help'), menu=submenu)
        self.win['menu'] = menu

        frame = ttk.LabelFrame(self.win, text=tr('Download Settings'), padding=(10, 5, 10, 5))
        frame.grid(row=0, column=0, sticky='we', padx=15, pady=10)
        frame.grid_columnconfigure(1, weight=1)
        for row_index in range(5):
            frame.grid_rowconfigure(row_index, pad=3)

        # Row
        label = ttk.Label(frame, text=tr('Manga URL:'))
        label.grid(row=0, column=0, sticky='e')
        self.manga_url = tk.StringVar(value=gui_config['manga_url'])
        ttk.Entry(frame, textvariable=self.manga_url).grid(row=0, column=1, sticky='we', padx=10)

        # Row
        label = ttk.Label(frame, text=tr('Cookies.txt path:'))
        label.grid(row=1, column=0, sticky='e')
        self.cookie_path = tk.StringVar(value=gui_config['cookie_txt_path'])
        self.txt_cookie_path = ttk.Entry(frame, textvariable=self.cookie_path)
        self.txt_cookie_path.grid(row=1, column=1, sticky='we', padx=10)
        btn = ttk.Button(frame, text=tr('Browse...'), command=self.browse_cookie_path)
        btn.grid(row=1, column=2)

        # Row
        label = ttk.Label(frame, text=tr('Save to:'))
        label.grid(row=2, column=0, sticky='e')
        self.output_path = tk.StringVar(value=gui_config['save_to_path'])
        self.txt_output_path = ttk.Entry(frame, textvariable=self.output_path)
        self.txt_output_path.grid(row=2, column=1, sticky='we', padx=10)
        btn = ttk.Button(frame, text=tr('Browse...'), command=self.browse_output_path)
        btn.grid(row=2, column=2)

        # Row
        label = ttk.Label(frame, text=tr('Proxy:'))
        label.grid(row=3, column=0, sticky='e')
        sub_frame = ttk.Frame(frame)
        sub_frame.grid(row=3, column=1, sticky='w', padx=10)
        self.proxy_state = tk.StringVar(value='disabled')
        ttk.Radiobutton(
            sub_frame, text=tr('[Proxy] Disabled'), value='disabled',
            variable=self.proxy_state, command=self.proxy_radiobutton_clicked,
        ).grid(row=0, column=0)
        ttk.Radiobutton(
            sub_frame, text=tr('[Proxy] HTTP'), value='http',
            variable=self.proxy_state, command=self.proxy_radiobutton_clicked,
        ).grid(row=0, column=1)
        ttk.Radiobutton(
            sub_frame, text=tr('[Proxy] SOCKS5'), value='socks5',
            variable=self.proxy_state, command=self.proxy_radiobutton_clicked,
        ).grid(row=0, column=2, padx=(0, 20))
        self.proxy_host = tk.StringVar()
        self.proxy_host_txt = ttk.Entry(sub_frame, textvariable=self.proxy_host, state='disabled')
        self.proxy_host_txt.grid(row=0, column=3)
        ttk.Label(sub_frame, text=':').grid(row=0, column=4)
        self.proxy_port = tk.StringVar()
        self.proxy_port_txt = ttk.Entry(sub_frame, textvariable=self.proxy_port, width=6, state='disabled')
        self.proxy_port_txt.grid(row=0, column=5)

        # Row
        label = ttk.Label(frame, text=tr('Threads num:'))
        label.grid(row=4, column=0, sticky='e')
        self.spin_threads = ttk.Spinbox(
            frame, values=tuple(range(1, MAX_THREAD_LIMIT + 1)), width=15, validate='all'
        )
        self.spin_threads.set(gui_config['thread_num'])
        self.spin_threads.grid(row=4, column=1, sticky='w', padx=10, pady=(3, 0))

        # Row
        frame = ttk.Frame(self.win, padding=(15, 0, 15, 10))
        frame.grid(row=1, column=0, sticky='we')
        frame.grid_columnconfigure(0, weight=1)

        self.manga_info_frame = ttk.LabelFrame(frame, text=tr('Manga Info'), padding=(10, 5, 10, 10))
        self.manga_info_frame.grid(row=1, column=0, sticky='news', padx=(0, 15), pady=0)
        self.manga_info_frame.grid_columnconfigure(1, weight=1)

        ttk.Label(self.manga_info_frame, text=tr('Title:')).grid(row=0, column=0, sticky='e', padx=(0, 5))
        self.manga_title = ttk.Label(self.manga_info_frame, width=60)
        self.manga_title.grid(row=0, column=1, sticky='w')

        ttk.Label(self.manga_info_frame, text=tr('Page num:')).grid(row=1, column=0, sticky='e', padx=(0, 5))
        self.manga_page_num = ttk.Label(self.manga_info_frame, width=10)
        self.manga_page_num.grid(row=1, column=1, sticky='w')

        self.download_option_frame = ttk.LabelFrame(frame, text=tr('Download Options'), padding=(10, 5, 10, 10))
        self.download_option_frame.grid(row=1, column=1, sticky='news')

        ttk.Label(
            self.download_option_frame, text=tr('[Download Options] Range:')
        ).grid(row=0, column=0, sticky='e', padx=(0, 5))
        self.range_option = tk.StringVar(value='all')
        ttk.Radiobutton(
            self.download_option_frame, text=tr('[Download Options] All'), variable=self.range_option, value='all',
            command=self.range_option_clicked,
        ).grid(row=0, column=1)
        ttk.Radiobutton(
            self.download_option_frame, text=tr('[Download Options] Partition'), variable=self.range_option,
            value='part',
            command=self.range_option_clicked,
        ).grid(row=0, column=2)
        ttk.Label(
            self.download_option_frame, text=tr('[Download Options] Pages:')
        ).grid(row=1, column=0, sticky='e', padx=(0, 5))
        self.download_page_range = tk.StringVar()
        self.txt_download_page_range = ttk.Entry(
            self.download_option_frame, textvariable=self.download_page_range, state='disabled')
        self.txt_download_page_range.grid(row=1, column=1, columnspan=2, sticky='we')

        # Row
        frame = ttk.Frame(self.win)
        frame.grid(row=2, column=0, sticky='we', padx=15, pady=0)
        frame.grid_columnconfigure(0, weight=1)

        self.progress_indicator = tk.IntVar()
        progress_bar = ttk.Progressbar(
            frame, mode='determinate', orient=tk.HORIZONTAL, variable=self.progress_indicator)
        progress_bar.grid(row=0, column=0, sticky='news', pady=1, padx=(0, 10))
        self.fetch_btn = ttk.Button(frame, text=tr('Fetch'), command=self.fetch_btn_clicked)
        self.fetch_btn.grid(row=0, column=1, padx=(0, 5))
        self.download_btn = ttk.Button(frame, text=tr('Download'), state='disabled', command=self.download_btn_clicked)
        self.download_btn.grid(row=0, column=2, padx=(0, 5))
        self.cancel_btn = ttk.Button(frame, text=tr('Cancel'), state='disabled', command=self.cancel_btn_clicked)
        self.cancel_btn.grid(row=0, column=3)

        self.scroll_text = ScrolledText(self.win, height=10, state='disabled')
        self.scroll_text.grid(row=3, column=0, sticky='news', padx=15, pady=(10, 15))

        self.win.grid_rowconfigure(3, weight=1)

        # >>> Initialize logging system <<<
        self.scroll_text.tag_config('verbose', foreground='#808080')
        self.scroll_text.tag_config('info', foreground='#449944')
        self.scroll_text.tag_config('error', foreground='#e25252')

        # Initial log, to solve the `Invalid index` issue
        self.scroll_text.insert(tk.INSERT, tr('Welcome to use the downloader.'), 'verbose')
Ejemplo n.º 53
0
    top.wm_title("Help")
    top.minsize(200,200)
    top.geometry("550x300")
    text=Text(top,bg='white')
    text.insert('1.0',"Welcome \n1) On the Menubar you can find file menu.\n\tNew :Open a new file\n\tNew Window :Open a new Notepad application\n\tOpen :Select and open a new txt file\n\tSave/Save As :Save the txt file\n\n2) On edit menu:\nU can operate the function with key notations also\n\n3) On format menu,U can find Word Warp and Fonts.Select the Font-style,size..etc\nClick on Apply to apply the fonts to sample text and click on OK")
    text.place(relx = 0.05,rely = 0.1,relwidth =0.9,relheight =0.6)


# The notepad design
root=tk.Tk()
root.geometry('600x600')
root.title('Simple Notepade')
root.iconphoto(True, PhotoImage(file=os.path.join("/home/krutika/Python_stuff", "Notepad-icon.png")))

# Area for text region
text=ScrolledText(root,width=1000,height=1000,undo=True)
text.place(x=0,y=0)

#Add the menubar with all necessary functions
#File menu
menubar=Menu(root)
filemenu=Menu(menubar,tearoff=0)
filemenu.add_command(label="New",command=new)
filemenu.add_command(label="New Window", command=new_window)
filemenu.add_command(label="Open",command=Open)
filemenu.add_command(label="Save",command=save)
filemenu.add_command(label="Save As" ,command=save_as)
filemenu.add_separator()
filemenu.add_command(label="Exit",command=exit)
menubar.add_cascade(label="File",menu=filemenu,font=('Arial ',11,'bold'))
Ejemplo n.º 54
0
    def __init__(self):
        Screen.__init__(self)
        self.lbl_title = tk.Label(self, text="Add Game", font=TITLE_FONT)
        self.lbl_title.grid(row=0, columnspan=4, sticky="news")

        #Genre entrybox
        self.lbl_search_by = tk.Label(self, text="Genre: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=1, column=0, sticky="news")
        self.ent_genre = tk.Entry(self)
        self.ent_genre.grid(row=1, column=1)
        #Title entrybox
        self.lbl_search_by = tk.Label(self, text="Title: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=2, column=0, sticky="news")
        self.ent_title = tk.Entry(self)
        self.ent_title.grid(row=2, column=1)
        #developer entrybox
        self.lbl_search_by = tk.Label(self,
                                      text="developer: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=3, column=0, sticky="news")
        self.ent_developer = tk.Entry(self)
        self.ent_developer.grid(row=3, column=1)
        #Publisher entrybox
        self.lbl_search_by = tk.Label(self,
                                      text="Publisher: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=4, column=0, sticky="news")
        self.ent_publisher = tk.Entry(self)
        self.ent_publisher.grid(row=4, column=1)
        #Year entrybox
        self.lbl_search_by = tk.Label(self, text="Year: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=5, column=0, sticky="news")
        self.ent_year = tk.Entry(self)
        self.ent_year.grid(row=5, column=1)

        self.lbl_search_by = tk.Label(self,
                                      text="Release Year: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=1, column=2, sticky="news")
        self.ent_release_year = tk.Entry(self)
        self.ent_release_year.grid(row=1, column=3)

        self.lbl_search_by = tk.Label(self, text="Rating: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=2, column=2, sticky="news")
        self.ent_rating = tk.Entry(self)
        self.ent_rating.grid(row=2, column=3)

        self.lbl_search_by = tk.Label(self,
                                      text="Single/Multiplayer: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=3, column=2, sticky="news")
        self.ent_single_multi = tk.Entry(self)
        self.ent_single_multi.grid(row=3, column=3)

        self.lbl_search_by = tk.Label(self, text="Price: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=4, column=2, sticky="news")
        self.ent_price = tk.Entry(self)
        self.ent_price.grid(row=4, column=3)

        self.lbl_search_by = tk.Label(self,
                                      text="Played it?: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=5, column=2, sticky="news")
        self.ent_played = tk.Entry(self)
        self.ent_played.grid(row=5, column=3)

        self.lbl_search_by = tk.Label(self,
                                      text="Purchase Date: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=6, column=0, sticky="news")
        self.ent_purchase_date = tk.Entry(self)
        self.ent_purchase_date.grid(row=6, column=1)

        #Notes Scrolled text box
        self.lbl_search_by = tk.Label(self, text="Notes: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=7, column=0, sticky="news")
        self.notes = ScrolledText(self, height=8, width=40)
        self.notes.grid(row=8, columnspan=3)
        #Cancel Reset Remove Buttons
        self.btn_add = tk.Button(self,
                                 text="Cancel",
                                 font=BUTTON_FONT,
                                 command=self.go_main)
        self.btn_add.grid(row=9, column=0, sticky="news")
        self.btn_add = tk.Button(self,
                                 text="Reset",
                                 font=BUTTON_FONT,
                                 command=self.go_clear)
        self.btn_add.grid(row=9, column=1, sticky="news")
        self.btn_add = tk.Button(self, text="Confirm", font=BUTTON_FONT)
        self.btn_add.grid(row=9, column=2, sticky="news")

        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)
        self.grid_columnconfigure(2, weight=1)
        self.grid_columnconfigure(3, weight=1)
        self.grid_columnconfigure(4, weight=1)
        self.grid_columnconfigure(5, weight=1)
        self.grid_columnconfigure(6, weight=1)
        self.grid_columnconfigure(7, weight=1)
        self.grid_columnconfigure(8, weight=1)
        self.grid_columnconfigure(9, weight=1)
        self.grid_columnconfigure(10, weight=1)
Ejemplo n.º 55
0
class EditTwo(Screen):
    def __init__(self):
        Screen.__init__(self)
        self.edit_key = [0]

        self.lbl_title = tk.Label(self, text="Edit Game", font=TITLE_FONT)
        self.lbl_title.grid(row=0, columnspan=4, sticky="news")
        #Genre entrybox
        self.lbl_search_by = tk.Label(self, text="Genre: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=1, column=0, sticky="news")
        self.ent_genre = tk.Entry(self)
        self.ent_genre.grid(row=1, column=1)
        #Title entrybox
        self.lbl_search_by = tk.Label(self, text="Title: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=2, column=0, sticky="news")
        self.ent_title = tk.Entry(self)
        self.ent_title.grid(row=2, column=1)
        #Decoloper entrybox
        self.lbl_search_by = tk.Label(self,
                                      text="developer: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=3, column=0, sticky="news")
        self.ent_developer = tk.Entry(self)
        self.ent_developer.grid(row=3, column=1)
        #Publisher entrybox
        self.lbl_search_by = tk.Label(self,
                                      text="Publisher: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=4, column=0, sticky="news")
        self.ent_publisher = tk.Entry(self)
        self.ent_publisher.grid(row=4, column=1)
        #Year entrybox
        self.lbl_search_by = tk.Label(self,
                                      text="Platform: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=5, column=0, sticky="news")
        self.ent_platform = tk.Entry(self)
        self.ent_platform.grid(row=5, column=1)

        self.lbl_search_by = tk.Label(self,
                                      text="Release Year: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=1, column=2, sticky="news")
        self.ent_release_year = tk.Entry(self)
        self.ent_release_year.grid(row=1, column=3)

        self.lbl_search_by = tk.Label(self, text="Rating: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=2, column=2, sticky="news")
        self.ent_rating = tk.Entry(self)
        self.ent_rating.grid(row=2, column=3)

        self.lbl_search_by = tk.Label(self,
                                      text="Single/Multiplayer: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=3, column=2, sticky="news")
        self.ent_single_multi = tk.Entry(self)
        self.ent_single_multi.grid(row=3, column=3)

        self.lbl_search_by = tk.Label(self, text="Price: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=4, column=2, sticky="news")
        self.ent_price = tk.Entry(self)
        self.ent_price.grid(row=4, column=3)

        self.lbl_search_by = tk.Label(self,
                                      text="Played it?: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=5, column=2, sticky="news")
        self.ent_played = tk.Entry(self)
        self.ent_played.grid(row=5, column=3)

        self.lbl_search_by = tk.Label(self,
                                      text="Purchase Date: ",
                                      font=BUTTON_FONT)
        self.lbl_search_by.grid(row=6, column=0, sticky="news")
        self.ent_purchase_date = tk.Entry(self)
        self.ent_purchase_date.grid(row=6, column=1)

        #Notes Scrolled text box
        self.lbl_search_by = tk.Label(self, text="Notes: ", font=BUTTON_FONT)
        self.lbl_search_by.grid(row=7, column=0, sticky="news")
        self.results = ScrolledText(self, height=8, width=40)
        self.results.grid(row=8, columnspan=3)

        #Cancel Reset Remove Buttons
        self.btn_add = tk.Button(self,
                                 text="Cancel",
                                 font=BUTTON_FONT,
                                 command=self.go_edit)
        self.btn_add.grid(row=9, column=0, sticky="news")
        self.btn_add = tk.Button(self,
                                 text="Reset",
                                 font=BUTTON_FONT,
                                 command=self.reset)
        self.btn_add.grid(row=9, column=1, sticky="news")
        self.btn_add = tk.Button(self,
                                 text="Confirm",
                                 font=BUTTON_FONT,
                                 command=self.confirm)
        self.btn_add.grid(row=9, column=2, sticky="news")

        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)
        self.grid_columnconfigure(2, weight=1)
        self.grid_columnconfigure(3, weight=1)
        self.grid_columnconfigure(4, weight=1)
        self.grid_columnconfigure(5, weight=1)
        self.grid_columnconfigure(6, weight=1)
        self.grid_columnconfigure(7, weight=1)
        self.grid_columnconfigure(8, weight=1)
        self.grid_columnconfigure(9, weight=1)
        self.grid_columnconfigure(10, weight=1)

    def update(self):
        entry = games[self.edit_key]
        self.ent_genre.delete(0, "end")
        self.ent_genre.insert(0, entry[0])
        self.ent_title.delete(0, "end")
        self.ent_title.insert(0, entry[1])
        self.ent_developer.delete(0, "end")
        self.ent_developer.insert(0, entry[2])
        self.ent_publisher.delete(0, "end")
        self.ent_publisher.insert(0, entry[3])
        self.ent_platform.delete(0, "end")
        self.ent_platform.insert(0, entry[4])
        self.ent_purchase_date.delete(0, "end")
        self.ent_purchase_date.insert(0, entry[5])
        self.ent_release_year.delete(0, "end")
        self.ent_release_year.insert(0, entry[6])
        self.ent_rating.delete(0, "end")
        self.ent_rating.insert(0, entry[7])
        self.ent_single_multi.delete(0, "end")
        self.ent_single_multi.insert(0, entry[8])
        self.ent_price.delete(0, "end")
        self.ent_price.insert(0, entry[9])
        self.ent_played.delete(0, "end")
        self.ent_played.insert(0, entry[10])

    def go_edit(self):
        pop_up = tk.Tk()
        pop_up.title("Edit")
        frm_edit_list = EditGame1(pop_up)
        frm_edit_list.grid(row=0, column=0)

    def reset(self):
        self.update()

    def confirm(self):
        Screen.current = 0
        Screen.switch_frame()
Ejemplo n.º 56
0
class targetDB_gui:
    def __init__(self):
        self.window = tk.Tk()
        dr.get_global_param()
        self.targetDB_path = dr.targetDB

        # ================================================================================ #
        # ============================== WIDGET BUILDING ================================= #
        # ================================================================================ #

        self.title = tk.Label(self.window,
                              height=2,
                              text='TargetDB',
                              bg='#00cc99',
                              font='Helvetica 16 bold')

        self.mode = tk.StringVar()

        self.mode.set('list')
        self.mode_label = tk.Label(self.window,
                                   text='Mode',
                                   relief="raised",
                                   bg='#e6e6e6')
        self.mode_single = tk.Radiobutton(self.window,
                                          text="Single mode",
                                          variable=self.mode,
                                          value='single')
        self.mode_list = tk.Radiobutton(self.window,
                                        text="List mode",
                                        variable=self.mode,
                                        value='list')
        self.mode_spider = tk.Radiobutton(self.window,
                                          text="Spider plot only",
                                          variable=self.mode,
                                          value='spider')

        self.target_input_label = tk.Label(self.window,
                                           text='Targets list',
                                           relief="raised",
                                           bg='#e6e6e6')
        self.message_target = tk.StringVar()
        self.message_target.set(
            """Please enter the list of targets. You can either enter a list of gene names directly from excel or a list of comma separated values (eg. "DYRK1A,CYP3D6")"""
        )
        self.target_message = tk.Message(self.window,
                                         textvariable=self.message_target,
                                         justify="center")
        self.input_text = ScrolledText(self.window)

        self.settings_button = tk.Button(self.window,
                                         text='Settings',
                                         bg='#b7b7b7',
                                         command=self.get_settings,
                                         font='Helvetica 10 bold')
        self.go_button = tk.Button(self.window,
                                   text='Start',
                                   bg='#00cc99',
                                   command=self.launch,
                                   font='Helvetica 12 bold')

        self.close = tk.Button(self.window,
                               text='Exit',
                               fg='red',
                               command=self.window.destroy,
                               font='Helvetica 12 bold')

        # ================================================================================ #
        # =========================== GRID CONSTRUCTION ================================== #
        # ================================================================================ #

        self.title.grid(row=0, column=0, columnspan=4, sticky="ew")
        self.mode_label.grid(row=1, column=0, ipadx=10, pady=10, sticky="w")
        self.mode_single.grid(row=1, column=1, pady=10)
        self.mode_list.grid(row=1, column=2, pady=10)
        self.mode_spider.grid(row=1, column=3, pady=10)

        self.target_input_label.grid(row=3, column=0, ipadx=10, sticky="wne")
        self.target_message.grid(row=4, column=0, rowspan=2, sticky='nw')
        self.settings_button.grid(row=6, column=0, sticky='nwe', ipadx=10)
        self.input_text.grid(row=3, column=1, columnspan=3, rowspan=4)

        self.go_button.grid(row=8,
                            column=1,
                            columnspan=2,
                            sticky="ew",
                            pady=10,
                            padx=10)
        self.close.grid(row=8,
                        column=3,
                        sticky='ew',
                        ipadx=20,
                        pady=10,
                        padx=10)

        # ================================================================================ #
        # =========================== LAUNCHING THE APP ================================== #
        # ================================================================================ #
        self.window.mainloop()

    def get_settings(self):
        self.settings = config_gui(get_only=False)

    def launch(self):
        target_list = self.input_text.get("1.0", tk.END).splitlines()
        mode = self.mode.get()
        target_list = [w.replace(' ', '') for w in target_list]
        target_list = list(filter(None, target_list))
        if len(target_list) == 0:
            showerror(
                'Error',
                'Your list of targets is empty or does not seems to be copy/paste from excel or a comma separated string (eg. DYRK1A,PREP,BACE1,...) '
            )
            return None
        if len(target_list) == 1:
            if ',' in target_list[0]:
                target_list = target_list[0].split(',')
        target_list = list(filter(None, target_list))
        self.gene_df = g2id.gene_to_id(target_list,
                                       targetDB_path=self.targetDB_path)
        message = ''
        if mode == 'list':
            dr.get_list_excel(self.gene_df)
        if mode == 'single':
            for gene_name in self.gene_df.index:
                message += dr.get_single_excel(self.gene_df.loc[gene_name])
            info_message(message)
        if mode == 'spider':
            self.top_spider = tk.Toplevel(self.window)
            self.top_spider.protocol("WM_DELETE_WINDOW", self.closing_top)
            self.top_spider.geometry("600x800")
            self.top_spider.resizable(False, True)

            spider_window = ScrolledFrame(self.top_spider)
            spider_window.pack(expand=True, fill='both')
            # grid_width = 3
            # col = 0
            # row = 0
            for gene_name in self.gene_df.index:
                target_desc = td.get_descriptors_list(
                    self.gene_df.loc[gene_name]['uniprot_ids'][0],
                    targetdb=self.targetDB_path)
                tscore = td.target_scores(target_desc, mode='single')
                target_desc = target_desc.merge(tscore.scores,
                                                on='Target_id',
                                                how='left')
                druggability_pred = dml.predict(ml_model,
                                                tscore.score_components)
                drug_proba = pd.DataFrame(dml.predict_prob(
                    ml_model, tscore.score_components),
                                          columns=ml_model.classes_)
                tscore.scores['Tractable'] = druggability_pred
                tscore.scores['Tractability_probability'] = round(
                    drug_proba[1] * 100, 2)
                tscore.scores['Tractable'] = tscore.scores[
                    'Tractable'].replace({
                        0: 'False',
                        1: 'True'
                    })
                tscore.scores['In_training_set'] = dml.in_training_set(
                    tscore.score_components)
                score_col = [
                    'structure_info_score', 'chemistry_score', 'biology_score',
                    'disease_score', 'genetic_score', 'information_score',
                    'safety_score'
                ]
                target_score = target_desc[score_col] * 10
                target_score.index = target_desc.Target_id
                target_score.fillna(0, inplace=True)
                target_score = target_score.rename(
                    columns={
                        'structure_info_score': 'Structural Biology',
                        'chemistry_score': 'Chemistry',
                        'biology_score': 'Biology',
                        'disease_score': 'Diseases',
                        'genetic_score': 'Genetic Association',
                        'information_score': 'Literature',
                        'safety_score': 'Safety'
                    })
                target_qual = tscore.scores_quality.copy()
                target_qual.set_index('Target_id', inplace=True)
                target_qual = target_qual * 10
                target_qual.fillna(0, inplace=True)
                target_qual = target_qual.rename(
                    columns={
                        'structural_drug_score': 'Structural Biology',
                        'chemistry_qual_score': 'Chemistry',
                        'genetic_score_qual': 'Genetic Association',
                        'safety_qual': 'Safety'
                    })
                self.spider_plot = self.make_spider_plot(
                    target_score.loc[self.gene_df.loc[gene_name]['uniprot_ids']
                                     [0]].values,
                    target_score.columns,
                    target_name=self.gene_df.loc[gene_name]['symbol'])
                self.spider_plot = self.make_spider_plot_v3(
                    target_score.loc[self.gene_df.loc[gene_name]['uniprot_ids']
                                     [0]].values,
                    target_qual.loc[self.gene_df.loc[gene_name]['uniprot_ids']
                                    [0]].to_dict(),
                    target_score.columns,
                    druggability_val=tscore.scores.iloc[0]
                    ['Tractability_probability'],
                    target_name=self.gene_df.loc[gene_name]['symbol'])

                canvas = FigureCanvasTkAgg(self.spider_plot,
                                           master=spider_window.inner)
                canvas.get_tk_widget().pack(expand=True, fill='both')
                # canvas.get_tk_widget().grid(column=col,row=row,sticky='ew')
                # col+=1
                # if col == grid_width:
                #     col = 0
                #     row+=1
                plt.close(self.spider_plot)
            self.window.wait_window(self.top_spider)

    def closing_top(self):
        self.top_spider.destroy()

    def make_spider_plot(self, data, labels, target_name=''):
        fig = plt.figure(figsize=(4, 3))
        ax = fig.add_axes([0, 0, 0.6, 0.8], polar=True)
        ax.spines['polar'].set_visible(False)
        N = len(data)
        bar_width = 2 * np.pi / N
        theta = np.arange(0, 2 * np.pi, 2 * np.pi / N)
        colors = [
            '#95d0fc', '#0485d1', '#b790d4', '#87ae73', '#fec615', '#fb7d07',
            '#95a3a6', '#ccff33'
        ]
        ax.bar(0,
               1,
               bottom=9,
               width=2 * np.pi,
               color='r',
               linewidth=0,
               alpha=0.3)
        ax.bar(0,
               5,
               bottom=4,
               width=2 * np.pi,
               color='lime',
               linewidth=0,
               alpha=0.2)
        ax.bar(0,
               3,
               bottom=1,
               width=2 * np.pi,
               color='gold',
               linewidth=0,
               alpha=0.2)
        ax.bar(0, 1, width=2 * np.pi, color='r', linewidth=0)
        for i in range(len(data)):
            ax.bar(theta[i],
                   data[i],
                   width=bar_width,
                   align='center',
                   label=list(labels)[i],
                   color=colors[i],
                   edgecolor='black',
                   linewidth=1.5)
        plt.title(target_name, weight='bold', fontsize=14)
        ax.set_xticks(theta)
        x_labels = [''] * len(theta)
        ax.set_xticklabels(x_labels)
        ax.yaxis.grid(True)
        ax.xaxis.grid(False)
        fig.legend(loc=7, fontsize=10, fancybox=True, markerscale=1.2)
        ax.set_yticks([])
        return fig

    def make_spider_plot_v3(self,
                            data,
                            data_qual,
                            labels,
                            druggability_val=0,
                            target_name=''):
        fig = plt.figure(figsize=(5, 3))
        ax = fig.add_axes([0, 0, 0.6, 0.8], polar=True)
        ax.spines['polar'].set_visible(False)
        N = len(data)
        bar_width = 2 * np.pi / N - 0.15
        theta = np.arange(0 * np.pi, 2 * np.pi, 2 * np.pi / N)
        theta = np.roll(theta, 4)
        #colors = ['#0c00ed', '#aa00ff', '#cc7700', '#1e7347', '#634100', '#5e5e5e', '#ab000b']
        colors = [
            '#5c88ed', '#b56dd6', '#6bcf67', '#f0ed37', '#f08522', '#7a7a7a',
            '#d41c1c'
        ]
        # ax.bar(0, 1, bottom=9, width=2 * np.pi, color='r', linewidth=0, alpha=0.3)
        # ax.bar(0, 5, bottom=4, width=2 * np.pi, color='lime', linewidth=0, alpha=0.2)
        # ax.bar(0, 3, bottom=1, width=2 * np.pi, color='gold', linewidth=0, alpha=0.2)
        # ax.bar(0, 1, bottom=0, width=2 * np.pi,alpha=0.2,color='red', linewidth=0)
        ax.bar(0,
               0.3,
               bottom=13,
               width=2 * np.pi,
               alpha=1,
               color='black',
               linewidth=0)
        ax.bar(0,
               3,
               width=2 * np.pi,
               alpha=1,
               color=get_green_red_grad(druggability_val, 0, 100),
               linewidth=0)
        value = '%2d%%' % druggability_val
        ax.text(1.1 * np.pi, 0.7 * np.pi, value, weight='bold', size='large')
        for i in reversed(range(len(data))):
            if list(labels)[i] in [
                    'Safety', 'Structural Biology', 'Chemistry',
                    'Genetic Association'
            ]:
                color_to_use = get_green_red_grad(data_qual[list(labels)[i]],
                                                  0, 10)
            else:
                color_to_use = '#d1d1d1'
            # ax.bar(theta[i], data[i],bottom=3, width=bar_width, align='center', color=color_to_use)
            ax.bar(theta[i],
                   data[i],
                   bottom=3,
                   width=bar_width,
                   align='center',
                   color=color_to_use,
                   label=list(labels)[i],
                   edgecolor=colors[i],
                   linewidth=4)

        plt.title(target_name, weight='bold', fontsize=14)
        ax.set_xticks(theta)
        x_labels = [''] * len(theta)
        ax.set_xticklabels(x_labels)
        ax.yaxis.grid(True)
        ax.xaxis.grid(False)
        fig.legend(loc=7, fontsize=10, fancybox=True, markerscale=1.2)
        ax.set_yticks([])
        return fig
Ejemplo n.º 57
0
class EditMenu(Screen):
    def __init__(self):
        Screen.__init__(self)
        self.edit_key = 0
        self.mode_options = ["", "Single Player", "Multi Player", "Either"]
        self.mode_tkvar = tk.StringVar(self)
        self.mode_tkvar.set(self.mode_options[0])

        self.status_options = ["", "Finished", "Unfinished"]
        self.status_tkvar = tk.StringVar(self)
        self.status_tkvar.set(self.status_options[0])

        self.lbl_title = tk.Label(self, text="Edit", font=TITLE_FONT)
        self.lbl_title.grid(row=0, column=0, columnspan=4, sticky="news")

        self.lbl_genre = tk.Label(self, text="Genre:", font=TITLE_FONT)
        self.lbl_genre.grid(row=1, column=0, sticky="news")

        self.ent_genre = tk.Entry(self, font=WIDGET_FONT)
        self.ent_genre.grid(row=1, column=1, sticky="news")

        self.lbl_title = tk.Label(self, text="Title:", font=TITLE_FONT)
        self.lbl_title.grid(row=1, column=2, sticky="news")

        self.ent_title = tk.Entry(self, font=WIDGET_FONT)
        self.ent_title.grid(row=1, column=3, sticky="news")

        self.lbl_dev = tk.Label(self, text="Developer:", font=TITLE_FONT)
        self.lbl_dev.grid(row=2, column=0, sticky="news")

        self.ent_dev = tk.Entry(self, font=WIDGET_FONT)
        self.ent_dev.grid(row=2, column=1, sticky="news")

        self.lbl_pub = tk.Label(self, text="Publisher:", font=TITLE_FONT)
        self.lbl_pub.grid(row=2, column=2, sticky="news")

        self.ent_pub = tk.Entry(self, font=WIDGET_FONT)
        self.ent_pub.grid(row=2, column=3, sticky="news")

        self.lbl_system = tk.Label(self, text="System:", font=TITLE_FONT)
        self.lbl_system.grid(row=3, column=0, sticky="news")

        self.ent_system = tk.Entry(self, font=WIDGET_FONT)
        self.ent_system.grid(row=3, column=1, sticky="news")

        self.lbl_release = tk.Label(self,
                                    text="Release Date:",
                                    font=TITLE_FONT)
        self.lbl_release.grid(row=3, column=2, sticky="news")

        self.ent_release = tk.Entry(self, font=WIDGET_FONT)
        self.ent_release.grid(row=3, column=3, sticky="news")

        self.lbl_rating = tk.Label(self, text="Rating:", font=TITLE_FONT)
        self.lbl_rating.grid(row=4, column=0, sticky="news")

        self.ent_rating = tk.Entry(self, font=WIDGET_FONT)
        self.ent_rating.grid(row=4, column=1, sticky="news")

        self.lbl_mode = tk.Label(self, text="Mode:", font=TITLE_FONT)
        self.lbl_mode.grid(row=4, column=2, sticky="news")

        self.dbx_mode = tk.OptionMenu(self, self.mode_tkvar,
                                      *self.mode_options)
        self.dbx_mode.grid(row=4, column=3, sticky="news")

        self.lbl_price = tk.Label(self, text="Price:", font=TITLE_FONT)
        self.lbl_price.grid(row=5, column=0, sticky="news")

        self.ent_price = tk.Entry(self, font=WIDGET_FONT)
        self.ent_price.grid(row=5, column=1, sticky="news")

        self.lbl_status = tk.Label(self, text="Status:", font=TITLE_FONT)
        self.lbl_status.grid(row=5, column=2, sticky="news")

        self.dbx_status = tk.OptionMenu(self, self.status_tkvar,
                                        *self.status_options)
        self.dbx_status.grid(row=5, column=3, sticky="news")

        self.lbl_purchase = tk.Label(self,
                                     text="Purchase Date:",
                                     font=TITLE_FONT)
        self.lbl_purchase.grid(row=6, column=0, sticky="news")

        self.ent_purchase = tk.Entry(self, font=WIDGET_FONT)
        self.ent_purchase.grid(row=6, column=1, sticky="news")

        self.lbl_notes = tk.Label(self, text="Notes:", font=TITLE_FONT)
        self.lbl_notes.grid(row=7, column=0, sticky="news")

        self.scr_notes = ScrolledText(self,
                                      height=8,
                                      width=40,
                                      font=WIDGET_FONT,
                                      wrap='word')
        self.scr_notes.grid(row=7, column=1, columnspan=2, sticky="news")

        self.frm_editbuttons = EditButtons(self)
        self.frm_editbuttons.grid(row=8, column=1, columnspan=2, sticky="ew")

    def update(self):
        entry = games[self.edit_key]
        self.ent_genre.delete(0, "end")
        self.ent_genre.insert(0, entry[0])
        self.ent_title.delete(0, "end")
        self.ent_title.insert(0, entry[1])
        self.ent_dev.delete(0, "end")
        self.ent_dev.insert(0, entry[2])
        self.ent_pub.delete(0, "end")
        self.ent_pub.insert(0, entry[3])
        self.ent_system.delete(0, "end")
        self.ent_system.insert(0, entry[4])
        self.ent_purchase.delete(0, "end")
        self.ent_purchase.insert(0, entry[10])
        self.ent_price.delete(0, "end")
        self.ent_price.insert(0, entry[8])
        self.ent_release.delete(0, "end")
        self.ent_release.insert(0, entry[5])
        self.ent_rating.delete(0, "end")
        self.ent_rating.insert(0, entry[6])
        self.scr_notes.delete(0.0, "end")
        self.scr_notes.insert(0.0, entry[11])

        if entry[7].lower() == "single player":
            self.mode_tkvar.set(self.mode_options[1])
        elif entry[7].lower() == "multi player":
            self.mode_tkvar.set(self.mode_options[2])
        elif entry[7].lower() == "either":
            self.mode_tkvar.set(self.mode_options[3])
        else:
            self.mode_tkvar.set(self.mode_options[0])

        if entry[9].lower() == "finished":
            self.status_tkvar.set(self.status_options[1])
        elif entry[9].lower() == "unfinished":
            self.status_tkvar.set(self.status_options[2])
        else:
            self.status_tkvar.set(self.status_options[0])
Ejemplo n.º 58
0
    def __init__(self):
        Screen.__init__(self)
        self.mode_options = ["", "Single Player", "Multi Player", "Either"]
        self.mode_tkvar = tk.StringVar(self)
        self.mode_tkvar.set(self.mode_options[0])

        self.status_options = ["", "Finished", "Unfinished"]
        self.status_tkvar = tk.StringVar(self)
        self.status_tkvar.set(self.status_options[0])

        self.lbl_maintitle = tk.Label(self, text="Add", font=TITLE_FONT)
        self.lbl_maintitle.grid(row=0, column=0, columnspan=4, sticky="news")

        self.lbl_genre = tk.Label(self, text="Genre:", font=TITLE_FONT)
        self.lbl_genre.grid(row=1, column=0, sticky="news")

        self.ent_genre = tk.Entry(self, font=WIDGET_FONT)
        self.ent_genre.grid(row=1, column=1, sticky="news")

        self.lbl_title = tk.Label(self, text="Title:", font=TITLE_FONT)
        self.lbl_title.grid(row=1, column=2, sticky="news")

        self.ent_title = tk.Entry(self, font=WIDGET_FONT)
        self.ent_title.grid(row=1, column=3, sticky="news")

        self.lbl_dev = tk.Label(self, text="Developer:", font=TITLE_FONT)
        self.lbl_dev.grid(row=2, column=0, sticky="news")

        self.ent_dev = tk.Entry(self, font=WIDGET_FONT)
        self.ent_dev.grid(row=2, column=1, sticky="news")

        self.lbl_pub = tk.Label(self, text="Publisher:", font=TITLE_FONT)
        self.lbl_pub.grid(row=2, column=2, sticky="news")

        self.ent_pub = tk.Entry(self, font=WIDGET_FONT)
        self.ent_pub.grid(row=2, column=3, sticky="news")

        self.lbl_system = tk.Label(self, text="System:", font=TITLE_FONT)
        self.lbl_system.grid(row=3, column=0, sticky="news")

        self.ent_system = tk.Entry(self, font=WIDGET_FONT)
        self.ent_system.grid(row=3, column=1, sticky="news")

        self.lbl_release = tk.Label(self,
                                    text="Release Date:",
                                    font=TITLE_FONT)
        self.lbl_release.grid(row=3, column=2, sticky="news")

        self.ent_release = tk.Entry(self, font=WIDGET_FONT)
        self.ent_release.grid(row=3, column=3, sticky="news")

        self.lbl_rating = tk.Label(self, text="Rating:", font=TITLE_FONT)
        self.lbl_rating.grid(row=4, column=0, sticky="news")

        self.ent_rating = tk.Entry(self, font=WIDGET_FONT)
        self.ent_rating.grid(row=4, column=1, sticky="news")

        self.lbl_mode = tk.Label(self, text="Mode:", font=TITLE_FONT)
        self.lbl_mode.grid(row=4, column=2, sticky="news")

        self.dbx_mode = tk.OptionMenu(self, self.mode_tkvar,
                                      *self.mode_options)
        self.dbx_mode.grid(row=4, column=3, sticky="news")

        self.lbl_price = tk.Label(self, text="Price:", font=TITLE_FONT)
        self.lbl_price.grid(row=5, column=0, sticky="news")

        self.ent_price = tk.Entry(self, font=WIDGET_FONT)
        self.ent_price.grid(row=5, column=1, sticky="news")

        self.lbl_status = tk.Label(self, text="Status:", font=TITLE_FONT)
        self.lbl_status.grid(row=5, column=2, sticky="news")

        self.dbx_status = tk.OptionMenu(self, self.status_tkvar,
                                        *self.status_options)
        self.dbx_status.grid(row=5, column=3, sticky="news")

        self.lbl_purchase = tk.Label(self,
                                     text="Purchase Date:",
                                     font=TITLE_FONT)
        self.lbl_purchase.grid(row=6, column=0, sticky="news")

        self.ent_purchase = tk.Entry(self, font=WIDGET_FONT)
        self.ent_purchase.grid(row=6, column=1, sticky="news")

        self.lbl_notes = tk.Label(self, text="Notes:", font=TITLE_FONT)
        self.lbl_notes.grid(row=7, column=0, sticky="news")

        self.scr_notes = ScrolledText(self,
                                      height=8,
                                      width=40,
                                      font=WIDGET_FONT,
                                      wrap='word')
        self.scr_notes.grid(row=7, column=1, columnspan=2, sticky="news")

        self.frm_addbuttons = AddButtons(self)
        self.frm_addbuttons.grid(row=8, column=1, columnspan=2, sticky="ew")
Ejemplo n.º 59
0
class SearchMenu(Screen):
    def __init__(self):
        Screen.__init__(self)
        self.search_options = [
            "All", "Genre", "Title", "Developer", "Publisher", "System",
            "Release Date", "Rating", "Mode", "Price", "Status",
            "Purchase Date"
        ]
        self.search_tkvar = tk.StringVar(self)
        self.search_tkvar.set(self.search_options[0])

        self.lbl_title = tk.Label(self, text="Search", font=TITLE_FONT)
        self.lbl_title.grid(row=0, column=0, sticky="news")

        self.lbl_searchby = tk.Label(self, text="Search By:", font=TITLE_FONT)
        self.lbl_searchby.grid(row=1, column=0, sticky="news")

        self.dbx_searchby = tk.OptionMenu(self, self.search_tkvar,
                                          *self.search_options)
        self.dbx_searchby.grid(row=2, column=0, sticky="news")

        self.lbl_searchfor = tk.Label(self,
                                      text="Search For:",
                                      font=TITLE_FONT)
        self.lbl_searchfor.grid(row=3, column=0, sticky="news")

        self.ent_searchfor = tk.Entry(self, font=WIDGET_FONT)
        self.ent_searchfor.grid(row=4, column=0, sticky="news")

        self.frm_printfilters = PrintFilters(self)
        self.frm_printfilters.grid(row=1, column=1, rowspan=4, sticky="news")

        self.scr_results = ScrolledText(self,
                                        height=8,
                                        width=40,
                                        font=WIDGET_FONT,
                                        wrap='word')
        self.scr_results.grid(row=5, column=0, columnspan=2, sticky="news")

        self.frm_searchbuttons = SearchButtons(self)
        self.frm_searchbuttons.grid(row=6, column=1, sticky="news")

        for key in games.keys():
            entry = games[key]
            self.filter_print(entry)

    def filter_print(self, entry):
        if self.frm_printfilters.genre_var.get() == True:
            msg = entry[0] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.title_var.get() == True:
            msg = entry[1] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.dev_var.get() == True:
            msg = entry[2] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.pub_var.get() == True:
            msg = entry[3] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.sys_var.get() == True:
            msg = entry[4] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.purchase_var.get() == True:
            msg = entry[5] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.mode_var.get() == True:
            msg = entry[6] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.price_var.get() == True:
            msg = entry[7] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.release_var.get() == True:
            msg = entry[8] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.status_var.get() == True:
            msg = entry[9] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.rating_var.get() == True:
            msg = entry[10] + "\n"
            self.scr_results.insert("insert", msg)

        if self.frm_printfilters.notes_var.get() == True:
            msg = entry[11] + "\n"
            self.scr_results.insert("insert", msg)

        msg = "**********************\n"
        self.scr_results.insert("insert", msg)
Ejemplo n.º 60
0
class EditorWindow:
    def __init__(self):
        self.root = Tk(className="EDITOR")

        self.python_files = PythonFiles(self)

        self.root.geometry("%dx%d+%d+%d" % (
            self.root.winfo_screenwidth() * 0.5,
            self.root.winfo_screenheight() * 0.4,
            # self.root.winfo_screenwidth() * 0.1, self.root.winfo_screenheight() * 0.1
            0,
            0))

        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

        self.base_title = "PyEditor v%s" % __version__
        self.root.title(self.base_title)

        self.text_frame = Frame(master=self.root)

        self.text = ScrolledText(master=self.root, background="white")
        self.text.bind("<Tab>", self.tab_event)
        self.text.grid(row=0, column=0, sticky=NSEW)

        #TODO: find a right height
        self.exec_output = ScrolledText(master=self.root,
                                        height=10,
                                        state=DISABLED,
                                        background="#dddddd")

        # for information text like load/save/run:
        self.exec_output.tag_config(
            "info",
            foreground="#0000ff",
            #background="#eeeeee"
        )

        self.exec_output.grid(row=1, column=0, sticky=NSEW)

        self.text.focus_set()

        # self.script_list = ScriptList(self)

        p = Percolator(self.text)
        d = ColorDelegator()
        p.insertfilter(d)

        # add statusbar to window
        self.init_statusbar()

        # add menu to window
        self.init_menu()

        # Add special RPi/Minecraft features, if available
        self.rpi = MinecraftSpecials(self)

        if self.rpi.mcpi_available:
            # minecraft is available
            self.set_content(DEFAULT_MCPI_SCRIPT)
            if not self.rpi.is_running:
                self.rpi.startup_minecraft()
        else:
            # no minecraft available
            self.set_content(DEFAULT_SCRIPT)

        self.root.update()

    ###########################################################################
    # Status bar

    FILENAME_LABEL = "filename"

    def get_filename(self):
        filename = self.status_bar.get_textEntry(self.FILENAME_LABEL)
        return filename

    def set_filename(self, filename):
        filename = os.path.split(filename)[-1]
        self.status_bar.set_textEntry(self.FILENAME_LABEL, filename)

    def update_filename(self, event=None):
        filename = self.get_filename()
        if filename and not filename.endswith(".py"):
            filename = "%s.py" % filename
            self.set_filename(filename)

    def init_statusbar(self):
        self.status_bar = MyMultiStatusBar(self.root)
        if sys.platform == "darwin":
            # Insert some padding to avoid obscuring some of the statusbar
            # by the resize widget.
            self.status_bar.set_label('_padding1', '    ', side=RIGHT)
        self.status_bar.grid(row=2, column=0)

        self.text.bind("<<set-line-and-column>>", self.set_line_and_column)
        self.text.event_add("<<set-line-and-column>>", "<KeyRelease>",
                            "<ButtonRelease>")
        self.text.after_idle(self.set_line_and_column)
        self.status_bar.new_textEntry(self.FILENAME_LABEL,
                                      'unnamed.py',
                                      callback=self.update_filename)

    def set_line_and_column(self, event=None):
        line, column = self.text.index(INSERT).split('.')
        self.status_bar.set_label('column', 'Column: %s' % column)
        self.status_bar.set_label('line', 'Line: %s' % line)

    ###########################################################################
    # Menu

    def init_menu(self):
        self.menubar = Menu(self.root)
        filemenu = Menu(self.menubar, tearoff=0)

        self.menubar.add_command(label="Run", command=self.command_run)
        self.menubar.add_command(label="Load", command=self.command_load_file)
        # filemenu.add_command(label="Load", command=self.command_load_file)
        self.menubar.add_command(label="Save", command=self.command_save_file)
        self.menubar.add_command(label="Exit", command=self.root.quit)
        #
        # self.menubar.add_cascade(label="File", menu=filemenu)

        self.root.config(menu=self.menubar)

    def command_run(self):
        source_listing = self.get_content()
        self.exec_output.config(state=NORMAL)
        self.exec_output.delete("1.0", END)
        filename = self.get_filename()
        self.python_files.run_source_listing(source_listing, filename)
        log.debug("Adding to terminal out")
        #self.exec_output.insert(END, "Run Script")
        self.exec_output.config(state=DISABLED)

    def command_load_file(self):
        infile = askopenfile(
            parent=self.root,
            mode="r",
            title="Select a Python file to load",
            filetypes=DEFAULT_FILETYPES,
            initialdir=BASE_PATH,
        )
        if infile is not None:
            source_listing = infile.read()
            infile.close()
            self.set_content(source_listing)

            self.set_filename(infile.name)  # FIXME: insert only name!
            self.append_feedback_to_output("Script %r loaded." % infile.name)

    def command_save_file(self):
        self.update_filename()  # FIXME: add .py if missing

        content = self.get_content()
        filename = self.get_filename()
        filepath = os.path.join(BASE_PATH, filename)

        if os.path.isfile(filepath):
            self.python_files.move_to_backup(filepath)

        with open(filepath, "w") as f:
            f.write(content)

        self.append_feedback_to_output("Save to: %r" % filepath)

    ###########################################################################

    def get_content(self):
        content = self.text.get("1.0", END)
        content = content.strip()
        return content

    def set_content(self, source_listing):
        self.text.delete("1.0", END)

        log.critical("insert %i Bytes listing.", len(source_listing))
        self.text.insert(END, source_listing)

        self.text.mark_set(INSERT, '1.0')  # Set cursor at start
        self.text.focus()

    def append_exec_output(self, text):
        self.exec_output.config(state=NORMAL)
        self.exec_output.insert(END, text)
        self.exec_output.config(state=DISABLED)

    def append_feedback_to_output(self, text):
        text = "%s\n" % text.rstrip()
        self.exec_output.config(state=NORMAL)
        self.exec_output.insert(END, text, "info")
        self.exec_output.config(state=DISABLED)

    ###########################################################################

    indent_pad = " " * 4

    def tab_event(self, event):
        log.debug("Tab event")
        self.text.insert("insert", self.indent_pad)
        return BREAK