Ejemplo n.º 1
0
class BMI(Frame):
    'Body Mass Index app'
    def __init__(self,parent=None):
        'constructor'
        Frame.__init__(self, parent)
        self.grid()
        BMI.make_widgets(self)

    def make_widgets(self):
        'defines BMI widgets'
        Label(self,text='Enter your height: ').grid(row=0,column=0)
        self.htEnt=Entry(self)
        self.htEnt.grid(row=0,column=1)
        Label(self,text='Enter your weight: ').grid(row=1,column=0)
        self.wtEnt=Entry(self)
        self.wtEnt.grid(row=1,column=1)
        Button(self,text='Compute BMI',command=self.compute).grid(row=2,column=0,columnspan=2)

    def compute(self):
        'the handler for button "Compute BMI"'
        try:
            hgt=eval(self.htEnt.get())
            wgt=eval(self.wtEnt.get())
            res=wgt*703/hgt**2
            showinfo(title='Result',message='Your BMI is {}'.format(res))
        except:
            showinfo(title='Ooops!',message='Invalid number!')
        self.wtEnt.delete(0,END)
        self.htEnt.delete(0,END)
Ejemplo n.º 2
0
    def show_captcha(self,img_file):
        dialogRoot = Tk()
        dialogRoot.title("Input text.")
    
        img = PhotoImage(file=img_file)
    
        frame = Frame(dialogRoot)
    
        imal = Label(frame, image=img)
        imal.pack()
    
        label = Label(frame)
        label['text'] = "Your Input:"
        label.pack(side=LEFT)
    
        inputEntry = Entry(frame)
        inputEntry["width"] = 50
        inputEntry.pack(side=LEFT)
    
        def getInputText():
            '''callback of button'''
            # global inputEntry, dialogRoot
            if inputEntry.get().strip() == "":
                print("Please enter a message.")
            else:
                self.captcha_ans = inputEntry.get().strip()
                dialogRoot.destroy()

    
        button = Button(frame, text="Submit", command=getInputText)
        button.pack(side=LEFT)
    
        frame.pack()
        dialogRoot.mainloop()
Ejemplo n.º 3
0
 def __init__(self, master):
     """
     Establish the GUI of this popup
     """
     BuilderPopup.__init__(self, master)
     self.top_left = complex(0, 0)
     self.bottom_right = complex(0, 0)
     self.lines = 0
     self.top_left_label = Label(self.top, text="\"Top Left\"")
     self.top_left_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.bottom_right_label = Label(self.top, text="\"Bottom Right\"")
     self.bottom_right_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.resolution_label = Label(self.top, text="Lines")
     self.resolution_entry = Entry(self.top, width=5)
     self.build_grid_submit = Button(self.top, text="Build!", command=self.cleanup)
     self.top.bind("<Return>", self.cleanup)
     self.top_left_label.grid(row=0, column=0)
     self.top_left_entry.grid(row=0, column=1)
     self.bottom_right_label.grid(row=1, column=0)
     self.bottom_right_entry.grid(row=1, column=1)
     self.resolution_label.grid(row=2, column=0)
     self.resolution_entry.grid(row=2, column=1)
     self.build_grid_submit.grid(row=3, column=0, columnspan=2)
     self.top_left_entry.focus()
     self.data = (0, 0, 0)
	def ingresarUsuario(cls):
		
		cls.nombre=""
		
		def salir():
			root.quit()
	
		def cargarArchivo():
			cls.nombre=a.get()
			root.destroy()
	
		def obtenerN():
			n=a.get()
			return (n)
		
		root = Tk()
		root.title('CargarDatos')
		a = StringVar()
		atxt = Entry(root, textvariable=a,width=20)
		cargar = Button(root, text="Cargar Archivo", command=cargarArchivo,width=15)
		salirB= Button(root, text ="Salir", command=root.destroy, width=10)
		atxt.grid(row=0, column=0)
		cargar.grid(row=1, column=0)
		salirB.grid(row=1,column=1)
		root.mainloop()
		return (obtenerN())
Ejemplo n.º 5
0
    def initInterfaceZone(self):
        # Draw the play, step and loading buttons
        self.interfaceFrame = Frame(self, background="dark gray")
        self.playFrame = Frame(self.interfaceFrame, background="dark gray")
        self.loadFrame = Frame(self.interfaceFrame, background="dark gray")

        self.isPlaying = False

        #Do the run buttons
        playButton = Button(self.playFrame, text=">", command=self.playPress)
        playButton.grid(row=0,column=0)
        pauseButton = Button(self.playFrame, text="||", command=self.pausePress)
        pauseButton.grid(row=0,column=1)
        stepBackButton = Button(self.playFrame, text="|<", command=self.stepBackPress)
        stepBackButton.grid(row=1,column=0)
        stepForwardButton = Button(self.playFrame, text=">|", command=self.stepForwardPress)
        stepForwardButton.grid(row=1,column=1)

        self.playFrame.pack(side=LEFT, expand=1, fill=BOTH)

        #Do the load-y stuff
        self.boardInputField = Entry(self.loadFrame)
        self.boardInputField.grid(row=0, column=0)
        boardInputButton = Button(self.loadFrame, text="Load Board", command=self.loadBoardPress)
        boardInputButton.grid(row=0, column=1)
        self.moveInputField = Entry(self.loadFrame)
        self.moveInputField.grid(row=1,column=0)
        moveInputButton = Button(self.loadFrame, text="Load Moves", command=self.loadMovesPress)
        moveInputButton.grid(row=1, column=1)

        self.loadFrame.pack(side=LEFT, expand=1, fill=BOTH)

        self.interfaceFrame.pack(side=BOTTOM)
Ejemplo n.º 6
0
class PlusTwo(Frame):
    def __init__(self):
        'the constructor for the GUI'
        Frame.__init__(self)
        self.make_widgets()
        self.pack()
    
    def make_widgets(self):
        'create the widgets for the GUI'
        Label(self, text="Please enter a numeric expression:").pack()

        self.ent = Entry(self)
        self.ent.pack()

        Button(self, text="+2", command=self.addtwo).pack(side=LEFT)
        Button(self, text="Clear", command=lambda: self.ent.delete(0, END)).pack(side=RIGHT)

    # Write this method
    def addtwo(self):
        'the event handler for the +2 button'
        try:
            val=eval(self.ent.get())
            res=val+2
            self.ent.delete(0,END)
            self.ent.insert(END,res)
        except:
            showinfo(title='Error',message='You need to enter numeric values!')
            self.ent.delete(0,END)
	def initialize(self):
		short_label = Label(self, text="Short Name")
		short_label.grid(row=0, column=0, sticky="W", padx=5)

		self.new_short_box = Entry(self, width=10)
		self.new_short_box.focus_set()
		self.new_short_box.grid(row=1, column=0, sticky="W", padx=5)

		item_label = Label(self, text="Item Name")
		item_label.grid(row=0, column=1)

		self.new_item_box = Entry(self, width=40)
		self.new_item_box.grid(row=1, column=1, sticky="EW")

		amount_label = Label(self, text="Amount")
		amount_label.grid(row=0, column=2, sticky="EW")

		self.new_amount_box = Entry(self, width=5)
		self.new_amount_box.grid(row=1, column=2, padx=10, sticky="EW")

		cancel_button = Button(self, text="Cancel", width=10, command=self.cancel)
		self.bind("<Escape>", self.cancel)
		cancel_button.grid(row=3, column=0, pady=10, padx=5, sticky="W")

		ok_button = Button(self, text="OK", width=10, command=self.ok)
		self.bind("<Return>", self.ok)
		ok_button.grid(row=3, column=2, pady=10, sticky="E")

		self.bind("<Return>", self.ok)
		self.bind("<Escape>", self.cancel)
Ejemplo n.º 8
0
class GuiGenerateCount(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.pack()
        
        #step increment len
        self._stepLenFrm  = Frame(self); self._stepLenFrm.pack()
        self._stepLenLbl  = Label(self._stepLenFrm, text="Step Len: ");   self._stepLenLbl.pack(side=LEFT)
        self._stepLenSpin = Spinbox(self._stepLenFrm, from_=0, to=1000); self._stepLenSpin.pack(side=LEFT)
        
        #start value
        self._startFrm  = Frame(self); self._startFrm.pack()
        self._startLbl  = Label(self._startFrm, text="Start Value: ");   self._startLbl.pack(side=LEFT)
        self._startTxt  = Entry(self._startFrm);   self._startTxt.pack(side=LEFT)
        self._startTxt.insert(0, "0")
        
    def getSettings(self):
        return  {   "StepLen":      self._stepLenSpin.get(),
                    "StartValue":   self._startTxt.get()
                }
    
    def getName(self):
        return "Counter"
        
    def getGeneratorFunction(self):
        return generateCounter
Ejemplo n.º 9
0
class Demo(Frame):
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args,**kw)
        self.e=Entry(self, text='Message')
        self.e.delete(0,'end')
        self.e.pack()
        self.makebuttons()        
        self.pack(expand='true',fill='x')

    def makebuttons(self):
        self.b1=Button(self, text="restart",bg="blue",fg='white',command= self.restart )
        self.b1.pack(side='right',fill='both' )
        self.b2=Button(self,text='quit',bg='green',fg='white',command=self.quit)
        self.b2.pack(side='left',fill='both')
        self.lastTime=""
        self.start_timer()
        
    def start_timer(self):
        pass

    def destroy(self):
        self.pack_forget()
    

    def restart(self):
        self.destroy()
        D=Demo(root,bg='purple')
        print ("killed")
        D.__init__(self,root)
        pass
    
    def quit(self):
        root.destroy()
Ejemplo n.º 10
0
 def _general_tabs(self):
     Label(self.frm_general, text=ugettext("Name")).grid(
         row=0, column=0, sticky=(N, W), padx=5, pady=3)
     self.name = Entry(self.frm_general)
     self.name.grid(row=0, column=1, sticky=(N, S, E, W), padx=5, pady=3)
     Label(self.frm_general, text=ugettext("Appli")).grid(
         row=1, column=0, sticky=(N, W), padx=5, pady=3)
     self.applis = ttk.Combobox(
         self.frm_general, textvariable=StringVar(), state=READLONY)
     self.applis.bind("<<ComboboxSelected>>", self.appli_selection)
     self.applis.grid(row=1, column=1, sticky=(N, S, E, W), padx=5, pady=3)
     Label(self.frm_general, text=ugettext("Modules")).grid(
         row=2, column=0, sticky=(N, W), padx=5, pady=3)
     self.modules = Listbox(self.frm_general, selectmode=EXTENDED)
     self.modules.configure(exportselection=False)
     self.modules.grid(row=2, column=1, sticky=(N, S, E, W), padx=5, pady=3)
     Label(self.frm_general, text=ugettext("Language")).grid(
         row=3, column=0, sticky=(N, W), padx=5, pady=3)
     self.language = ttk.Combobox(
         self.frm_general, textvariable=StringVar(), state=READLONY)
     self.language.grid(
         row=3, column=1, sticky=(N, S, E, W), padx=5, pady=3)
     Label(self.frm_general, text=ugettext("CORE-connectmode")
           ).grid(row=4, column=0, sticky=(N, W), padx=5, pady=3)
     self.mode = ttk.Combobox(
         self.frm_general, textvariable=StringVar(), state=READLONY)
     self.mode.bind("<<ComboboxSelected>>", self.mode_selection)
     self.mode.grid(row=4, column=1, sticky=(N, S, E, W), padx=5, pady=3)
     Label(self.frm_general, text=ugettext("Password")).grid(
         row=5, column=0, sticky=(N, W), padx=5, pady=3)
     self.password = Entry(self.frm_general, show="*")
     self.password.grid(
         row=5, column=1, sticky=(N, S, E, W), padx=5, pady=3)
Ejemplo n.º 11
0
 def make_widgets(self):
     'defines Ed widgets'
     self.exp=Entry(self)
     self.exp.grid(row=0,column=0)
     self.res=Entry(self)
     self.res.grid(row=0,column=1)
     Button(self,text='Enter',command=self.evaluate).grid(row=0,column=3)
Ejemplo n.º 12
0
    def draw_setup_screen(self):
        """User setup screen"""
        self.canvas.delete(ALL)
        cx, cy = self.width/2, self.height/2
        text = "Number of Users (1-{})".format(self.max_users)
        font = ("Impact", 24)
        self.canvas.create_text(cx, 0.4*cy, text=text, font=font)
        self.num_users_entry = Entry(self.canvas, justify=CENTER)
        self.canvas.create_window(cx, 0.5*cy, window=self.num_users_entry)
        self.num_users_entry.insert(0, str(self.default_users))

        text = "Number of Coaches"
        self.canvas.create_text(cx, 0.6*cy, text=text, font=font)
        self.num_coaches_entry = Entry(self.canvas, justify=CENTER)
        self.canvas.create_window(cx, 0.7*cy, window=self.num_coaches_entry)
        self.num_coaches_entry.insert(0, str(self.default_coaches))

        text = "Max Number of Students"
        self.canvas.create_text(cx, 0.8*cy, text=text, font=font)
        self.num_students_entry = Entry(self.canvas, justify=CENTER)
        self.canvas.create_window(cx, 0.9*cy, window=self.num_students_entry)
        self.num_students_entry.insert(0, str(self.default_students))

        self.button = Button(cx, 1.5*cy, 0.3*cx, 0.2*cy, "Begin")
        self.button.draw(self.canvas)
Ejemplo n.º 13
0
def ua_win_tk(url, pipe = None):
    from tkinter import Tk, Frame, Label, Entry, StringVar, BOTH, Button, RIGHT
    import sys
    sys.stdout.flush()
    instructions = "Visit the following URL to authorize the application:"
    response = {"x": False}
    root = Tk()
    root.title("oAuth2 Authorization Required")
    webbox = Frame(root)
    instructions = Label(webbox, text = instructions)
    instructions.pack(padx = 5, pady = 5)
    urlstr = StringVar(value = url)
    urlbox = Entry(webbox, textvariable = urlstr, state = "readonly")
    urlbox.pack(padx = 5, pady = 5)
    def open_browser():
        from subprocess import Popen
        p = Popen(["sensible-browser", url])
    browserbutton = Button(webbox, text = "Open in web browser", command = open_browser)
    browserbutton.pack(padx = 5, pady = 5)
    webbox.pack(fill = BOTH, expand = 1)
    if pipe:
        def poll():
            if pipe.poll():
                root.destroy()
                #Mutability ftw... wat
                response["x"] = True
            else:
                root.after(300, poll)
        root.after(300, poll)
    cancelbutton = Button(root, text = "Cancel", command = root.destroy)
    cancelbutton.pack(side = RIGHT, padx = 5, pady = 5)
    root.mainloop()
    return response["x"]
Ejemplo n.º 14
0
    def create_widgets(self):
        """ Login form """

        frame_top = Frame(self, pady=15, padx=15)
        frame_top.pack()

        self.email = StringVar()
        self.email_label = Label(frame_top, text="Email")
        self.email_entry = Entry(frame_top, textvariable=self.email)

        self.password = StringVar()
        self.password_label = Label(frame_top, text="Password")
        self.password_entry = Entry(frame_top,
                                    textvariable=self.password, show='*')

        frame_bottom = Frame(self, pady=15, padx=15)
        frame_bottom.pack()

        self.submit = Button(frame_bottom)
        self.submit["text"] = "Login"
        self.submit["command"] = self.sign_in

        #layout widgets in grid
        self.email_label.grid(row=1, column=0)
        self.email_entry.grid(row=1, column=1)
        self.password_label.grid(row=2, column=0)
        self.password_entry.grid(row=2, column=1)
        self.submit.grid(row=2, column=0)
Ejemplo n.º 15
0
 def __init__(self, master):
     self.top = Toplevel(master)
     self.entry_width = 15
     self.set_none_limits()
     self.real_max_label = Label(self.top, text="Real Max: ")
     self.real_min_label = Label(self.top, text="Real Min: ")
     self.imag_max_label = Label(self.top, text="Imag Max: ")
     self.imag_min_label = Label(self.top, text="Imag Min: ")
     self.real_max_entry = Entry(self.top, width=self.entry_width)
     self.real_min_entry = Entry(self.top, width=self.entry_width)
     self.imag_max_entry = Entry(self.top, width=self.entry_width)
     self.imag_min_entry = Entry(self.top, width=self.entry_width)
     self.submit_button = Button(self.top, text="Submit", command=self.submit)
     self.cancel_button = Button(self.top, text="Cancel", command=self.top.destroy)
     self.real_max_label.grid(row=0, column=0)
     self.real_min_label.grid(row=1, column=0)
     self.imag_max_label.grid(row=2, column=0)
     self.imag_min_label.grid(row=3, column=0)
     self.real_max_entry.grid(row=0, column=1)
     self.real_min_entry.grid(row=1, column=1)
     self.imag_max_entry.grid(row=2, column=1)
     self.imag_min_entry.grid(row=3, column=1)
     self.submit_button.grid(row=4, column=0)
     self.cancel_button.grid(row=4, column=1)
     self.top.bind("<Return>", self.submit)
     self.top.bind("<Escape>", self.top.destroy)
     self.real_max_entry.focus()
Ejemplo n.º 16
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.º 17
0
 def __init__(self, master):
     """
     Establish the GUI of this popup
     """
     BuilderPopup.__init__(self, master)
     self.data = (0, 0, 0)
     self.radius = Label(self.top, text="Radius")
     self.radius_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.n_circles_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.n_circles_label = Label(self.top, text="Number of circles")
     self.center = Label(self.top, text="Center")
     self.center_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.spindles = Label(self.top, text="Number of \"Roots\"")
     self.spindles_entry = Entry(self.top, width=self.width, bd=self.bd)
     self.build_spindle_submit = Button(self.top, text="Build!", command=self.cleanup)
     self.top.bind("<Return>", self.cleanup)
     self.radius.grid(row=0, column=0)
     self.radius_entry.grid(row=0, column=1)
     self.n_circles_label.grid(row=1, column=0)
     self.n_circles_entry.grid(row=1, column=1)
     self.center.grid(row=2, column=0)
     self.center_entry.grid(row=2, column=1)
     self.spindles_entry.grid(row=3, column=1)
     self.spindles.grid(row=3, column=0)
     self.build_spindle_submit.grid(row=4, column=0, columnspan=2)
     self.top_left = 0
     self.bottom_right = 0
     self.radius_entry.focus()
Ejemplo n.º 18
0
class Application(object):

    def __init__(self):
        self.helper = YouDaoHelper()
        self.window = Tk()
        self.window.title(u'知了词典')
        self.window.geometry("280x350+700+300")
        # 输入框
        self.entry = Entry(self.window)
        self.entry.place(x=10, y=10, width=200, height=25)

        # 提交按钮
        self.submit_btn = Button(self.window, text=u'查询', command=self.submit)
        self.submit_btn.place(x=220, y=10, width=50, height=25)

        # 翻译结果标题
        self.title_label = Label(self.window, text=u'翻译结果:')
        self.title_label.place(x=10, y=55)

        # 翻译结果
        self.result_text = Text(self.window, background='#ccc')
        self.result_text.place(x=10, y=75, width=260, height=265)

    def submit(self):
        # 1. 从输入框中获取用户输入的值
        content = self.entry.get()
        # 2. 把这个值发送给有道的服务器,进行翻译
        result = self.helper.crawl(content)
        # 3. 把结果放在底部的Text控件中
        self.result_text.delete(1.0,END)
        self.result_text.insert(END,result)

    def run(self):
        self.window.mainloop()
Ejemplo n.º 19
0
Archivo: tkui.py Proyecto: mindhog/mawb
class ProgramWidget(Frame):

    def __init__(self, parent, client):
        super(ProgramWidget, self).__init__(parent)
        self.client = client
        self.client.onProgramChange = self.programChanged

        self.programLabel = Label(self, text = 'Program:')
        self.programLabel.grid(row = 0, column = 0)
        self.programEntry = Entry(self, text = 'Program name',
                                  state = 'readonly')
        self.programEntry.grid(row = 0, column = 1)
        self.buttonPanel = Frame(self)
        self.buttonPanel.grid(row = 1, column = 0, columnspan = 2, sticky = W)
        self.newButton = Button(self.buttonPanel, text='New',
                                command = self.newProgram)
        self.newButton.pack(side = LEFT)

    def programChanged(self):
        self.__setProgramText(str(self.client.state))

    def __setProgramText(self, text):
        self.programEntry.configure(state = NORMAL)
        self.programEntry.delete(0)
        self.programEntry.insert(0, text)
        self.programEntry.configure(state = 'readonly')

    def newProgram(self):
        self.client.makeNewProgram()
Ejemplo n.º 20
0
class PasswordDialog(Dialog):

    def __init__(self, title, prompt, parent):
        self.prompt = prompt
        Dialog.__init__(self, parent, title)

    def body(self, master):
        from tkinter import Label
        from tkinter import Entry
        from tkinter import Checkbutton
        from tkinter import IntVar
        from tkinter import W

        self.checkVar = IntVar()

        Label(master, text=self.prompt).grid(row=0, sticky=W)

        self.e1 = Entry(master)

        self.e1.grid(row=0, column=1)

        self.cb = Checkbutton(master, text="Save to keychain", variable=self.checkVar)
        self.cb.pack()
        self.cb.grid(row=1, columnspan=2, sticky=W)
        self.e1.configure(show='*')

    def apply(self):
        self.result = (self.e1.get(), self.checkVar.get() == 1)
Ejemplo n.º 21
0
    def guiSetup(self):    # Setups GUI
        self.counter = 0
        self.searched = []
        self.counter2 = 0

        self.f1 = Frame(self.win)  # Top frame
        self.f1.grid(row=0,column=1)

        l1 = Label(self.f1, text = 'Number Search File')
        l1.grid(row=0,column=0)                                 # Search Labels
        l2 = Label(self.f1,text = 'Number Bank File    ')
        l2.grid(row = 1, column = 0)

        self.e1 = Entry(self.f1,state = 'readonly')   # Num Search File Display
        self.e1.grid(row = 0, column =1,columnspan = 6 )

        self.e2 = Entry(self.f1,state = 'readonly')  # Num Bank File Display
        self.e2.grid(row=1,column=1,columnspan = 6)

        self.f2 = Frame(self.win)  # Bottom Frame, holds grid
        self.f2.grid(row = 2, column = 1)

        self.f3 = Frame(self.win, relief = 'raised', border = 4) # Holds num bank numbers
        self.f3.grid(row = 2, column = 2)

        b1 = Button(self.f1,text = 'Select File',command = self.openNSClicked) # Search file open
        b1.grid(row = 0, column = 8)

        b2 = Button(self.f1,text = 'Select File', command=self.openNBClicked)  # Bank file open
        b2.grid(row = 1, column = 8)

        b3 = Button(self.f1,text = 'Generate Number Search',command=self.generate) # generates grid
        b3.grid(row=2,column=0)

        self.functionRan = [False,False] # shows if both files have been selected
Ejemplo n.º 22
0
 def make_entry(self, label, var):
     "Return gridded labeled Entry."
     l = Label(self.top, text=label)
     l.grid(row=self.row, column=0, sticky="nw")
     e = Entry(self.top, textvariable=var, exportselection=0)
     e.grid(row=self.row, column=1, sticky="nwe")
     self.row = self.row + 1
     return e
Ejemplo n.º 23
0
    def __init__(self):

        root = Tk()


        root.title("Calculator")

        self.string = StringVar()
        txtDisplay = Entry(root,textvariable = self.string,insertwidth = 1 , font = "Helvetica 17 bold")
        txtDisplay.grid(row = 0,column = 0,columnspan = 6)
        txtDisplay.focus()



        values = ["7","8","9","/","Clear",
                  "4","5","6","*","<-",
                  "1","2","3","-","=",
                  "0",".","%","+"]


        i = 0
        row = 1
        col = 0

        for txt in values:

            if(i==5):
                row = 2
                col = 0
            if(i==10):
                row = 3
                col = 0
            if(i==15):
                row = 4
                col = 0
            padx = 23
            pady = 23

            if(txt == "="):
                btn = Button(root,height = 2,width = 4,padx = padx,pady =pady,text = txt,
                             command = lambda:self.equals())
                btn.grid(row = row,column = col,columnspan = 2,rowspan = 2,padx = 1,pady =1)
            elif(txt == "<-"):
                btn = Button(root,height = 2,width = 4,padx = 10,pady = 10,text = txt,
                             command = lambda:self.DeleteText())
                btn.grid(row = row,column = col,columnspan = 2,rowspan = 1,padx = 1,pady =1)
            elif(txt == "Clear"):
                btn = Button(root,height = 2,width = 4,padx = 10,pady = 10,text = txt,
                             command = lambda:self.ClearText())
                btn.grid(row = row,column = col,columnspan = 2,rowspan = 1,padx = 1,pady =1)
            else:
                btn = Button (root,height = 2,width = 4,padx = 10,pady = 10,text = txt,
                              command = lambda txt=txt:self.addchar(txt))
                btn.grid(row = row,column = col,padx = 1,pady =1)

            col = col + 1
            i = i + 1
        root.mainloop()
Ejemplo n.º 24
0
class FrameKSPObject(Frame):
    
    
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        frame = Frame(self)
        frame.pack()
        self.string_var0 = StringVar()
        self.string_var1 = StringVar()
        self.int_var = IntVar()
        self.entry0 = Entry(frame, textvariable=self.string_var0)
        self.entry0.pack(side='left')
        Entry(frame, textvariable=self.string_var1).pack(side='left')
        frame = Frame(self)
        frame.pack()
        Button(frame, width=8, text='Accept', command=self.accept).pack(side='left')
        Button(frame, width=8, text='Cancel', command=self.cancel).pack(side='left')
        Button(frame, width=8, text='Delete', command=self.delete).pack(side='left')
        
        
    def populate(self, kspobject):
        self._kspobject = kspobject
        self.string_var0.set(kspobject.name)
        self.string_var1.set(kspobject.value)
        self.int_var.set(kspobject.id_)
        
        
    def accept(self):
        name = self.string_var0.get()
        value = self.string_var1.get()
        id_ = self.int_var.get()
        self.master.master.update_kspobject(name, value, id_)
        self.master.destroy()
    
    
    def cancel(self):
        self.master.destroy()
    
    
    def delete(self):
        id_ = self.int_var.get()
        self.master.master.delete_kspobject(id_)
        self.master.destroy()
        
        
        
        
        
        
        
        
        
        
        
        
        
Ejemplo n.º 25
0
class Calculator:
    def __init__(self, master):
        self.master = master
        master.title("Calculator")

        self.total = 0
        self.entered_number = 0

        self.total_label_text = IntVar()
        self.total_label_text.set(self.total)
        self.total_label = Label(master, textvariable=self.total_label_text)

        self.label = Label(master, text="Total:")

        vcmd = master.register(self.validate)  # we have to wrap the command
        self.entry = Entry(master, validate="key", validatecommand=(vcmd, "%P"))

        self.add_button = Button(master, text="+", command=lambda: self.update("add"))
        self.subtract_button = Button(master, text="-", command=lambda: self.update("subtract"))
        self.multiply_button = Button(master, text="*", command=lambda: self.update("multiply"))
        # self.divide_button = Button(master, text="/", command=lambda: self.update("divide"))
        self.reset_button = Button(master, text="Reset", command=lambda: self.update("reset"))

        # LAYOUT
        self.label.grid(row=0, column=0, sticky=W)
        self.total_label.grid(row=0, column=1, columnspan=2, sticky=E)
        self.entry.grid(row=1, column=0, columnspan=5, sticky=W + E)
        self.add_button.grid(row=2, column=0)
        self.subtract_button.grid(row=2, column=1)
        self.multiply_button.grid(row=2, column=2)
        # self.divide_button.grid(row=2, column=3)
        self.reset_button.grid(row=2, column=4, sticky=W + E)

    def validate(self, new_text):
        if not new_text:  # the field is being cleared
            self.entered_number = 0
        return True

        try:
            self.entered_number = int(new_text)
            return True
        except ValueError:
            return False

    def update(self, method):
        if method == "add":
            self.total += self.entered_number
        elif method == "subtract":
            self.total -= self.entered_number
        elif method == "multiply":
            self.total *= self.entered_number
        elif method == "divide":
            self.total /= self.entered_number
        else:  # reset
            self.total = 0
        self.total_label_text.set(self.total)
        self.entry.delete(0, END)
Ejemplo n.º 26
0
 def make_widgets(self):
     'defines BMI widgets'
     Label(self,text='Enter your height: ').grid(row=0,column=0)
     self.htEnt=Entry(self)
     self.htEnt.grid(row=0,column=1)
     Label(self,text='Enter your weight: ').grid(row=1,column=0)
     self.wtEnt=Entry(self)
     self.wtEnt.grid(row=1,column=1)
     Button(self,text='Compute BMI',command=self.compute).grid(row=2,column=0,columnspan=2)
Ejemplo n.º 27
0
class LayoutDialog(tkSimpleDialog.Dialog):
    def body(self, master):
        Label(master, text="Enter the name of the layout:").grid(row=0)
        self.e1 = Entry(master)
        self.e1.grid(row=0, column=1)
        return self.e1

    def apply(self):
        self.result = self.e1.get()
Ejemplo n.º 28
0
    def __init__(self):

        window = Tk()
        window.title("Calculator")

        self.string = StringVar()
        entry = Entry(window, textvariable=self.string)
        entry.grid(row=0, column=0, columnspan=6)
        entry.focus()

        values= ["7", "8", "9", "/", "Clear", "<-",
                 "4", "5", "6", "*", "(", ")", "1",
                 "2", "3", "-", "=", "0", ".", "%", "+"]

        i=0
        row=1
        col=0
        for txt in values:
            padx=10
            pady=10

            if(i==6):
                row=2
                col=0

            if(i==12):
                row=3
                col=0

            if(i==17):
                col=0
                row=4

            if(txt=="="):
                btn = Button(window, height=2, width=4, padx=23, pady=23, text=txt,
                             command=lambda txt=txt:self.equals())
                btn.grid(row=row, column=col, columnspan=2, rowspan=2, padx=1, pady=1)

            elif(txt=="Clear"):
                btn = Button(window, height=2, width=4, padx=padx, pady=pady, text=txt,
                             command=lambda txt=txt:self.clearTxt())
                btn.grid(row=row, column=col, padx=1, pady=1)

            elif(txt=="<-"):
                btn = Button(window, height=2, width=4, padx=padx, pady=pady, text=txt,
                             command=lambda txt=txt:self.delete())
                btn.grid(row=row, column=col, padx=1, pady=1)

            else:
                btn = Button(window, height=2, width=4, padx=padx, pady=pady, text=txt,
                             command=lambda txt=txt:self.addChar(txt))
                btn.grid(row=row, column=col, padx=1, pady=1)

            col=col+1
            i=i+1

        window.mainloop()
Ejemplo n.º 29
0
class LabelEntry(Frame):
    def __init__(self, tk, name, text, **kwargs):
        super().__init__(tk, **kwargs)
        self.label = Label(self, text=name)
        self.entry = Entry(self, text=text)
        self.label.grid(row=0, column=0)
        self.entry.grid(row=0, column=1)

    def updateText(self, text):
        self.entry.configure(text=text)
Ejemplo n.º 30
0
class GetUrlFrame(Frame):
    def __init__(self, master=None, thread=None):
        Frame.__init__(self, master)
        self.controlThread=thread
        
        self.url=""
        self.urlFilter="rapidgator.net"

        self.grid()
        
        self.createWidgets()
        
        
        
    def createWidgets(self):
        self.inputText = Label(self)
        if self.inputText != None:
            self.inputText["text"] = "URL:"
            self.inputText.grid(row=0, column=0)
        else:
            pass
        
        self.inputField = Entry(self)
        if self.inputField != None:
            self.inputField["width"] = 50
            self.inputField.grid(row=0, column=1, columnspan=6)
        else:
            pass
        
        
        self.submitBtn = Button(self, command=self.clickSubmitBtn)
        if self.submitBtn != None:
            self.submitBtn["text"] = "Submit"
            self.submitBtn.grid(row=0, column=7)
        else:
            pass
        

    def clickSubmitBtn(self):
        if self.urlFilter in self.inputField.get():
            self.url=self.inputField.get()

            self.controlThread.setFileURL(self.url)
            
            self.quit()
            
        else:
            messagebox.showerror(
                        "Url error!",
                        "Not Support host site!"
                                  )
        
        
    def getSubmitURL(self):
        return self.url
class ChatbotApp:
    def __init__(self):
        self.window = Tk()
        self._setup_main_window()

    def run(self):
        self.window.mainloop()

    def _setup_main_window(self):
        self.window.title("Chat With Me :-)")
        self.window.resizable(width=TRUE, height=False)
        self.window.configure(width=470, height=520, bg=BG_COLOR)

        # head label
        head_label = Label(self.window,
                           bg=BG_COLOR,
                           fg=TXT_COLOR,
                           text="Welcome to IntroVerse",
                           font=FONT_BOLD,
                           pady=10)
        head_label.place(relwidth=1)

        # tiny divider
        line = Label(self.window, width=450, bg=BG_GRAY)
        line.place(relwidth=1, rely=0.07, relheight=0.012)

        # text widget
        self.text_widget = Text(self.window,
                                width=20,
                                height=2,
                                bg=BG_COLOR,
                                fg=TXT_COLOR,
                                font=FONT,
                                padx=5,
                                pady=5)
        self.text_widget.place(relheight=0.745, relwidth=1, rely=0.08)
        self.text_widget.configure(cursor="arrow", state=DISABLED)

        # scroll bar
        scrollbar = Scrollbar(self.text_widget)
        scrollbar.place(relheight=1, relx=0.974)
        scrollbar.configure(command=self.text_widget.yview)

        # button label
        button_label = Label(self.window, bg=BG_GRAY, height=80)
        button_label.place(relwidth=1, rely=0.825)

        # message box
        self.msg_entry = Entry(button_label,
                               bg="#2C3E50",
                               fg=TXT_COLOR,
                               font=FONT)
        self.msg_entry.place(relwidth=0.74,
                             relheight=0.03,
                             rely=0.008,
                             relx=0.011)
        self.msg_entry.focus()
        self.msg_entry.bind("<Return>", self._on_enter_pressed)

        # send button
        send_button = Button(button_label,
                             text="Send",
                             font=FONT_BOLD,
                             width=20,
                             bg=BG_GRAY,
                             command=lambda: self._on_enter_pressed(None))
        send_button.place(relx=0.77,
                          rely=0.008,
                          relheight=0.03,
                          relwidth=0.223)

    def _on_enter_pressed(self, event):
        msg = self.msg_entry.get()
        self._insert_message(msg, "You")

    def _insert_message(self, msg, sender):
        if not msg:
            return

        self.msg_entry.delete(0, END)
        msg_1 = f"{ sender }: { msg }\n\n"
        self.text_widget.configure(state=NORMAL)
        self.text_widget.insert(END, msg_1)
        self.text_widget.configure(state=DISABLED)

        msg_2 = f"{ bot_name }: { get_response(msg) }\n\n"
        self.text_widget.configure(state=NORMAL)
        self.text_widget.insert(END, msg_2)
        self.text_widget.configure(state=DISABLED)

        self.text_widget.see(END)
    def _setup_main_window(self):
        self.window.title("Chat With Me :-)")
        self.window.resizable(width=TRUE, height=False)
        self.window.configure(width=470, height=520, bg=BG_COLOR)

        # head label
        head_label = Label(self.window,
                           bg=BG_COLOR,
                           fg=TXT_COLOR,
                           text="Welcome to IntroVerse",
                           font=FONT_BOLD,
                           pady=10)
        head_label.place(relwidth=1)

        # tiny divider
        line = Label(self.window, width=450, bg=BG_GRAY)
        line.place(relwidth=1, rely=0.07, relheight=0.012)

        # text widget
        self.text_widget = Text(self.window,
                                width=20,
                                height=2,
                                bg=BG_COLOR,
                                fg=TXT_COLOR,
                                font=FONT,
                                padx=5,
                                pady=5)
        self.text_widget.place(relheight=0.745, relwidth=1, rely=0.08)
        self.text_widget.configure(cursor="arrow", state=DISABLED)

        # scroll bar
        scrollbar = Scrollbar(self.text_widget)
        scrollbar.place(relheight=1, relx=0.974)
        scrollbar.configure(command=self.text_widget.yview)

        # button label
        button_label = Label(self.window, bg=BG_GRAY, height=80)
        button_label.place(relwidth=1, rely=0.825)

        # message box
        self.msg_entry = Entry(button_label,
                               bg="#2C3E50",
                               fg=TXT_COLOR,
                               font=FONT)
        self.msg_entry.place(relwidth=0.74,
                             relheight=0.03,
                             rely=0.008,
                             relx=0.011)
        self.msg_entry.focus()
        self.msg_entry.bind("<Return>", self._on_enter_pressed)

        # send button
        send_button = Button(button_label,
                             text="Send",
                             font=FONT_BOLD,
                             width=20,
                             bg=BG_GRAY,
                             command=lambda: self._on_enter_pressed(None))
        send_button.place(relx=0.77,
                          rely=0.008,
                          relheight=0.03,
                          relwidth=0.223)
Ejemplo n.º 33
0
class entries(main, verify):
    def __init__(self, root):
        super().__init__(root)
        verify.__init__(self, root)

        self.name1 = Label(root,
                           text='First Name:',
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=80)
        self.name2 = Label(root,
                           text="Second Name:",
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=110)
        self.name3 = Label(root,
                           text="Third Name:",
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=140)
        self.name4 = Label(root,
                           text="Fourth Name:",
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=170)
        self.year = Label(root,
                          text='Year:',
                          bg='#2B2B2B',
                          fg='#B0B9D9',
                          font='bold 10').place(x=10, y=220)
        self.topic = Label(root,
                           text="Topic(s):",
                           bg='#2B2B2B',
                           fg='#F8D8C0',
                           font='bold 10').place(x=10, y=250)
        self.book = Label(root,
                          text="Book(s):",
                          bg='#2B2B2B',
                          fg='#F8D8C0',
                          font='bold 10').place(x=10, y=330)
        self.volume = Label(root,
                            text="Volume(s):",
                            bg='#2B2B2B',
                            fg='#B0D9D9',
                            font='bold 10').place(x=10, y=430)
        self.issue = Label(root,
                           text="Issue(s):",
                           bg='#2B2B2B',
                           fg='#B0D9D9',
                           font='bold 10').place(x=10, y=460)
        self.page = Label(root,
                          text="Page(s)",
                          bg='#2B2B2B',
                          fg='#B0D9D9',
                          font='bold 10').place(x=10, y=490)

        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=85, y=80)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=100, y=110)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=85, y=140)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=95, y=170)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=70, y=250)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=70, y=330)

        vname1 = root.register(self.name1_entry)
        vname2 = root.register(self.name2_entry)
        vname3 = root.register(self.name3_entry)
        vname4 = root.register(self.name4_entry)
        vyear = root.register(self.year_entry)
        vtopic = root.register(self.topic_entry)
        vbook = root.register(self.book_entry)
        vvolume = root.register(self.volume_entry)
        vissue = root.register(self.issue_entry)
        vpage = root.register(self.page_entry)

        self.iname1 = Entry(root,
                            validate="key",
                            validatecommand=(vname1, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname1.place(x=110, y=80)
        self.iname2 = Entry(root,
                            validate="key",
                            validatecommand=(vname2, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname2.place(x=110, y=110)
        self.iname3 = Entry(root,
                            validate="key",
                            validatecommand=(vname3, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname3.place(x=110, y=140)
        self.iname4 = Entry(root,
                            validate="key",
                            validatecommand=(vname4, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname4.place(x=110, y=170)
        self.year = Entry(root,
                          validate="key",
                          validatecommand=(vyear, '%P'),
                          width=20,
                          bg='#3C3F41',
                          fg='yellow',
                          relief=FLAT,
                          highlightbackground='#2B2B2B',
                          highlightthickness=0.5,
                          highlightcolor='black').place(x=90, y=220)
        self.topic = Entry(root,
                           validate="key",
                           validatecommand=(vtopic, '%P'),
                           bg='#3C3F41',
                           fg='yellow',
                           relief=FLAT,
                           highlightbackground='#2B2B2B',
                           highlightthickness=0.5,
                           highlightcolor='black').place(width=304,
                                                         height=70,
                                                         x=90,
                                                         y=250)
        self.book = Entry(root,
                          validate="key",
                          validatecommand=(vbook, '%P'),
                          bg='#3C3F41',
                          fg='yellow',
                          relief=FLAT,
                          highlightbackground='#2B2B2B',
                          highlightthickness=0.5,
                          highlightcolor='black').place(width=304,
                                                        height=70,
                                                        x=90,
                                                        y=330)
        self.volume = Entry(root,
                            validate="key",
                            validatecommand=(vvolume, '%P'),
                            width=20,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black').place(x=90, y=430)
        self.issue = Entry(root,
                           validate="key",
                           validatecommand=(vissue, '%P'),
                           width=20,
                           bg='#3C3F41',
                           fg='yellow',
                           relief=FLAT,
                           highlightbackground='#2B2B2B',
                           highlightthickness=0.5,
                           highlightcolor='black').place(x=90, y=460)
        self.page = Entry(root,
                          validate="key",
                          validatecommand=(vpage, '%P'),
                          width=20,
                          bg='#3C3F41',
                          fg='yellow',
                          relief=FLAT,
                          highlightbackground='#2B2B2B',
                          highlightthickness=0.5,
                          highlightcolor='black').place(x=90, y=490)

        self.verify_name1.config(text='☐')
        self.verify_name2.config(text='☐')
        self.verify_name3.config(text='☐')
        self.verify_name4.config(text='☐')
        self.verify_year.config(text='☐')
        self.verify_volume.config(text='☐')
        self.verify_issue.config(text='☐')
        self.verify_page.config(text='☐')

        self.correctname1 = self.correctname2 = self.correctname3 = self.correctname4 = self.correcttopic = self.correctbook = self.correctyear = self.correctyear = self.correctissue = self.correctpage = ' '

    def name1_entry(self, name1):
        try:
            if name1 != None:
                self.name1 = name1
                if self.et_al == True:
                    self.name2 = self.name3 = self.name4 = None
                self.correctname1 = APA.nameAPA(name1, self.name2, self.name3,
                                                self.name4)

                if self.name1 == '':
                    self.verify_name1.config(text='☐', state=DISABLED)

                else:
                    self.verify_name1.config(text='☑', state=NORMAL)

                if self.correctname1 != ' ':
                    if (self.correcttopic != ' ' or self.correctbook != ' '):
                        main.name_value = self.correctname1
                        self.submitbtn.config(state=NORMAL, relief=RAISED)

                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                print(self.correctname1)
                main.name_value = self.correctname1

                return True
            else:
                return False
        except IndexError:
            self.name1 = None
            return True

    def name2_entry(self, name2):
        try:
            if name2 != None:
                self.name2 = name2
                if self.et_al == True:
                    self.name2 = self.name3 = self.name4 = None
                self.correctname2 = APA.nameAPA(self.name1, name2, self.name3,
                                                self.name4)
                if self.name2 == '':
                    self.verify_name2.config(text='☐', state=DISABLED)

                else:
                    self.verify_name2.config(text='☑', state=NORMAL)

                if self.correctname2 != ' ':
                    if (self.correcttopic != ' ' or self.correctbook != ' '):
                        main.name_value = self.correctname2
                        self.submitbtn.config(state=NORMAL, relief=RAISED)
                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                main.name_value = self.correctname2
                print(self.correctname2)

                return True
            else:
                return False
        except IndexError:
            self.name2 = None
            return True

    def name3_entry(self, name3):
        try:
            if name3 != None:
                self.name3 = name3
                if self.et_al == True:
                    self.name2 = self.name3 = self.name4 = None
                self.correctname3 = APA.nameAPA(self.name1, self.name2, name3,
                                                self.name4)
                if self.name3 == '':
                    self.verify_name3.config(text='☐', state=DISABLED)

                else:
                    self.verify_name3.config(text='☑', state=NORMAL)

                if (self.correcttopic != ' ' and self.correctbook != ' '):
                    main.name_value = self.correctname3
                    self.submitbtn.config(state=NORMAL, relief=RAISED)
                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                main.name_value = self.correctname3
                print(self.correctname3)
                return True
            else:
                return False
        except IndexError:
            self.name3 = None
            return True

    def name4_entry(self, name4):
        try:
            if name4 != None:
                self.name4 = name4
                if self.et_al == True:
                    self.name2 = self.name3 = self.name4 = None
                self.correctname4 = APA.nameAPA(self.name1, self.name2,
                                                self.name3, name4)
                if self.name4 == '':
                    self.verify_name4.config(text='☐', state=DISABLED)

                else:
                    self.verify_name4.config(text='☑', state=NORMAL)

                if (self.correcttopic != ' ' and self.correctbook != ' '):
                    main.name_value = self.correctname4
                    self.submitbtn.config(state=NORMAL, relief=RAISED)

                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                main.name_value = self.correctname4
                print(self.correctname4)
                return True
            else:
                return False
        except IndexError:
            self.name4 = None
            return True

    def year_entry(self, year):
        try:
            if year != None:
                main.year_value = ''
                self.year = year
                self.correctyear = APA.yearAPA(year)
                if self.correctyear == 'Invalid Year':
                    self.verify_year.config(text='☒',
                                            fg='#8B0000',
                                            state=NORMAL)
                else:
                    self.verify_year.config(text='☑', fg='green', state=NORMAL)
                    main.year_value = self.correctyear
                print(self.correctyear)

                self.year = ''
                return True
            else:
                return False
        except IndexError:
            self.verify_year.config(text='☐', state=DISABLED)
            return True

    def topic_entry(self, topic):
        try:
            if topic != None:
                self.topic = topic
                self.correcttopic = APA.topicAPA(topic)
                if self.correcttopic != 'Err(Low)':
                    if (self.correctname1 != ' ' or self.correctname2 != ' '
                            or self.correctname3 != ' '
                            or self.correctname4 != ' '):
                        if self.correctbook != ' ':
                            main.topic_value = self.correcttopic
                            self.submitbtn.config(state=NORMAL, relief=RAISED)
                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                main.topic_value = self.correcttopic
                print(self.correcttopic)

                return True
            else:
                self.submitbtn.config(state=DISABLED)
                return False
        except IndexError:
            self.topic = None
            return True

    def book_entry(self, book):
        try:
            if book != None:
                self.book = book
                self.correctbook = APA.bookAPA(book)
                if self.correctbook != 'Err(Low)':
                    if (self.correctname1 != ' ' or self.correctname2 != ' '
                            or self.correctname3 != ' '
                            or self.correctname4 != ' '
                            and self.correcttopic != ' '):
                        main.book_value = self.correctbook
                        self.submitbtn.config(state=NORMAL, relief=RAISED)
                else:
                    self.submitbtn.config(state=DISABLED, relief=RIDGE)
                main.book_value = self.correctbook
                print(self.correctbook)
                return True
            else:
                return False
        except:
            return True

    def volume_entry(self, volume):
        try:
            if volume != None:
                self.volume = volume
                self.correctvolume = APA.volumeAPA(volume)
                if self.correctvolume == 'Invalid Volume':
                    self.verify_volume.config(text='☒',
                                              fg='#8B0000',
                                              state=NORMAL)
                    main.volume_value = ''
                elif self.correctvolume == '':
                    self.verify_volume.config(text='☐', state=DISABLED)
                    main.volume_value = ''
                else:
                    self.verify_volume.config(text='☑',
                                              fg='green',
                                              state=NORMAL)
                    main.volume_value = self.correctvolume
                print(self.correctvolume)
                return True
            else:
                return False
        except IndexError:
            self.verify_volume.config(text='☐', state=DISABLED)
            return True

    def issue_entry(self, issue):
        try:
            if issue != None:
                self.issue = issue
                self.correctissue = APA.issueAPA(issue)
                if self.correctissue == 'Invalid Issue':
                    self.verify_issue.config(text='☒',
                                             fg='#8B0000',
                                             state=NORMAL)
                    main.issue_value = ''
                elif self.correctissue == '':
                    self.verify_issue.config(text='☐', state=DISABLED)
                    main.issue_value = ''
                else:
                    self.verify_issue.config(text='☑',
                                             fg='green',
                                             state=NORMAL)
                    main.issue_value = self.correctissue
                print(self.correctissue)
                return True
            else:
                return False
        except IndexError:
            return True

    def page_entry(self, page):
        try:
            if page != None:
                self.page = page
                self.correctpage = APA.pageAPA(page)
                if self.correctpage == 'Invalid Page':
                    self.verify_page.config(text='☒',
                                            fg='#8B0000',
                                            state=NORMAL)
                    main.page_value = ''
                elif self.correctpage == '':
                    self.verify_page.config(text='☐', state=DISABLED)
                    main.page_value = ''
                else:
                    self.verify_page.config(text='☑', fg='green', state=NORMAL)
                    main.page_value = self.correctpage
                print(self.correctpage)
                return True
            else:
                return False
        except IndexError:
            return True

    def enter_txt(self):
        if self.et_al == False:
            total_txt = main.name_value + main.year_value + main.topic_value + main.book_value + main.volume_value + main.issue_value + main.page_value + '\n' + '\n'
        elif self.et_al == True:
            total_txt = main.name_value + 'et.al. ' + main.year_value + main.topic_value + main.book_value + main.volume_value + main.issue_value + main.page_value + '\n' + '\n'
        APA_txt.set_txt(total_txt)
        APA_inputs.__init__(root)
        self.savebtn.config(state=NORMAL, relief=RAISED)

    def hide_names(self):

        self.et_al = True
        self.correctname1 = self.correctname2 = self.correctname3 = self.correctname4 = ' '
        self.name1 = self.iname1.get()
        APA_inputs.name1_entry(self.name1)
        self.iname2.config(state=DISABLED, disabledbackground='#4F4B41')
        self.iname3.config(state=DISABLED, disabledbackground='#4F4B41')
        self.iname4.config(state=DISABLED, disabledbackground='#4F4B41')
        self.etal = Checkbutton(root,
                                text='Et.al?',
                                bg='#2B2B2B',
                                fg='orange',
                                font='bold 12',
                                bd=0,
                                activebackground='#2B2B2B',
                                activeforeground='orange',
                                command=lambda: [APA_inputs.show_names()])
        self.etal.select()
        self.etal.place(x=110, y=195)

    def show_names(self):

        self.et_al = False
        self.iname2.config(state=NORMAL)
        self.iname3.config(state=NORMAL)
        self.iname4.config(state=NORMAL)

        self.name1 = self.iname1.get()
        self.name2 = self.iname2.get()
        self.name3 = self.iname3.get()
        self.name4 = self.iname4.get()

        APA_inputs.name1_entry(self.name1)
        APA_inputs.name2_entry(self.name2)
        APA_inputs.name3_entry(self.name3)
        APA_inputs.name4_entry(self.name4)

        self.etal = Checkbutton(root,
                                text='Et.al?',
                                bg='#2B2B2B',
                                fg='orange',
                                font='bold 12',
                                bd=0,
                                activebackground='#2B2B2B',
                                activeforeground='orange',
                                command=lambda: [APA_inputs.hide_names()])
        self.etal.deselect()
        self.etal.place(x=110, y=195)
Ejemplo n.º 34
0
class TestTab(tk.Frame):
    def __init__(self, master, **kw):
        super().__init__(master, **kw)

        self.recorder = Recorder()
        self.dictPath = os.path.dirname(os.path.realpath(__file__))

        self.current_index = 0
        self.sentences = []
        self.init_sentences()

        # Initialize elements
        name_label = Label(self,
                           text="Name (in English)",
                           font="Arial 16 bold")
        self.name = Entry(self,
                          font="Arial 16")
        explanation = Label(self,
                            text="Press on the Record button, read the text out loud and then press it again",
                            font="Arial 16 bold")
        self.record_text = Label(self,
                                 text="Test",
                                 fg="red",
                                 font="Arial 16 bold")
        self.status = Label(self,
                            text="Status: {}\{}".format(self.current_index, len(self.sentences)),
                            font="Arial 16 bold")
        self.record_button = Button(self,
                                    text="התחל להקליט",
                                    command=self.record_clicked,
                                    font="Arial 12 bold",
                                    height=2,
                                    bg=Colors.START)
        self.cancel_button = Button(self, text="בטל הקלטה",
                                    command=self.cancel_clicked,
                                    font="Arial 12 bold",
                                    height=2,
                                    state=tk.DISABLED,
                                    bg=Colors.CANCEL_DISABLED)
        self.process_button = Button(self,
                                     command=self.process_clicked,
                                     text="Process with Kaldi",
                                     font="Arial 12 bold",
                                     height=2,
                                     bg=Colors.PROCESS)

        # Set the current sentence the speaker should say out loud
        self.__set_sentence()

        # Place elements inside the grid
        name_label.grid(row=0, column=0, rowspan=1, columnspan=2, padx=10, pady=5, sticky=tk.W)
        self.name.grid(row=1, column=0, rowspan=1, columnspan=2, padx=10, pady=5, sticky=tk.W)
        explanation.grid(row=2, column=0, rowspan=1, columnspan=2, padx=10, pady=5, sticky=tk.W)
        self.record_text.grid(row=3, column=0, rowspan=1, columnspan=2, padx=30, pady=5, sticky=tk.E)
        self.status.grid(row=4, column=0, rowspan=1, columnspan=2, padx=10, pady=5, sticky=tk.W)
        self.cancel_button.grid(row=5, column=0, padx=10, pady=5, sticky=tk.W + tk.N + tk.E + tk.S)
        self.record_button.grid(row=5, column=1, padx=10, pady=5, sticky=tk.W + tk.N + tk.E + tk.S)
        self.process_button.grid(row=6, column=0, rowspan=1, columnspan=2, padx=10, pady=5,
                                 sticky=tk.W + tk.N + tk.E + tk.S)

    def __set_sentence(self):
        self.record_text["text"] = self.sentences[self.current_index].sentence
        if self.status is not None:
            self.status["text"] = "Status: {}\{}".format(self.current_index, len(self.sentences))

    def init_sentences(self):
        # Iterate over all odd number between 1 and 24 for type 1 sentence
        for i in range(0, 25, 1):
            self.sentences.append(Data("העבר מודול {} לשידור".format(i), "-1-{}".format(i)))

        # Iterate over all even number between 0 and 24 for type 2 sentence
        for i in range(0, 25, 1):
            self.sentences.append(Data("העבר מודול {} להאזנה".format(i), "-2-{}".format(i)))

        # Iterate over all odd number between 1 and 24 for type 3 sentence
        for i in range(0, 25, 1):
            d1, d2, d3, d4 = random.randint(0, 9), random.randint(0, 9), random.randint(0, 9), random.randint(0, 9)
            self.sentences.append(Data("בצע הקצאה במודול {} לערוץ {}, {}, {}, {}".format(i, d1, d2, d3, d4),
                                       "-3-{}-{}-{}-{}-{}".format(i, d1, d2, d3, d4)))

        # Iterate the numbers 1, 2 & 3 for type 4 sentence
        for i in range(1, 4):
            self.sentences.append(Data("עבור לגיבוי {}".format(i), "-4-{}".format(i)))

        # Record 5 times the user saying all numbers between 0 and 24, shuffled each time differently
        for _ in range(5):
            nums = list(range(0, 25))
            random.shuffle(nums)
            nums = [str(num) for num in nums]
            self.sentences.append(Data("➡➡➡ {}".format(", ".join(nums)), "-5-{}".format("-".join(nums))))

    def record_clicked(self):
        if "התחל" in self.record_button["text"]:
            # Change button to its Stop version
            self.record_button["text"] = "סיים הקלטה"
            self.record_button["bg"] = Colors.STOP

            # Start recordings
            self.recorder.startRecording()

            # Enable the Cancel button
            self.cancel_button["state"] = tk.NORMAL
            self.cancel_button["bg"] = Colors.CANCEL
        elif "סיים" in self.record_button["text"]:
            # Change button to its Start version
            self.record_button["text"] = "התחל להקליט"
            self.record_button["bg"] = Colors.START

            # Stop recording
            if not os.path.isdir(os.path.join(self.dictPath, "recordings")):
                os.makedirs(os.path.join(self.dictPath, "recordings"))
            self.recorder.stopRecording(
                os.path.join(self.dictPath, "recordings",
                             self.name.get() + self.sentences[self.current_index].postfix + ".wav"))

            # Disable the Cancel button
            self.cancel_button["state"] = tk.DISABLED
            self.cancel_button["bg"] = Colors.CANCEL_DISABLED

            # Generate a new text for the user to record
            self.current_index += 1
            self.__set_sentence()

    def cancel_clicked(self):
        # Change button to its Start version
        self.record_button["text"] = "התחל להקליט"
        self.record_button["bg"] = Colors.START

        # Disable the Cancel button
        self.cancel_button["state"] = tk.DISABLED
        self.cancel_button["bg"] = Colors.CANCEL_DISABLED

        # Stop recording without saving
        self.recorder.stopRecording("", save=False)

    def process_clicked(self):
        # Clear the training folder
        train_dir = os.path.join(self.dictPath, os.path.pardir, os.path.pardir, os.path.pardir, "digits_audio", "train")
        shutil.rmtree(train_dir)
        os.makedirs(os.path.join(train_dir, self.name.get()))
        print(os.path.join(train_dir, self.name.get()))

        self.process_button["state"] = tk.DISABLED

        logging.info("Copying recordings to the training folder")
        # Move all recordings to the train folder
        for recording in os.listdir(os.path.join(self.dictPath, "recordings")):
            shutil.copy(os.path.join(self.dictPath, "recordings", recording),
                        os.path.join(self.dictPath, os.path.pardir, os.path.pardir, os.path.pardir, "digits_audio",
                                     "train", self.name.get(), recording))

        logging.info("Organizing data")
        subprocess.call(
            ["python {}".format(os.path.join(self.dictPath, os.path.pardir, os.path.pardir, "pre", "organizer.py"))],
            shell=True, start_new_session=True)
        logging.info("Finished organizing data")

        logging.info("Executing Kaldi")
        subprocess.call(["echo {} | sudo -S ./train.sh".format("q1w2e3r4")], shell=True, start_new_session=True)
        logging.info("Finished Kaldi")

        self.process_button["state"] = tk.NORMAL
def pat_screen():
    global pat_address, pat_contact, pat_CT, pat_ID, pat_name, pat_sex
    global rootp,regform,id,name,sex,ct,addr,c1,c2,SUBMIT,menubar,filemenu,back,SEARCH,DELETE,UPDATE
    global copy_of_image, label
    global rootp

    rootp= Toplevel()
    rootp.title("PATIENT FORM")
    rootp.geometry("1920x1080")

    copy_of_image = Image.open("images/hospital.jpeg")
    photo = ImageTk.PhotoImage(copy_of_image)

    label = Label(rootp, image=photo)
    label.place(x=0, y=0, relwidth=1, relheight=1)
    label.bind('<Configure>', resize_image)

    center_frame = Frame(rootp, relief='raised', borderwidth=2)
    # center_frame.pack(fill=None, expand=False)
    center_frame.place(relx=0.22, rely=0.6, anchor=S)

    regform = Label(center_frame, text="PATIENT REGISTRATION FORM", padx=5, pady=5,
                   fg='BLACK', bg='GREY', font="Helvetica 30 bold")
    regform.grid(columnspan=2, padx=5, pady=5) #, sticky=W+E)

    id = Label(center_frame,text="PATIENT ID", font='Helvetica 20 bold ')
    # id.pack(side=LEFT, padx=5, pady=5)
    id.grid(row=1, column=0, padx=5, pady=5, ipadx=5, ipady=5)

    pat_ID = Entry(center_frame)
    pat_ID.grid(row=1, column=1, padx=5, pady=5, ipadx=5, ipady=5)

    name = Label(center_frame,text="PATIENT NAME", font='Helvetica 20 bold ')
    name.grid(row=2, column=0, padx=5, pady=5, ipadx=5, ipady=5)

    pat_name =  Entry(center_frame)
    pat_name.grid(row=2, column=1, padx=5, pady=5, ipadx=5, ipady=5)

    sex= Label(center_frame,text="GENDER", font='Helvetica 20 bold')
    sex.grid(row=3, column=0, padx=5, pady=5, ipadx=5, ipady=5)

    pat_sex= Entry(center_frame)
    pat_sex.grid(row=3, column=1, padx=5, pady=5, ipadx=5, ipady=5)

    addr =  Label(center_frame, text="ADDRESS", font='Helvetica 20 bold')
    addr.grid(row=4, column=0, padx=5, pady=5, ipadx=5, ipady=5)

    pat_address =  Entry(center_frame)
    pat_address.grid(row=4, column=1, padx=5, pady=5, ipadx=5, ipady=5)

    c1 =  Label(center_frame, text="CONTACT NUMBER", font='Helvetica 20 bold')
    c1.grid(row=5, column=0, padx=5, pady=5, ipadx=5, ipady=5)

    pat_contact =  Entry(center_frame)
    pat_contact.grid(row=5, column=1, padx=5, pady=5, ipadx=5, ipady=5)

    ct =  Label(center_frame, text="CONSULTING TEAM / DOCTOR ID", font='Helvetica 20 bold')
    ct.grid(row=6, column=0, padx=5, pady=5, ipadx=5, ipady=5)

    pat_CT =  Entry(center_frame)
    pat_CT.grid(row=6, column=1, padx=5, pady=5, ipadx=5, ipady=5)

    SUBMIT = Button(center_frame, text="  SUBMIT  ",font='Helvetica 20 bold ',
                    command=IN_PAT)
    SUBMIT.grid(row=7, columnspan=2, padx=5, pady=10, ipadx=5, ipady=10)

    back= Button(center_frame,text="<< BACK", font='Helvetica 20 bold ',
                    command=EXO)
    back.grid(row=8, column=0, padx=5, pady=5, ipadx=5, ipady=10)

    SEARCH= Button(center_frame,text="  SEARCH >>  ", font='Helvetica 20 bold ',
                    command=P_display)
    SEARCH.grid(row=8, column=1, padx=5, pady=5, ipadx=5, ipady=10)

    DELETE= Button(center_frame,text="  DELETE  ", font='Helvetica 20 bold ',
                    command=D_display)
    DELETE.grid(row=9, column=0, padx=5, pady=5, ipadx=5, ipady=10)

    UPDATE= Button(center_frame,text="  UPDATE  ", font='Helvetica 20 bold ',
                    command=P_UPDATE)
    UPDATE.grid(row=9, column=1, padx=5, pady=5, ipadx=5, ipady=10)

    pat_list()

    rootp.mainloop()
Ejemplo n.º 36
0
class modifygood:
    def __init__(self):
        self.window = Tk()
        self.mainframe = Frame(self.window)

        self.instructionL = Label(
            self.mainframe,
            text="Please fill in the fields\nwith appropriate values. ")
        self.priceL = Label(self.mainframe, text="Price: ")
        self.quantityL = Label(self.mainframe, text="Quantity: ")
        self.typeL = Label(self.mainframe, text="Type: ")

        self.priceI = Entry(self.mainframe)
        self.quantityI = Entry(self.mainframe)
        self.typeI = Entry(self.mainframe)

        self.okayB = Button(self.mainframe, text="OKAY")
        self.cancelB = Button(self.mainframe,
                              text="CANCEL",
                              command=self.cancel)
        self.mainframe.grid(row=0,
                            column=0,
                            columnspan=2,
                            sticky=W + E + N + S)
        self.mainframe.propagate(0)

        self.instructionL.grid(row=0, column=0, columnspan=2)
        self.priceL.grid(row=1, column=0)
        self.quantityL.grid(row=2, column=0)
        self.typeL.grid(row=3, column=0)

        self.priceI.grid(row=1, column=1)
        self.quantityI.grid(row=2, column=1)
        self.typeI.grid(row=3, column=1)

        self.okayB.grid(row=4, column=0)
        self.okayB.bind("<Button-1>", self.okayE)
        self.cancelB.grid(row=4, column=1)

    def cancel(self):
        self.window.destroy()

    def okayE(self, event):
        removable = False
        cursor = QF.cursor
        info = []
        price = self.priceI.get()
        quantity = self.quantityI.get()

        try:
            if float(price) < 0 or int(quantity) < 0:
                messagebox.showerror(
                    "Error", "the price or quantity cannot be less than zero.")
                self.window.destroy()
            type = self.typeI.get()
            info.append(price)
            info.append(quantity)
            info.append(type)
            good = tuple(info)
            allgoods = QF.showGood(cursor)
            for n in allgoods:
                if type == n[0]:
                    removable = True
            if removable:
                QF.modifyGood(good)
                self.window.destroy()
            else:
                messagebox.showerror("Error", "the item does not exist.")
                self.window.destroy()
        except:
            messagebox.showerror("Error",
                                 "Something is wrong\n Check your input.")
            self.window.destroy()
Ejemplo n.º 37
0
class Interface(Socket):
    def __init__(self):
        Socket.__init__(self)
        self.server = socket(AF_INET, SOCK_STREAM)
        self.connected = False

        self.window = Tk()
        self.window.title('KEO Chat')
        self.window.resizable(width=False, height=False)

        login_frame = Frame(self.window, bd=10)
        login_frame.pack(pady=5, padx=10, fill=X)

        host_label = Label(login_frame, text='Server')
        host_label.grid(row=0, column=0)

        self.host_entry = Entry(login_frame, width=30, justify='center')
        self.host_entry.grid(row=0, column=1)
        self.host_entry.insert(END, '127.0.0.1:5368')

        user_label = Label(login_frame, text='Username')
        user_label.grid(row=1, column=0)

        self.user_entry = Entry(login_frame, width=30, justify='center')
        self.user_entry.grid(row=1, column=1)
        self.user_entry.insert(END, os.environ.get('USER', f'Unknown-{random.randint(1000, 9999)}'))

        self.connect_button = Button(login_frame, text='Connect')
        self.connect_button.grid(row=2, column=1)
        self.connect_button['command'] = self.connect

        frame = Frame(self.window, bd=10)
        frame.pack(pady=5, padx=10, fill=X)

        scroll = Scrollbar(frame)
        self.text = Text(frame, width=50, height=30,
                         highlightcolor=colors['gray'],
                         highlightbackground=colors['gray'],
                         highlightthickness=1)
        self.text.configure(yscrollcommand=scroll.set,
                            state=DISABLED)

        scroll.configure(command=self.text.yview)

        self.text.pack(side=LEFT)
        scroll.pack(side=LEFT, fill=Y)

        self.entry = Entry(self.window)
        self.entry.pack(pady=10, padx=16, fill=X)
        self.entry.bind('<Return>', self.send_message)

    def connect(self):
        host = self.host_entry.get()

        if self.connected:
            self.server.close()  # disconnect
            self.server = socket(AF_INET, SOCK_STREAM)  # reset the connection
            self.connected = False
            self.insert("You disconnected")

            self.connect_button['text'] = 'Connect'
            self.host_entry.configure(background="white")
            self.user_entry.configure(state=NORMAL)

        elif host.count(':') != 1:  # wrong ip format
            self.host_entry.delete(0, END)
            self.host_entry.insert(END, '127.0.0.1:5368')

        else:
            addr, port = host.split(':')

            try:
                if not self.user_entry.get():
                    self.user_entry.insert(END, os.environ.get('USER', f'Unknown-{random.randint(1000, 9999)}'))

                self.server.connect((addr, int(port)))  # connect to server
                self.send(self.server, self.user_entry.get())  # send the username

            except Exception as e:
                self.server = socket(AF_INET, SOCK_STREAM)  # reset the socket object
                self.insert(str(e))
                return

            self.connected = True
            self.connect_button['text'] = 'Disconnect'
            self.insert("You connected")

            self.host_entry.configure(background=colors['green'])
            self.user_entry.configure(state=DISABLED)

            thread = Thread(target=self.listen, daemon=True)  # listen to the server in parallel
            thread.start()

    def listen(self):
        while True:
            try:
                message = self.recv(self.server)
            except error:  # it means the connection is closed
                break

            self.insert(message)

    def insert(self, message):
        self.text.configure(state=NORMAL)
        for line in message.split("\n"):
            self.text.insert(END, time.strftime(f'[%H:%M:%S] {line}\n'))
        self.text.configure(state=DISABLED)  # make the text area disable

    def send_message(self, event):
        message = event.widget.get()
        event.widget.delete(0, END)

        if self.connected:
            self.send(self.server, message)  # send the server the message
            self.insert(f"You: {message}")

        else:
            self.insert('Please connect first!')

    def main(self):
        self.window.mainloop()
        self.server.close()  # after window exit event
Ejemplo n.º 38
0
from tkinter import Tk, Button, Label, Entry
import matplotlib as mpl

root = Tk()

colors = ('red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet')


def make_color_button(color):
    return Button(root, bg=color,
                  command=lambda: get_color(color)).pack(fill='x')


def get_color(color):
    top_label['text'] = color.upper()
    top_entry.delete(0, 'end')
    top_entry.insert('end', mpl.colors.cnames[color])


top_label = Label(root)
top_label.pack()

top_entry = Entry(root, width=30, justify='center')
top_entry.pack()

for color in colors:
    make_color_button(color)

root.mainloop()
Ejemplo n.º 39
0
def text():
    e1 = Entry(root, width=40, bd=3, bg='white', fg='black')
    e1.place(x=30, y=150)
    return e1
Ejemplo n.º 40
0
class Calculator:
    def __init__(self, master):
        self.master = master
        self.numframe = Frame(master=self.master, bg='dark red')
        self.rframe = Frame(master=self.master, bg='light green')
        self.lframe = Frame(master=self.master, bg='light blue')
        # self.scrframe = Frame(master=self.master, bg='navy blue')
        self.entry = Entry(master=self.master,
                           font=('Times New Roman', 16, 'bold'),
                           bg='silver',
                           fg='black',
                           relief='sunken',
                           bd=5)

        self.del_all = Button(self.lframe,
                              text='ON',
                              width=5,
                              height=3,
                              command=self.reset_scr)
        self.del_one = Button(self.lframe,
                              text='DEL',
                              width=5,
                              height=3,
                              command=self.bspace)

        self.num0 = Button(self.numframe,
                           text='0',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('0'))
        self.num1 = Button(self.numframe,
                           text='1',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('1'))
        self.num2 = Button(self.numframe,
                           text='2',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('2'))
        self.num3 = Button(self.numframe,
                           text='3',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('3'))
        self.num4 = Button(self.numframe,
                           text='4',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('4'))
        self.num5 = Button(self.numframe,
                           text='5',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('5'))
        self.num6 = Button(self.numframe,
                           text='6',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('6'))
        self.num7 = Button(self.numframe,
                           text='7',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('7'))
        self.num8 = Button(self.numframe,
                           text='8',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('8'))
        self.num9 = Button(self.numframe,
                           text='9',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('9'))

        self.point = Button(self.numframe,
                            text='.',
                            bg='black',
                            fg='white',
                            width=5,
                            height=3,
                            command=lambda: self.numpress('.'))
        self.eq = Button(self.numframe,
                         text='=',
                         bg='black',
                         fg='white',
                         width=5,
                         height=3,
                         command=self.evaluate)
        self.open_paren = Button(self.lframe,
                                 text='(',
                                 width=5,
                                 height=3,
                                 command=lambda: self.numpress('('))
        self.close_paren = Button(self.lframe,
                                  text=')',
                                  width=5,
                                  height=3,
                                  command=lambda: self.numpress(')'))

        self.minus = Button(self.rframe,
                            text='-',
                            width=5,
                            height=3,
                            command=lambda: self.numpress('-'))
        self.plus = Button(self.rframe,
                           text='+',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('+'))
        self.mult = Button(self.rframe,
                           text='*',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('*'))
        self.div = Button(self.rframe,
                          text='/',
                          width=5,
                          height=3,
                          command=lambda: self.numpress('/'))

    def place_frames(self):
        # frames (invisible containers) for screen and buttons
        self.numframe.grid(row=2,
                           column=1,
                           rowspan=4,
                           columnspan=3,
                           sticky='NSEW',
                           padx=2,
                           pady=2)
        # self.scrframe.grid(row=0, column=0, columnspan=5, sticky='NSEW', padx=2, pady=2)
        self.rframe.grid(row=2,
                         rowspan=4,
                         column=4,
                         sticky='NSEW',
                         padx=2,
                         pady=2)
        self.lframe.grid(row=2,
                         rowspan=4,
                         column=0,
                         sticky='NSEW',
                         padx=2,
                         pady=2)

    def place_entry(self):
        self.entry.grid(row=0,
                        column=0,
                        columnspan=5,
                        sticky='NSEW',
                        padx=2,
                        pady=2)

    def place_buttons(self):
        self.num7.grid(row=2, column=1, pady=2, padx=2)
        self.num8.grid(row=2, column=2, pady=2, padx=2)
        self.num9.grid(row=2, column=3, pady=2, padx=2)
        self.num4.grid(row=3, column=1, pady=2, padx=2)
        self.num5.grid(row=3, column=2, pady=2, padx=2)
        self.num6.grid(row=3, column=3, pady=2, padx=2)
        self.num1.grid(row=4, column=1, pady=2, padx=2)
        self.num2.grid(row=4, column=2, pady=2, padx=2)
        self.num3.grid(row=4, column=3, pady=2, padx=2)
        self.num0.grid(row=5, column=2, pady=2, padx=2)

        self.point.grid(row=5, column=3, pady=2, padx=2)
        self.eq.grid(row=5, column=1, pady=2, padx=2)

        self.plus.grid(row=0, pady=2, padx=2)
        self.minus.grid(row=1, pady=2, padx=2)
        self.mult.grid(row=2, pady=2, padx=2)
        self.div.grid(row=3, pady=2, padx=2)

        self.del_all.grid(row=0, pady=2, padx=2)
        self.del_one.grid(row=1, pady=2, padx=2)
        self.open_paren.grid(row=2, pady=2, padx=2)
        self.close_paren.grid(row=3, pady=2, padx=2)

    def numpress(self, button_entry):
        # if open parenthesis was pressed
        # if len(self.entry.get()) > 0:
        #     # display last input
        #     print(self.entry.get()[len(self.entry.get()) - 1])
        if (button_entry == '(') and (self.entry.get()[len(self.entry.get()) -
                                                       1] == '('):
            # print('Check')
            return None
        elif button_entry == '(' and self.entry.get()[
                len(self.entry.get()) - 1] not in ['*', '/', '+', ')', '-']:
            return self.entry.insert(len(self.entry.get()),
                                     f"* {button_entry}")

        self.entry.insert(len(self.entry.get()), button_entry)

    def evaluate(self):
        result = eval(self.entry.get())
        self.entry.delete(first=0, last='end')
        self.entry.insert(0, result)

    def bspace(self):
        print(len(self.entry.get()))
        self.entry.delete(first=len(self.entry.get()) - 1, last='end')

    def reset_scr(self):
        self.entry.delete(first=0, last='end')
Ejemplo n.º 41
0
    def __init__(self, master):
        self.master = master
        self.numframe = Frame(master=self.master, bg='dark red')
        self.rframe = Frame(master=self.master, bg='light green')
        self.lframe = Frame(master=self.master, bg='light blue')
        # self.scrframe = Frame(master=self.master, bg='navy blue')
        self.entry = Entry(master=self.master,
                           font=('Times New Roman', 16, 'bold'),
                           bg='silver',
                           fg='black',
                           relief='sunken',
                           bd=5)

        self.del_all = Button(self.lframe,
                              text='ON',
                              width=5,
                              height=3,
                              command=self.reset_scr)
        self.del_one = Button(self.lframe,
                              text='DEL',
                              width=5,
                              height=3,
                              command=self.bspace)

        self.num0 = Button(self.numframe,
                           text='0',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('0'))
        self.num1 = Button(self.numframe,
                           text='1',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('1'))
        self.num2 = Button(self.numframe,
                           text='2',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('2'))
        self.num3 = Button(self.numframe,
                           text='3',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('3'))
        self.num4 = Button(self.numframe,
                           text='4',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('4'))
        self.num5 = Button(self.numframe,
                           text='5',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('5'))
        self.num6 = Button(self.numframe,
                           text='6',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('6'))
        self.num7 = Button(self.numframe,
                           text='7',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('7'))
        self.num8 = Button(self.numframe,
                           text='8',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('8'))
        self.num9 = Button(self.numframe,
                           text='9',
                           bg='black',
                           fg='white',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('9'))

        self.point = Button(self.numframe,
                            text='.',
                            bg='black',
                            fg='white',
                            width=5,
                            height=3,
                            command=lambda: self.numpress('.'))
        self.eq = Button(self.numframe,
                         text='=',
                         bg='black',
                         fg='white',
                         width=5,
                         height=3,
                         command=self.evaluate)
        self.open_paren = Button(self.lframe,
                                 text='(',
                                 width=5,
                                 height=3,
                                 command=lambda: self.numpress('('))
        self.close_paren = Button(self.lframe,
                                  text=')',
                                  width=5,
                                  height=3,
                                  command=lambda: self.numpress(')'))

        self.minus = Button(self.rframe,
                            text='-',
                            width=5,
                            height=3,
                            command=lambda: self.numpress('-'))
        self.plus = Button(self.rframe,
                           text='+',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('+'))
        self.mult = Button(self.rframe,
                           text='*',
                           width=5,
                           height=3,
                           command=lambda: self.numpress('*'))
        self.div = Button(self.rframe,
                          text='/',
                          width=5,
                          height=3,
                          command=lambda: self.numpress('/'))
Ejemplo n.º 42
0
from tkinter import Tk, Entry, Button
window = Tk()
window.title("ma calculette")
screen = Entry(window)
screen.grid(column = 0 ,row = 0, columnspan = 3) 

pave_numerique = []
pave_operateur = []

for i in range (0,11):
    if i == 10: 
        pave_numerique.append(Button(window, text = "."))
    else : 
        pave_numerique.append(Button(window, text = i))
    
for i in range (0, 11):
    if i == 0 : 
        pave_numerique[i].grid(column = 1, row = 4)
    elif i == 10:
        pave_numerique[i].grid(column = 0, row = 4)
    else : 
        pave_numerique[i].grid(column = (i-1)%3, row = ((i-1)//3)+1)
    

window.geometry("600x400")
window.mainloop()
Ejemplo n.º 43
0
class Application:
    """The main application GUI Window."""
    def __init__(self, master=None):

        self.master = master
        self.Frame = Frame(self.master)
        try:
            self.config = open(glob(expanduser('~/.flo/*.conf'))[0])
        except:
            messagebox.showerror("Configuration Error",
                                 "Configuration File is corrupt")
        self.LEVEL = {
            1: 'unsatisfactory',
            2: 'satisfactory',
            3: 'meet expectations',
            4: 'Exceed expectations',
            5: 'Exceptional'
        }
        for line in self.config:
            if "rpcuser" in line:
                self.user_id = line[8:-1]
                break

    def main(self):
        """
        Method name: main.

        Method use: The program starts the main GUI of the Rating System.
        """
        try:
            self.IS.destroy()
        except:
            pass
        try:
            self.EM.destroy()
        except:
            pass
        self.MF = Frame(self.master)
        self.MF.pack()
        WelcomeLabel = Label(self.MF,
                             text="Choose who you are ?",
                             font=("Arial", 20))
        WelcomeLabel.grid(column=1, columnspan=2)
        label = Label(self.MF, text=" ")
        label.grid(row=2, columnspan=2)
        ISButton = Button(self.MF, text="Intern", command=self.internWindow)
        ISButton.grid(row=3, column=1)
        EMButton = Button(self.MF,
                          text="Employee",
                          command=self.employeeWindow)
        EMButton.grid(row=3, column=2)
        contentText = "\n\nWhat is this?\nThis app lets us to rate Interns through the FLO blockchain .\n\nThis is a zero knowledge application.\n\nHow to work ?\n\n Choose if you are an Intern or Employeer\n\n" + "An Intern's work would be to enter the Transaction id in the given field and get rating\n\nAn Empolyee must enter the transaction address and write all the intern data to it "
        Context = Message(self.MF, text=contentText)
        Context.grid(column=1, columnspan=2)

    #Intern Section Starts
    def internWindow(self):
        """
        Method Name: internWindow.

        Method use: Provides a GUI for the Intern Application.
        """

        self.MF.destroy()
        self.IS = Frame(self.master)
        self.IS.pack()
        self.tranLBL = Label(self.IS, text="Enter Trasaction id: ")
        self.tranLBL.grid(row=0, column=0, sticky=NSEW, padx=8, pady=8)
        self.TXE = Entry(self.IS)
        self.TXE.grid(row=0, column=1, sticky=NSEW, padx=16, pady=8)
        self.Sub = Button(self.IS,
                          text="Fetch Rating",
                          command=self.ratingResults)
        self.Sub.grid(row=1, columnspan=2, pady=16, padx=16, sticky=NSEW)
        self.LBL = Label(
            self.IS, text="Make a search and results will be displayed here:")
        self.LBL.grid(row=2, columnspan=2)
        self.Text = Text(self.IS, height=20, width=40, state='disabled')
        self.TextScroll = Scrollbar(self.Text, orient=VERTICAL)
        self.Text.config(yscrollcommand=self.TextScroll.set)
        self.TextScroll.config(command=self.Text.yview)
        self.Text.grid(row=3, columnspan=2, padx=16, pady=16)
        self.findMyRating = Button(self.IS,
                                   text="Find My Rating",
                                   command=self.findRating)
        self.findMyRating.grid(row=4, padx=8, pady=8)
        self.BackButton = Button(self.IS, text="Back", command=self.main)
        self.BackButton.grid(row=5, column=0)
        self.QUIT = Button(self.IS, command=self.master.destroy, text="QUIT")
        self.QUIT.grid(row=5, column=1)

    def findRating(self):
        """
        Method name: findRating.

        Method use: Driver to get Intern specific rating from all the ratings.
        """
        for data in self.Text.get("1.0", END).split('\n'):
            if self.user_id in data:
                messagebox.showinfo("Rating Information",
                                    "Your Rating is: \n" + data)
                return

    def ratingResults(self):
        """
        Method name: ratingResults.

        Method use: Driver for Intern Window GUI.
        """

        self.txid = self.TXE.get()
        self.TXE.configure(state="normal")
        self.TXE.insert('end', "Attempting to connect to BlockChain Address")
        self.TXE.configure(state="disabled")
        self.Text.configure(state="normal")
        self.Text.insert('end', "Trying to read Data from Block Chain")
        self.Text.configure(state="disabled")
        try:
            if len(self.txid) == 0:
                messagebox.showwarning('Txid Error',
                                       "Trasaction Id cannot be empty")
                self.TXE.configure(state='normal')
                self.TXE.delete(0, 'end')
                self.Text.configure(state='normal')
                self.Text.delete(1.0, 'end')
                self.Text.configure(state='disabled')
                return
            recv = Transaction.readDatafromBlockchain(self.txid)
        except:
            messagebox.showerror(
                "Error",
                "Make sure FLO Core Wallet is running and the Transaction id is correct"
            )
            self.TXE.configure(state='normal')
            self.TXE.delete(0, 'end')
            self.Text.configure(state='normal')
            self.Text.delete(1.0, 'end')
            self.Text.configure(state='disabled')
            self.IS.destroy()
            self.internWindow()
            return
        pt = bytes.fromhex(recv).decode()
        lines = pt.split('\n')
        self.Text.configure(state="normal")
        self.Text.delete(1.0, 'end')
        for line in lines:
            if line:
                num = line.split()[1]
                num = int(float(num)) + 1
                try:
                    self.Text.insert('1.0',
                                     line + " " + self.LEVEL[num] + "\n")
                except:
                    self.Text.insert('1.0', "INVALID DATA ENTERED\n")
        self.Text.configure(state='disabled')

    #Intern Section Ends Here

    #Employee Section Starts Here

    def employeeWindow(self, text=None):
        """
            Method name: employeeWindow.

            Method use: Provide a GUI for employee Window.

            Positional Arguments:

                Arguement Name: text.
                Argument Use: To provide the neccessary details to the GUI about rating data
                              retrieved from the finalizeRatings method.
        """

        try:
            self.MF.destroy()
            self.RW.destroy()
        except:
            pass
        self.EM = Frame(self.master)
        self.EM.pack()
        self.IDLBL = Label(self.EM, text="Enter the Adress: ")
        self.IDLBL.grid(row=0, column=0, sticky=NSEW, padx=8, pady=8)
        self.TRE = Entry(self.EM)
        self.TRE.grid(row=0, column=1, sticky=NSEW, padx=16, pady=8)
        self.pButton = Button(self.EM,
                              text="Create New Ratings",
                              command=self.createRatings)
        self.pButton.grid(row=2, column=0, pady=16, padx=16)
        self.Sub = Button(self.EM,
                          text="Post Rating",
                          command=self.postResults)
        self.Sub.grid(row=2, column=1, pady=16, padx=16, sticky=NSEW)
        self.LBL = Label(self.EM, text="The rating Data is Here:")
        self.LBL.grid(row=3, columnspan=2)
        self.Text = Text(self.EM, height=20, width=30)
        if text:
            self.Text.insert('1.0', text)
        self.Text.grid(row=4, columnspan=2, padx=16, pady=16)
        self.BackButton = Button(self.EM, text="Back", command=self.main)
        self.BackButton.grid(row=5, column=0)
        self.QUIT = Button(self.EM, command=self.master.destroy, text="QUIT")
        self.QUIT.grid(row=5, column=1)

    def resource_path(self, relative_path):
        """ Get absolute path to resource, works for dev and for PyInstaller """
        try:
            # PyInstaller creates a temp folder and stores path in _MEIPASS
            base_path = sys._MEIPASS
        except Exception:
            base_path = os.path.abspath(".")
        return os.path.join(base_path, relative_path)

    def createRatings(self):
        """
            Method name: createRaNSEWtings.

            Method use: Provides a GUI for the Intern Rating.
        """
        try:
            self.EM.destroy()
        except:
            pass
        DataCenter.checkState()
        self.RW = Frame(self.master)
        self.RW.pack()
        self.IDLBL = Label(
            self.RW,
            text="Intern's Data\n(Sno  Intern Name  Intern User Name)")
        self.IDLBL.grid(row=0, column=1, padx=8, pady=8)
        self.RTLBL = Label(self.RW,
                           text="Rating Data\n( Intern User Name  Rating)")
        self.RTLBL.grid(row=0, column=4, padx=8, pady=8)
        self.IDLB = Listbox(self.RW, width=50, height=20, selectmode=MULTIPLE)
        self.scrollbar = Scrollbar(self.IDLB, orient=VERTICAL)
        self.IDLB.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.IDLB.yview)
        self.populateListBox()
        self.IDLB.grid(row=1, column=1, padx=16, pady=16, sticky=NSEW)
        self.loadImg = PhotoImage(file=self.resource_path("AddBtn.gif"))
        self.remImg = PhotoImage(file=self.resource_path("RenmBtn.gif"))
        self.removeIntern = Button(self.RW,
                                   height=48,
                                   width=48,
                                   image=self.remImg,
                                   command=self.removeData)
        self.removeIntern.grid(row=1, column=2, padx=8, pady=8)
        self.addIntern = Button(self.RW,
                                text="",
                                height=48,
                                width=48,
                                image=self.loadImg,
                                command=self.loadData)
        self.addIntern.grid(row=1, column=3, padx=8, pady=8)
        self.RL = Listbox(self.RW, width=50, height=20, selectmode=MULTIPLE)
        for usr, rat in DataCenter.retrieveRating():
            self.RL.insert(END, usr + " " + str(rat))
        try:
            self.RAT.destroy()
        except:
            pass
        self.RLscroll = Scrollbar(self.RL, orient=VERTICAL)
        self.RL.config(yscrollcommand=self.RLscroll.set)
        self.RLscroll.config(command=self.RL.yview)
        self.RL.grid(row=1, column=4, padx=16, pady=16)
        self.createIntern = Button(self.RW,
                                   text="Add a new Intern",
                                   command=self.newIntern)
        self.createIntern.grid(row=2, column=1, padx=8, pady=4)
        self.DeleteIntern = Button(self.RW,
                                   text="Remove an Existing Intern",
                                   command=self.removeExistingIntern)
        self.DeleteIntern.grid(row=3, column=1, padx=8, pady=4)
        self.finalBtn = Button(self.RW,
                               text="Finalize",
                               command=self.finalizeRatings)
        self.finalBtn.grid(row=3, column=4)

    def newIntern(self):
        """
        Method name: newIntern.

        Method use: GUI for the creation of new Intern
        """

        self.RW.destroy()
        self.NE = Frame(self.master)
        self.NE.pack()
        self.newLBL = Label(self.NE, text="Enter the name: ")
        self.newLBL.grid(row=0, column=0, padx=8, pady=8)
        self.newNMEntry = Entry(self.NE)
        self.newNMEntry.grid(row=0, column=1, padx=8, pady=8)
        self.newUser = Label(self.NE, text="Enter the username: "******"Add Intern", command=self.CIB)
        self.AddBtn.grid(row=2, padx=8, pady=8)

    def finalizeRatings(self):
        """
            Method Name: finalizeRatings.

            Method Use: Format the rating data into desirable format and return back to the
                        Employee Window.
        """

        Rating_Str = ""
        for usr, rat in DataCenter.retrieveRating():
            Rating_Str += usr + " " + str(rat) + "\n"

        if not messagebox.askyesno(
                "Revive Data", "Should you want the rating data to be kept"):
            DataCenter.clearRatings()
        self.RW.destroy()
        self.employeeWindow(text=Rating_Str)

    def CIB(self):
        """
        Method name: CIB.

        Method Use: Driver Code to add a new Intern to the DataBase.
        """
        if len(self.newNMEntry.get()) <= 3 or len(self.newUNMEntry.get()) <= 3:
            messagebox.showwarning(
                "Invalid Length",
                "The Intern Fields are either empty or under 3 charecters")
            return
        else:
            try:
                DataCenter.write(self.newNMEntry.get(), self.newUNMEntry.get())
            except:
                messagebox.showwarning("Invalid Data", "Please Check again")
                return
            messagebox.showinfo("Success", "New Intern Sucessfully added")
            self.NE.destroy()
            self.createRatings()

    def loadData(self, process=None):
        """
        Method name: loadData.

        Method use: GUI to take the Input from the user and load the data to the Rating Data Base.
        """

        self.ratList = []
        self.TMPEN = []
        if process:
            for name, rating in process:
                if float(rating.get()) >= 0 and float(rating.get()) <= 5:
                    DataCenter.insertRating(name, rating.get())
                else:
                    DataCenter.insertRating(name, -1)
            self.createRatings()
            return
        if not self.IDLB.curselection():
            messagebox.showinfo(
                "Empty Selection",
                "Please make sure to select at least one intern")
            return
        for i in self.IDLB.curselection():
            self.ratList.append(self.IDLB.get(i).split(' ')[2])
        self.RW.destroy()
        self.RAT = VerticalScrolledFrame(self.master)
        self.RAT.pack()
        self.LBL = Label(self.RAT.interior,
                         text="Enter a Rating for the selected interns: ")
        self.LBL.pack()
        for item, row in zip(self.ratList, range(1, len(self.ratList) + 1)):
            self.LBx = Label(self.RAT.interior, text=item)
            self.LBx.pack()
            self.TMPEN.append(Entry(self.RAT.interior))
            self.TMPEN[row - 1].pack()
        self.Sub = Button(
            self.RAT.interior,
            command=lambda: self.loadData(zip(self.ratList, self.TMPEN)),
            text="submit")
        self.Sub.pack(pady=8)

    def removeData(self):
        """
        Method Name: removeData.

        Method use: Driver code to remove an Intern's Rating from the DataBase.
        """

        delList = []
        for item in self.RL.curselection():
            delList.append(self.RL.get(item))
            self.RL.delete(item)
        for item in delList:
            DataCenter.removeRating(item.split(' ')[0])

    def populateListBox(self):
        """
        Method Name: populateListBox

        Method use: To Format the rating Data and Fill it into the Intern's List
        """

        try:
            for data in enumerate(DataCenter.readAll(), 1):
                self.IDLB.insert(
                    END,
                    str(data[0]) + " " + str(data[1][0]) + " " +
                    str(data[1][1]))
        except:
            return

    def removeExistingIntern(self):
        """
        Method Name: removeExistingIntern

        Method use: To remove an Existing Intern from the DataBase
        """

        delList = []
        for i in self.IDLB.curselection():
            delList.append(self.IDLB.get(i))
        if messagebox.askyesno(
                "Are you sure to delete ? (This can't be undone)",
                "The following interns data is deleted:\n\n" +
                "\n".join(delList)):
            for item in delList:
                DataCenter.delete(item.split(' ')[2])
        self.RW.destroy()
        self.createRatings()

    def postResults(self):
        """
        Method Name: postResults

        Method use: To post the results on to the Block Chain
        """

        self.addr = self.TRE.get()
        self.ratingData = self.Text.get('1.0', END)
        try:
            if len(self.addr) == 0:
                messagebox.showwarning('Adress Error',
                                       "Trasaction Address cannot be empty")
                self.TRE.configure(state='normal')
                self.TRE.delete(0, 'end')
                self.Text.delete(1.0, 'end')
                return
            elif len(self.ratingData) == 0:
                messagebox.showwarning('Empty Ratings Error',
                                       "Ratings Field cannot be empty")
            hexCoded = self.ratingData.encode()
            hexCoded = hexCoded.hex()
            send = Transaction.writeDatatoBlockchain(hexCoded, self.addr,
                                                     0.003)
            print(send)
            messagebox.showinfo("Transaction Success",
                                "Share this id with your interns:\n" + send)
            f = open("RatingData.txt", "w")
            f.write(send)
            f.close()
        except:
            messagebox.showwarning("NetworkError",
                                   "Make Sure FLO-Core is running")
            self.TRE.configure(state='normal')
            self.TRE.delete(0, 'end')
            self.Text.delete(1.0, 'end')
Ejemplo n.º 44
0
def input_entry(x_coor):  #function for creating entry box in root
    entry = Entry(root, width=17, background='black',
                  foreground='white')  #create the entry box within root
    entry['font'] = helv
    entry.grid(row=x_coor, column=5)  #place the box within root using x_coor
    return entry  #return entry to create entry box
Ejemplo n.º 45
0
    pady = 10
    )
enterLink = Label(
    inputFrame2,
    text='Enter Video Link: ',
    font=("calibri",12,"bold")
    )
enterLink.grid(
    column= 1  ,
    row = 1
    )

videoUrl = StringVar()
inputlink = Entry(
    inputFrame2,
    textvariable = videoUrl,
    width =50
    )
inputlink.grid(
    column= 2 ,
    row = 1
    )

findVideo= Button(
    inputFrame2,
    text = "Find Video Information",
    command = getVideoDetails
    )
findVideo.grid(
    column = 1,
    row =2,
Ejemplo n.º 46
0
 def __init__(self):
     super().__init__()
     font1 = ("helvetica", 12, "bold"
              )  # font designated for larger title text
     font2 = ("helvetica", 8, "bold"
              )  # font designate for smaller descriptory text
     photo = Image.open(
         "paving.png")  # image specified for header of application
     render = ImageTk.PhotoImage(photo)
     picFrame = Frame(self)
     picFrame.pack(
     )  # set image to Frame to properly render and adjust spacing
     self.title_label = Label(picFrame, image=render)
     self.title_label.image = render
     self.title_label.pack()
     self.title_label = Label(
         self,
         text=
         "\n\nPaving Calculation Assistant\n\nUse this tool to perform quick calculations\n\nUse the toggle buttons to select your conversions\n\n"
     )
     self.title_label["bg"] = "PeachPuff"
     self.title_label.configure(font=font1)
     self.title_label.pack()
     frame = Frame(self)
     frame.pack()
     self.button = Button(
         frame, text="Convert(sqft-sqyds)", command=self.convertToYds
     )  # button created to activate convertToYds function
     self.button.configure(font=font2)
     self.button.pack(side="left")
     self.button = Button(
         frame, text="Convert(sqyds-sqft", command=self.convertToFt
     )  # button created to activate convertToFt function
     self.button.configure(font=font2)
     self.button.pack(side="left")
     self.button = Button(
         frame, text="Compute Grade Equivalent", command=self.convertGrade
     )  # button created to activate convertGrade function
     self.button.configure(font=font2)
     self.button.pack(side="left")
     self.button = Button(
         frame,
         text="Click to convert units to standard inches.",
         command=self.convertButton
     )  # button created to activate converToInches function
     self.button.configure(font=font2)
     self.button.pack(side="left")
     self.label = Label(self, text="\n")
     self.label["bg"] = "PeachPuff"
     self.label.pack()
     entryFrame = Frame(self)
     entryFrame.pack()
     self.entry = Entry(entryFrame)
     self.entry.pack()
     self.entry.insert(0, 0)
     self.label = Label(self, text="\n")
     self.label["bg"] = "PeachPuff"
     self.label.pack()
     self.title_label.pack()
     self.title_label = Label(
         self, text="\n\n\nCopyright\n\nNick Pisor\nLakeside Industries")
     self.title_label["bg"] = "PeachPuff"
     self.title_label.pack()
Ejemplo n.º 47
0
    def __init__(self):
        window = Tk()
        window.title('Scientific Calculator')
        window.configure(background="white")
        self.string = StringVar()
        entry = Entry(window, textvariable=self.string)
        entry.grid(row=0, column=0, columnspan=6)
        entry.configure(background="white")
        entry.focus()

        values = [
            "7", "8", "9", "/", "%", "clear", "AC", "4", "5", "6", "*", "(",
            ")", "**", "1", "2", "3", "-", "=", ",", "0", ".", "min", "+",
            "sin", "asin", "cos", "acos", "tan()", "pow", "log10", "max",
            "abs", "floor", "pi", "e", "log", "ceil", "degrees", "radians"
        ]
        text = 1
        i = 0
        row = 1
        col = 0
        for txt in values:
            padx = 10
            pady = 10
            if (i == 7):
                row = 2
                col = 0
            if (i == 14):
                row = 3
                col = 0
            if (i == 19):
                row = 4
                col = 0
            if (i == 26):
                row = 5
                col = 0
            if (i == 33):
                row = 6
                col = 0
            if (txt == '='):
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=70,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.equals())
                btn.grid(row=row, column=col, columnspan=3, padx=2, pady=2)
                btn.configure(background="yellow")

            elif (txt == 'clear'):
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.delete())
                btn.grid(row=row, column=col, padx=1, pady=1)
                btn.configure(background="grey")
            elif (txt == 'AC'):
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.clearall())
                btn.grid(row=row, column=col, padx=1, pady=1)
                btn.configure(background="red")
            else:
                btn = Button(window,
                             height=2,
                             width=4,
                             padx=padx,
                             pady=pady,
                             text=txt,
                             command=lambda txt=txt: self.addChar(txt))
                btn.grid(row=row, column=col, padx=1, pady=1)
                btn.configure(background="cyan")

            col = col + 1
            i = i + 1
        window.mainloop()
Ejemplo n.º 48
0
class DecisionGui:
    def __init__(self, root=Tk()):
        self.root = root
        self.root.title("Decision Experiment")
        self.root.configure(bg=BACKGROUND_COLOR)
        self.titleLabel = Label(self.root,
                                text='Decision Experiment',
                                font=STATUS_FONT,
                                bg=BACKGROUND_COLOR)
        self.ard = None
        self.experiment = None
        self.isConfigLoaded = False
        self.isArdConnected = False
        self.isPumpOn = False
        self.estTime = StringVar()
        self.lickCount = IntVar()
        self.lickCount.set(0)
        self.isSoundOn = BooleanVar()
        self.stopUpdating = threading.Event()
        self.ardUpdater = threading.Thread(target=self.updateVariable)
        port = MouseArduino.getUnoPort()

        #Frames
        self.master = Frame(root, bg=BACKGROUND_COLOR)
        self.master.grid_rowconfigure(0)
        self.master.grid_rowconfigure(1)
        self.master.grid_rowconfigure(2, weight=5)
        self.master.grid_columnconfigure(0, weight=1)
        self.master.grid_columnconfigure(1, weight=1)
        self.master.grid_columnconfigure(2, weight=1)
        self.ardInitFrame = Frame(self.master,
                                  bd=3,
                                  relief='groove',
                                  bg=BACKGROUND_COLOR)
        self.ardControlFrame = Frame(self.master,
                                     bd=3,
                                     relief='groove',
                                     bg=BACKGROUND_COLOR)
        self.initFrame = Frame(self.master,
                               bd=3,
                               relief='groove',
                               bg=BACKGROUND_COLOR)
        self.argFrame = Frame(self.master,
                              bd=3,
                              relief='groove',
                              bg=BACKGROUND_COLOR)
        self.finalControlFrame = Frame(self.master,
                                       bd=3,
                                       relief='groove',
                                       bg=BACKGROUND_COLOR)

        #ardInitFrame
        self.ardInitFrameLabel = Label(self.ardInitFrame,
                                       text="Connect to Hardware",
                                       bg=HEADER_COLOR,
                                       font=LARGE_FONT,
                                       fg='black',
                                       borderwidth=2,
                                       width=40)
        self.comLabel = Label(self.ardInitFrame,
                              bg=BACKGROUND_COLOR,
                              text="Com Port:",
                              font=TEXT_FONT)
        self.comEntry = Entry(self.ardInitFrame, font=TEXT_FONT)
        self.baudrateLabel = Label(self.ardInitFrame,
                                   bg=BACKGROUND_COLOR,
                                   text="Baudrate:",
                                   font=TEXT_FONT)
        self.baudrateEntry = Entry(self.ardInitFrame, font=TEXT_FONT)
        self.connectButton = Button(self.ardInitFrame,
                                    text="Connect",
                                    font=STATUS_FONT,
                                    command=self.connect)
        self.ardInitFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10)
        self.comLabel.grid(row=1, column=0, sticky=tk.E)
        self.comEntry.grid(row=1, column=1, sticky=tk.W)
        self.baudrateLabel.grid(row=2, column=0, sticky=tk.E)
        self.baudrateEntry.grid(row=2, column=1, sticky=tk.W)
        self.connectButton.grid(row=3, columnspan=2, pady=10)
        self.comEntry.insert(0, port)
        self.baudrateEntry.insert(0, 115200)

        #ardControlFrame
        self.ardControlFrameLabel = Label(self.ardControlFrame,
                                          text='Pre-experiment Control',
                                          bg=HEADER_COLOR,
                                          font=LARGE_FONT,
                                          fg='black',
                                          borderwidth=2,
                                          width=40)
        self.sendStringEntry = Entry(self.ardControlFrame,
                                     font=TEXT_FONT,
                                     width=20)
        self.sendStringButton = Button(self.ardControlFrame,
                                       text='Send String',
                                       font=TEXT_FONT,
                                       bg=BACKGROUND_COLOR,
                                       command=self.sendString)
        self.rewardButton = Button(self.ardControlFrame,
                                   text='Reward(R)',
                                   font=STATUS_FONT,
                                   width=10,
                                   bg=BACKGROUND_COLOR,
                                   command=self.deliverReward,
                                   height=1)
        self.pumpButton = Button(self.ardControlFrame,
                                 text='Pump Water(P)',
                                 font=STATUS_FONT,
                                 command=self.togglePump,
                                 bg=OFF_COLOR,
                                 width=12,
                                 height=1)
        self.lickLabel = Label(self.ardControlFrame,
                               text='LICK',
                               bg=LICK_OFF_COLOR,
                               font=LICK_FONT,
                               width=10,
                               height=1)
        self.lickCountLabel = Label(self.ardControlFrame,
                                    text='Lick Count :',
                                    bg=BACKGROUND_COLOR,
                                    font=LARGE_FONT)
        self.lickCountButton = Button(self.ardControlFrame,
                                      textvariable=self.lickCount,
                                      font=LARGE_FONT,
                                      bg=BACKGROUND_COLOR,
                                      command=lambda: self.lickCount.set(0))
        self.soundCheckButton = Checkbutton(self.ardControlFrame,
                                            text='Lick Sound',
                                            variable=self.isSoundOn,
                                            bg=BACKGROUND_COLOR)

        self.ardControlFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10)
        self.sendStringEntry.bind('<Return>', self.sendString)
        self.sendStringEntry.grid(row=1, column=0, padx=5, sticky=tk.E)
        self.sendStringEntry.bind('<Escape>', lambda x: self.master.focus())
        self.sendStringButton.grid(row=1, column=1, padx=5, sticky=tk.W)
        self.rewardButton.grid(row=2, column=0, pady=10)
        self.pumpButton.grid(row=2, column=1, pady=10)
        self.lickLabel.grid(row=3, columnspan=2, pady=15)
        self.lickCountLabel.grid(row=4, column=0, sticky=tk.E)
        self.lickCountButton.grid(row=4, column=1, sticky=tk.W)
        self.soundCheckButton.grid(row=5, columnspan=2)

        #initFrame
        self.initFrameLabel = Label(self.initFrame,
                                    text="Session Configuration",
                                    font=LARGE_FONT,
                                    bg=HEADER_COLOR,
                                    fg='black',
                                    borderwidth=2,
                                    width=40)
        self.loadButton = Button(self.initFrame,
                                 text="Load Config(L)",
                                 font=STATUS_FONT,
                                 command=self.selectFile)
        self.sessionNameLabel = Label(self.initFrame,
                                      text="Session Name:",
                                      font=TEXT_FONT,
                                      bg=BACKGROUND_COLOR)
        self.sessionNameEntry = Entry(self.initFrame, font=TEXT_FONT)
        self.numOfTrialsLabel = Label(self.initFrame,
                                      text="Number of Trials:",
                                      font=TEXT_FONT,
                                      bg=BACKGROUND_COLOR)
        self.numOfTrialsEntry = Entry(self.initFrame, font=TEXT_FONT)
        self.numOfTrialsEntry.bind('<KeyRelease>', self.updateTime)
        self.numOfTrialsEntry.bind('<Escape>', lambda x: self.master.focus())
        self.initFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10)
        self.sessionNameLabel.grid(row=1, column=0, sticky=tk.E)
        self.sessionNameEntry.grid(row=1, column=1, sticky=tk.W)
        self.sessionNameEntry.bind('<Escape>', lambda x: self.master.focus())
        self.numOfTrialsLabel.grid(row=2, column=0, sticky=tk.E)
        self.numOfTrialsEntry.grid(row=2, column=1, sticky=tk.W)
        self.loadButton.grid(row=3, columnspan=2, pady=10)

        #finalControlFrame
        self.finalControlFrameLabel = Label(self.finalControlFrame,
                                            text='Experiment Control',
                                            bg=HEADER_COLOR,
                                            font=LARGE_FONT,
                                            fg='black',
                                            bd=2,
                                            width=40)
        self.estTimeLabel = Label(self.finalControlFrame,
                                  textvariable=self.estTime,
                                  font=STATUS_FONT,
                                  bg=BACKGROUND_COLOR)
        self.startButton = Button(self.finalControlFrame,
                                  text="START EXPERIMENT",
                                  font='Helvetica 20 bold',
                                  command=self.startExperiment)
        self.finalControlFrameLabel.grid(padx=40, pady=10)
        self.estTimeLabel.grid(pady=10)
        self.startButton.grid(pady=15)

        #master
        self.titleLabel.pack(pady=5)
        self.master.pack(padx=20, pady=20)
        self.initFrame.grid(row=0, column=0)
        self.ardInitFrame.grid(row=1, column=0)
        self.finalControlFrame.grid(row=2, column=0, sticky='NSWE')
        self.argFrame.grid(row=0, column=1, rowspan=3, sticky='NSWE')
        for frame in [
                self.master, self.initFrame, self.ardInitFrame,
                self.finalControlFrame, self.argFrame
        ]:
            frame.bind('r', self.deliverReward)
            frame.bind('p', self.togglePump)
            frame.bind('l', self.selectFile)
            frame.bind('R', self.deliverReward)
            frame.bind('P', self.togglePump)
            frame.bind('L', self.selectFile)
            frame.bind("<Button-1>", lambda e: self.master.focus_set())
        self.updateTime()

    def run(self):
        self.master.mainloop()

    def selectFile(self, event=None):
        fileName = filedialog.askopenfilename()
        self.configFileName = fileName
        for widget in self.argFrame.winfo_children():
            widget.destroy()
        self.argFrameLabel = Label(self.argFrame,
                                   text="Experiment Configuration: " +
                                   os.path.basename(fileName),
                                   font=LARGE_FONT,
                                   bg=HEADER_COLOR,
                                   fg='black',
                                   bd=2,
                                   width=40).grid(columnspan=2,
                                                  padx=40,
                                                  pady=10)
        try:
            with open(fileName) as f:
                self.args = json.load(f)
        except Exception as e:
            print(e)
        argToLen = lambda x: len(str(x))
        maxArgNameLength = argToLen(
            max(self.args.keys(), key=lambda x: argToLen(x)))
        maxArgValueLength = argToLen(
            max(self.args.values(), key=lambda x: argToLen(x)))
        self.trialDuration = self.args["Rule duration"] +\
                                self.args["Delay duration"] +\
                                self.args["Stimulus duration"] + \
                                self.args["Wrong response flash duration"] + \
                                self.args["Wrong response rest duration"]
        for i, (argName, value) in enumerate(
                sorted(self.args.items(), key=lambda item: item[0])):
            lName = Label(self.argFrame,
                          text=str(argName) + " :",
                          font='Helvetica 12 bold',
                          bg=BACKGROUND_COLOR).grid(row=i + 3,
                                                    column=0,
                                                    sticky=tk.E)
            lValue = Label(self.argFrame, text=str(value),
                           bg=BACKGROUND_COLOR).grid(
                               row=i + 3,
                               column=1,
                               sticky=tk.W,
                           )
        self.updateTime()
        self.isConfigLoaded = True

    def connect(self):
        try:
            comport = self.comEntry.get()
            baudrate = self.baudrateEntry.get()
            if comport == "" or baudrate == "":
                raise Exception("Please fill in all values")
            baudrate = int(baudrate)
            self.ard = MouseArduino(comport, baudrate)
            self.ard.start()
            self.ardInitFrame.destroy()
            self.ardUpdater.start()
            self.ardControlFrame.grid(row=1, column=0)
            self.isArdConnected = True
        except Exception as e:
            messagebox.showerror(
                "Error",
                "Could not connect to Arduino. Make sure port is correct or other program isn't grabbing the port :"
                + str(e))

    def deliverReward(self, event=None):
        self.ard.deliverReward()

    def sendString(self, event=None):
        self.ard.write(self.sendStringEntry.get())
        self.sendStringEntry.delete(0, 'end')

    def updateVariable(self):
        while not self.stopUpdating.is_set():
            if self.ard.newMsg.wait(1):
                while not self.ard.msgQueue.empty():
                    self.ard.newMsg.clear()
                    msg = self.ard.msgQueue.get()
                    print(msg)
                    args = Utilities.parse(msg)
                    arg = args[1].strip()
                    if arg == 'LK':
                        self.lickCount.set(self.lickCount.get() + 1)
                        self.lickLabel.configure(bg=ON_COLOR)
                        if self.isSoundOn.get():
                            Sound.cue(0.05)
                        time.sleep(0.2)
                        self.lickLabel.configure(bg=LICK_OFF_COLOR)
                    elif arg == 'startpump':
                        self.pumpButton.configure(bg=ON_COLOR)
                        self.isPumpOn = True
                    elif arg == 'stoppump':
                        self.pumpButton.configure(bg=OFF_COLOR)
                        self.isPumpOn = False

    def togglePump(self, event=None):
        if self.isPumpOn:
            self.ard.stopPump()
        else:
            self.ard.startPump()

    def updateTime(self, event=None):
        numOfTrials = self.numOfTrialsEntry.get()
        try:
            totalDuration = self.trialDuration * int(numOfTrials)
            tmin = totalDuration // 60
            tsec = totalDuration % 60
            timeStr = "{:.0f} Min {:.0f} Sec".format(tmin, tsec)
        except Exception as e:
            timeStr = ""
            print(e)
        self.estTime.set("Estimated duration: {:>10}".format(timeStr))

    def startExperiment(self):
        if not self.isConfigLoaded:
            messagebox.showerror("Error", "Please load configuration file")
        elif not self.isArdConnected:
            messagebox.showerror("Error", "Please connect Arduino")
        else:
            try:
                sessionName = self.sessionNameEntry.get()
                numOfTrials = self.numOfTrialsEntry.get()
                if sessionName == "" or numOfTrials == "":
                    raise Exception("Please fill in all values")
                numOfTrials = int(numOfTrials)
                self.experiment = Decision(self.ard)
                self.experiment.startExperiment(sessionName, numOfTrials,
                                                self.configFileName)
            except Exception as e:
                messagebox.showerror("Error", e)
class Decryptor(object):
    
    def __init__(self):
        self.fileBrowserShadowInformation = dict()
        self.startUI()
        
    def startUI(self):
        self.root = Tk()
        self.root.title('Decryptor')
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        
        mainFrame = Frame(self.root)
        mainFrame.grid(row=0, column=0, padx=5, pady=5, sticky='nswe')
        mainFrame.rowconfigure(1, weight=1)
        mainFrame.columnconfigure(0, weight=1)
        
        optionsFrame = Frame(mainFrame)
        optionsFrame.grid(row=0, column=0, pady=(5,0), sticky='nswe')
        optionsFrame.columnconfigure(0, pad=5)
        optionsFrame.columnconfigure(1, weight=1)
        optionsFrame.columnconfigure(2, pad=5)
        
        browserFrame = Frame(mainFrame)
        browserFrame.grid(row=1, column=0, pady=(5,0), sticky='nswe')
        browserFrame.rowconfigure(0, weight=1)
        browserFrame.columnconfigure(0, weight=1)
        
        actionFrame = Frame(mainFrame)
        actionFrame.grid(row=2, column=0, pady=(5,0), sticky='e')
        actionFrame.columnconfigure(0, weight=1)
        
        Label(optionsFrame, text="Secret").grid(row=0, column=0, sticky='w')
        self.secret = Entry(optionsFrame)
        self.secret.grid(row=0, column=1, sticky='nswe')
        self.secret.focus_set()
        self.secretToggleButton = Button(optionsFrame, text="Set", command=self.toggleSecret, width=8)
        self.secretToggleButton.grid(row=0, column=2, sticky='e')
        self.secretToggleButton.setvar('set', False)
        
        Label(optionsFrame, text="Encrypted Folder").grid(row=1, column=0, sticky='w')
        self.folderPath = Entry(optionsFrame, state='readonly')
        self.browseButton = Button(optionsFrame, text="Browse", command=self.chooseFolder, width=8)
        self.browseButton.grid(row=1, column=2, sticky='e')
        self.browseButton.configure(state='disabled')
        self.folderPath.grid(row=1, column=1, sticky='nswe')
        
        fileBrowserColumns = ('size', 'modified', 'encrypted name')
        self.fileBrowser = Treeview(browserFrame, columns=fileBrowserColumns)
        self.fileBrowser.heading('#0', text='File')
        for i in range(0, len(fileBrowserColumns)):
            self.fileBrowser.heading('#{0}'.format(i+1), text=fileBrowserColumns[i].title())
        self.fileBrowser.grid(row=0, column=0, sticky='nswe')
        
        scrollBarY = Scrollbar(orient=VERTICAL, command=self.fileBrowser.yview)
        scrollBarX = Scrollbar(orient=HORIZONTAL, command=self.fileBrowser.xview)
        self.fileBrowser['yscroll'] = scrollBarY.set
        self.fileBrowser['xscroll'] = scrollBarX.set
        scrollBarY.grid(in_=browserFrame, row=0, column=1, sticky='ns')
        scrollBarX.grid(in_=browserFrame, row=1, column=0, sticky='ew')
        
        Button(actionFrame, text="Decrypt Selected", command=self.decryptSelected).grid(row=0, column=0)
        Button(actionFrame, text="Decrypt All", command=self.decryptAll).grid(row=0, column=1)
        
        self.root.mainloop()

    def chooseFolder(self):
        dirPath = askdirectory(parent=self.root, mustexist=True)
        if os.name == 'nt':
            dirPath = '\\\\?\\' + os.path.normpath(dirPath)
        self.folderPath.configure(state='normal')
        self.folderPath.delete(0, len(self.folderPath.get()))
        self.folderPath.insert(0, dirPath)
        self.folderPath.configure(state='readonly')
        self.initializeFileBrowser()
        
    def toggleSecret(self):
        if self.secretToggleButton.getvar('set'):
            self.secret.configure(state='normal')
            self.secretToggleButton.setvar('set', False)
            self.secretToggleButton.configure(text='Set')
            self.browseButton.configure(state='disabled')
            self.__clearFileBrowser()
        else:
            if self.secret.get() == '':
                showerror('Invalid Secret', 'The provided secret must not be empty.')
                return
            self.secret.configure(state='readonly')
            self.secretToggleButton.setvar('set', True)
            self.secretToggleButton.configure(text='Change')
            self.browseButton.configure(state='normal')
            self.decryptor = Encryption(self.secret.get(), None, None)
        
    def initializeFileBrowser(self):
        self.__clearFileBrowser()
        self.__initializeFileBrowser(self.decryptor, self.folderPath.get())
        self.fileBrowser.focus_set()
        
    def decryptSelected(self):
        selectedItems = self.fileBrowser.selection()
        if len(selectedItems) < 1:
            return

        destinationFolder = self.__askForDestinationFolder()
        if destinationFolder is None:
            return

        transitiveSelectedItems = set()
        for selectedItem in selectedItems:
            transitiveSelectedItems.update(self.__getAllFileBrowserChildren(selectedItem))
        filteredSelectedItems = filter(lambda x: not x in transitiveSelectedItems, selectedItems)
        
        for selectedItem in filteredSelectedItems:
            self.__decryptFileBrowserItemToDestination(selectedItem, destinationFolder)
    
    
    def decryptAll(self):
        destinationFolder = self.__askForDestinationFolder()
        if destinationFolder is None:
            return
        
        children = self.fileBrowser.get_children('')
        for child in children:
            self.__decryptFileBrowserItemToDestination(child, destinationFolder)
    
    def __getAllFileBrowserChildren(self, identifier):
        children = set()
        queue = list()
        queue.append(identifier)
        while len(queue) > 0:
            for item in self.fileBrowser.get_children(queue.pop()):
                children.add(item)
                queue.append(item)
        return children
    
    def __askForDestinationFolder(self):
        return askdirectory(parent=self.root, mustexist=True, title='Destination Folder')
    
    def __decryptFileBrowserItemToDestination(self, selectedItem, destinationFolder):
        decryptedFileName = self.fileBrowser.item(selectedItem, option='text')
        destinationFullPath = os.path.join(destinationFolder, decryptedFileName)
        encryptedFullPath = self.fileBrowserShadowInformation.get(selectedItem)
        
        if os.path.isdir(encryptedFullPath):
            self.__decryptDirToDestination(encryptedFullPath, destinationFullPath)
        else:
            self.__decryptFileToDestination(encryptedFullPath, destinationFullPath)
            
    def __decryptFileToDestination(self, encryptedFullPath, destinationPath):
        chunkSize = 4096
        encryptedVirtualFile = None
        
        filename, segmentNumber = FilenameUtils.splitSegmentedFileName(encryptedFullPath)
        if segmentNumber is None:
            encryptedVirtualFile = VirtualFile(encryptedFullPath)
        else:
            encryptedVirtualFile = SegmentedVirtualFile(filename)
            
        try:
            decryptedFileSize = self.decryptor.decryptedFileSize(encryptedVirtualFile)
            with open(destinationPath, 'wb') as destinationFile:    
                for offset in range(0, decryptedFileSize, chunkSize):
                    destinationFile.write(self.decryptor.decryptedContent(encryptedVirtualFile, offset, chunkSize))
        finally:
            encryptedVirtualFile.closeFileHandle()
    
    def __decryptDirToDestination(self, encryptedFullPath, destinationFullPath):
        if not os.path.isdir(destinationFullPath):
            os.mkdir(destinationFullPath)
        for entry in os.listdir(encryptedFullPath):
            entryEncryptedFullPath = os.path.join(encryptedFullPath, entry)
            decryptedEntryName = self.decryptor.decryptFileName(entry)
            entryDestinationFullPath = os.path.join(destinationFullPath, decryptedEntryName)
            if os.path.isdir(entryEncryptedFullPath):
                self.__decryptDirToDestination(entryEncryptedFullPath, entryDestinationFullPath)
            else:
                self.__decryptFileToDestination(entryEncryptedFullPath, entryDestinationFullPath)
        
    def __clearFileBrowser(self):
        for child in self.fileBrowser.get_children():
            self.fileBrowser.delete(child)
        self.fileBrowserShadowInformation.clear()
            
    def __initializeFileBrowser(self, decryption, encryptedDir, parent=''):
        for entry in os.listdir(encryptedDir):

            # Check if file is segmented
            filename, segment = FilenameUtils.splitSegmentedFileName(entry)
            if segment is not None and segment is not 0:
                continue
            
            encryptedFullPathForEntry = os.path.join(encryptedDir, entry)
            decryptedName = decryption.decryptFileName(filename)

            identifier = None
            printableModificationDate = datetime.fromtimestamp(os.path.getmtime(encryptedFullPathForEntry)).strftime('%Y-%m-%d %H:%M:%S')
            fileSize = None

            if os.path.isfile(encryptedFullPathForEntry):
                encryptedVirtualFile = None
                if segment is not None:
                    encryptedVirtualFile = SegmentedVirtualFile(os.path.join(encryptedDir, filename))
                else:
                    encryptedVirtualFile = VirtualFile(encryptedFullPathForEntry)
                fileSize = decryption.decryptedFileSize(encryptedVirtualFile)
                encryptedVirtualFile.closeFileHandle()
                identifier = self.fileBrowser.insert(parent, 'end', text=decryptedName)
            else:
                identifier = self.fileBrowser.insert(parent, 'end', text=decryptedName)
                self.__initializeFileBrowser(decryption, encryptedFullPathForEntry, identifier)
                fileSize = os.path.getsize(encryptedFullPathForEntry)
                
            self.fileBrowser.set(identifier, 'size', hurry.filesize.size(fileSize))
            self.fileBrowser.set(identifier, 'modified', printableModificationDate)
            self.fileBrowser.set(identifier, 'encrypted name', entry)
            self.fileBrowserShadowInformation[identifier] = encryptedFullPathForEntry
Ejemplo n.º 50
0
class mainGUI:
    def __init__(self, root):
        self.root = root

        ## Menu
        self.MMenu = Menu(root)

        self.FMenu = Menu(root)
        self.FMenu.add_command(label="SELECT", command=self.aaxbrowse)
        self.FMenu.add_command(label="COMPARE", command=self.icompare)
        self.FMenu.add_command(label="EDIT", command=self.opentxt)

        self.TMenu = Menu(root)
        self.TMenu.add_command(label="CONVERT to TXT", command=self.convert)
        self.TMenu.add_command(label="SCAN FOLDER")
        self.TMenu.add_command(label="X-REFERENCE", command=self.vpins)

        self.MMenu.add_cascade(label="FILE", menu=self.FMenu)
        self.MMenu.add_cascade(label="TOOLS", menu=self.TMenu)

        #self.root.configure(menu=self.MMenu)

        ## LABELS & PICTURES
        root.title('GUI rev:%s AMPLA rev:%s' % (rev, ampla_rev))
        root.config(menu=self.MMenu)
        Label(text='X-REF VALUE:').grid(row=rowBefore, column=0, sticky='E')
        Label(text=' BEFORE:').grid(row=rowBefore, column=3, sticky='W')
        Label(text=' AFTER:').grid(row=rowAfter, column=3, sticky='W')
        ## OUTPUT
        self.cmpOutput = STX.ScrolledText(root)
        self.cmpOutput.grid(row=rowOUTPUT,
                            column=0,
                            sticky='N' + 'S' + 'w' + 'E',
                            columnspan=11)
        ## ENTRIES
        ## AAX file entry - BEFORE
        self.FBefore = Entry(root, width=wwidth)
        self.FBefore.grid(row=rowBefore, column=4, sticky='W')
        ## AAX file entry - AFTER
        self.FAfter = Entry(root, width=wwidth)
        self.FAfter.grid(row=rowAfter, column=4, sticky='W')
        ## TAG NAME entry - cross reference
        self.TagEdit = Entry(root)
        self.TagEdit.grid(row=rowBefore, column=1, sticky='W')

    def aaxbrowse(self):
        self.FBefore.delete(0, len(self.FBefore.get()))
        self.FAfter.delete(0, len(self.FAfter.get()))
        self.FBefore.insert(
            0,
            filedialog.askopenfilename(initialdir="~",
                                       title="Select original file",
                                       filetypes=ftypes))
        self.FAfter.insert(
            0,
            filedialog.askopenfilename(initialdir="~",
                                       title="Select modified file",
                                       filetypes=ftypes))
        self.icompare()

    def opentxt(self):
        os.startfile(self.FBefore.get())
        os.startfile(self.FAfter.get())

    def icompare(self):
        extB = self.FBefore.get()[-3:].upper()
        extA = self.FAfter.get()[-3:].upper()

        if extB == '.AA':
            fB = AA(self.FBefore.get())
        elif extB == 'AAX':
            fB = AAX(self.FBefore.get())
        elif extB == 'BAX':
            fB = BAX(self.FBefore.get())
        elif extB == '.BA':
            fB = BA(self.FBefore.get())
        else:
            return

        if extA == '.AA':
            fA = AA(self.FAfter.get())
        elif extA == 'AAX':
            fA = AAX(self.FAfter.get())
        elif extA == 'BAX':
            fA = BAX(self.FAfter.get())
        elif extA == '.BA':
            fA = BA(self.FAfter.get())
        else:
            return

        self.cmpOutput.insert('0.0', '\n\tEND OF REPORT')
        self.cmpOutput.insert('0.0', str(fB.compare(fA)))
        self.cmpOutput.insert(
            '0.0', '\n\n\t>>> DISCREPANCIES REPORT <<<\n%s\nand\n%s\n' %
            (fB.fName, fA.fName))

    def vpins(self):
        extB = self.FBefore.get()[-3:].upper()
        extA = self.FAfter.get()[-3:].upper()

        if extB == '.AA':
            fB = AA(self.FBefore.get())
        elif extB == 'AAX':
            fB = AAX(self.FBefore.get())
        elif extB == 'BAX':
            fB = BAX(self.FBefore.get())
        elif extB == '.BA':
            fB = BA(self.FBefore.get())
        else:
            return

        if extA == '.AA':
            fA = AA(self.FAfter.get())
        elif extA == 'AAX':
            fA = AAX(self.FAfter.get())
        elif extA == 'BAX':
            fA = BAX(self.FAfter.get())
        elif extA == '.BA':
            fA = BA(self.FAfter.get())
        else:
            return

        self.cmpOutput.insert('0.0', "\n\tEND OF REPORT")
        s = str('\n\t%s at %s\n' % (self.TagEdit.get(), fB.fName))
        if len(s) > 0:
            for cradd in fB.cref(self.TagEdit.get()):
                s += str(fB.Blocks[cradd[:cradd.index(':')]])
            s += str('\n\t%s at %s\n' % (self.TagEdit.get(), fA.fName))
            for cradd in fA.cref(self.TagEdit.get()):
                s += str(fA.Blocks[cradd[:cradd.index(':')]])
            self.cmpOutput.insert('0.0', s)
        self.cmpOutput.insert('0.0', '\n\n\t>>> X_REFERENCE REPORT <<<')

    def convert(self):
        afile = filedialog.askopenfilename(initialdir="~",
                                           title="Select AA or BA file",
                                           filetypes=ftypes)
        ext = afile[-3:].upper()
        if ext == '.AA':
            f = AA(afile)
        elif ext == '.BA':
            f = BA(afile)
        else:
            #self.cmpOutput.insert('0.0',"\n\t Error occure while converting %s"%afile)
            return
        f.write()
        self.cmpOutput.insert('0.0',
                              "\n\n\tSuccesfully converted to %s.txt " % afile)
Ejemplo n.º 51
0
    def __init__(self, root=Tk()):
        self.root = root
        self.root.title("Decision Experiment")
        self.root.configure(bg=BACKGROUND_COLOR)
        self.titleLabel = Label(self.root,
                                text='Decision Experiment',
                                font=STATUS_FONT,
                                bg=BACKGROUND_COLOR)
        self.ard = None
        self.experiment = None
        self.isConfigLoaded = False
        self.isArdConnected = False
        self.isPumpOn = False
        self.estTime = StringVar()
        self.lickCount = IntVar()
        self.lickCount.set(0)
        self.isSoundOn = BooleanVar()
        self.stopUpdating = threading.Event()
        self.ardUpdater = threading.Thread(target=self.updateVariable)
        port = MouseArduino.getUnoPort()

        #Frames
        self.master = Frame(root, bg=BACKGROUND_COLOR)
        self.master.grid_rowconfigure(0)
        self.master.grid_rowconfigure(1)
        self.master.grid_rowconfigure(2, weight=5)
        self.master.grid_columnconfigure(0, weight=1)
        self.master.grid_columnconfigure(1, weight=1)
        self.master.grid_columnconfigure(2, weight=1)
        self.ardInitFrame = Frame(self.master,
                                  bd=3,
                                  relief='groove',
                                  bg=BACKGROUND_COLOR)
        self.ardControlFrame = Frame(self.master,
                                     bd=3,
                                     relief='groove',
                                     bg=BACKGROUND_COLOR)
        self.initFrame = Frame(self.master,
                               bd=3,
                               relief='groove',
                               bg=BACKGROUND_COLOR)
        self.argFrame = Frame(self.master,
                              bd=3,
                              relief='groove',
                              bg=BACKGROUND_COLOR)
        self.finalControlFrame = Frame(self.master,
                                       bd=3,
                                       relief='groove',
                                       bg=BACKGROUND_COLOR)

        #ardInitFrame
        self.ardInitFrameLabel = Label(self.ardInitFrame,
                                       text="Connect to Hardware",
                                       bg=HEADER_COLOR,
                                       font=LARGE_FONT,
                                       fg='black',
                                       borderwidth=2,
                                       width=40)
        self.comLabel = Label(self.ardInitFrame,
                              bg=BACKGROUND_COLOR,
                              text="Com Port:",
                              font=TEXT_FONT)
        self.comEntry = Entry(self.ardInitFrame, font=TEXT_FONT)
        self.baudrateLabel = Label(self.ardInitFrame,
                                   bg=BACKGROUND_COLOR,
                                   text="Baudrate:",
                                   font=TEXT_FONT)
        self.baudrateEntry = Entry(self.ardInitFrame, font=TEXT_FONT)
        self.connectButton = Button(self.ardInitFrame,
                                    text="Connect",
                                    font=STATUS_FONT,
                                    command=self.connect)
        self.ardInitFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10)
        self.comLabel.grid(row=1, column=0, sticky=tk.E)
        self.comEntry.grid(row=1, column=1, sticky=tk.W)
        self.baudrateLabel.grid(row=2, column=0, sticky=tk.E)
        self.baudrateEntry.grid(row=2, column=1, sticky=tk.W)
        self.connectButton.grid(row=3, columnspan=2, pady=10)
        self.comEntry.insert(0, port)
        self.baudrateEntry.insert(0, 115200)

        #ardControlFrame
        self.ardControlFrameLabel = Label(self.ardControlFrame,
                                          text='Pre-experiment Control',
                                          bg=HEADER_COLOR,
                                          font=LARGE_FONT,
                                          fg='black',
                                          borderwidth=2,
                                          width=40)
        self.sendStringEntry = Entry(self.ardControlFrame,
                                     font=TEXT_FONT,
                                     width=20)
        self.sendStringButton = Button(self.ardControlFrame,
                                       text='Send String',
                                       font=TEXT_FONT,
                                       bg=BACKGROUND_COLOR,
                                       command=self.sendString)
        self.rewardButton = Button(self.ardControlFrame,
                                   text='Reward(R)',
                                   font=STATUS_FONT,
                                   width=10,
                                   bg=BACKGROUND_COLOR,
                                   command=self.deliverReward,
                                   height=1)
        self.pumpButton = Button(self.ardControlFrame,
                                 text='Pump Water(P)',
                                 font=STATUS_FONT,
                                 command=self.togglePump,
                                 bg=OFF_COLOR,
                                 width=12,
                                 height=1)
        self.lickLabel = Label(self.ardControlFrame,
                               text='LICK',
                               bg=LICK_OFF_COLOR,
                               font=LICK_FONT,
                               width=10,
                               height=1)
        self.lickCountLabel = Label(self.ardControlFrame,
                                    text='Lick Count :',
                                    bg=BACKGROUND_COLOR,
                                    font=LARGE_FONT)
        self.lickCountButton = Button(self.ardControlFrame,
                                      textvariable=self.lickCount,
                                      font=LARGE_FONT,
                                      bg=BACKGROUND_COLOR,
                                      command=lambda: self.lickCount.set(0))
        self.soundCheckButton = Checkbutton(self.ardControlFrame,
                                            text='Lick Sound',
                                            variable=self.isSoundOn,
                                            bg=BACKGROUND_COLOR)

        self.ardControlFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10)
        self.sendStringEntry.bind('<Return>', self.sendString)
        self.sendStringEntry.grid(row=1, column=0, padx=5, sticky=tk.E)
        self.sendStringEntry.bind('<Escape>', lambda x: self.master.focus())
        self.sendStringButton.grid(row=1, column=1, padx=5, sticky=tk.W)
        self.rewardButton.grid(row=2, column=0, pady=10)
        self.pumpButton.grid(row=2, column=1, pady=10)
        self.lickLabel.grid(row=3, columnspan=2, pady=15)
        self.lickCountLabel.grid(row=4, column=0, sticky=tk.E)
        self.lickCountButton.grid(row=4, column=1, sticky=tk.W)
        self.soundCheckButton.grid(row=5, columnspan=2)

        #initFrame
        self.initFrameLabel = Label(self.initFrame,
                                    text="Session Configuration",
                                    font=LARGE_FONT,
                                    bg=HEADER_COLOR,
                                    fg='black',
                                    borderwidth=2,
                                    width=40)
        self.loadButton = Button(self.initFrame,
                                 text="Load Config(L)",
                                 font=STATUS_FONT,
                                 command=self.selectFile)
        self.sessionNameLabel = Label(self.initFrame,
                                      text="Session Name:",
                                      font=TEXT_FONT,
                                      bg=BACKGROUND_COLOR)
        self.sessionNameEntry = Entry(self.initFrame, font=TEXT_FONT)
        self.numOfTrialsLabel = Label(self.initFrame,
                                      text="Number of Trials:",
                                      font=TEXT_FONT,
                                      bg=BACKGROUND_COLOR)
        self.numOfTrialsEntry = Entry(self.initFrame, font=TEXT_FONT)
        self.numOfTrialsEntry.bind('<KeyRelease>', self.updateTime)
        self.numOfTrialsEntry.bind('<Escape>', lambda x: self.master.focus())
        self.initFrameLabel.grid(row=0, columnspan=2, padx=40, pady=10)
        self.sessionNameLabel.grid(row=1, column=0, sticky=tk.E)
        self.sessionNameEntry.grid(row=1, column=1, sticky=tk.W)
        self.sessionNameEntry.bind('<Escape>', lambda x: self.master.focus())
        self.numOfTrialsLabel.grid(row=2, column=0, sticky=tk.E)
        self.numOfTrialsEntry.grid(row=2, column=1, sticky=tk.W)
        self.loadButton.grid(row=3, columnspan=2, pady=10)

        #finalControlFrame
        self.finalControlFrameLabel = Label(self.finalControlFrame,
                                            text='Experiment Control',
                                            bg=HEADER_COLOR,
                                            font=LARGE_FONT,
                                            fg='black',
                                            bd=2,
                                            width=40)
        self.estTimeLabel = Label(self.finalControlFrame,
                                  textvariable=self.estTime,
                                  font=STATUS_FONT,
                                  bg=BACKGROUND_COLOR)
        self.startButton = Button(self.finalControlFrame,
                                  text="START EXPERIMENT",
                                  font='Helvetica 20 bold',
                                  command=self.startExperiment)
        self.finalControlFrameLabel.grid(padx=40, pady=10)
        self.estTimeLabel.grid(pady=10)
        self.startButton.grid(pady=15)

        #master
        self.titleLabel.pack(pady=5)
        self.master.pack(padx=20, pady=20)
        self.initFrame.grid(row=0, column=0)
        self.ardInitFrame.grid(row=1, column=0)
        self.finalControlFrame.grid(row=2, column=0, sticky='NSWE')
        self.argFrame.grid(row=0, column=1, rowspan=3, sticky='NSWE')
        for frame in [
                self.master, self.initFrame, self.ardInitFrame,
                self.finalControlFrame, self.argFrame
        ]:
            frame.bind('r', self.deliverReward)
            frame.bind('p', self.togglePump)
            frame.bind('l', self.selectFile)
            frame.bind('R', self.deliverReward)
            frame.bind('P', self.togglePump)
            frame.bind('L', self.selectFile)
            frame.bind("<Button-1>", lambda e: self.master.focus_set())
        self.updateTime()
Ejemplo n.º 52
0
class PyRegexEvaluator(Frame):

    def centre_window(self):
        """ Display's your gui in the centre of the screen """
        w = 685     # Sets your gui's width
        h = 635     # Sets your gui's height
        sw = self.root.winfo_screenwidth()
        sh = self.root.winfo_screenheight()
        x = (sw - w) // 2   # Use integer devision to avoid having to convert
        y = (sh - h) // 2   # float to int
        self.root.geometry('{:d}x{:d}+{:d}+{:d}'.format(w, h, x, y))

    def __init__(self, parent, *args, **kwargs):
        Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        self.centre_window()
        centre_title_text = (' ' * 40)  # Uses spaces to center Title
        title_text = 'Python Regular Expression Checker  -  By Jack Ackermann'
        self.root.title(centre_title_text + title_text)
        self.root.iconbitmap('images\icon.ico')
        self.grid(column=0, row=0, sticky='nsew', padx=12, pady=5)

        self.create_widgets()
        self.create_right_click_menu()

    def create_widgets(self):
        '''Create and load all widgets'''
        # Entry widget and Label Section
        label_text = 'Please enter regex expression to find: '
        self.regex_label = tk.Label(self, text=label_text)
        self.regex_label.grid(row=0, column=0, sticky="w", pady=15)

        self.regex_pattern = tk.StringVar()
        self.regex_string = Entry(self, textvariable=self.regex_pattern)
        self.regex_string.config(borderwidth=2, relief='sunken', width=70)
        self.regex_string.grid(row=0, column=0, sticky="e", pady=15)

        # Data widget and Label Section. Data to be searched.
        label_data1 = 'Enter data below that you want to search.  '
        label_data2 = 'Results are then highlighted using re.finditer'
        self.data_label = tk.Label(self, text=label_data1 + label_data2)
        self.data_label.grid(row=1, column=0, sticky="w")

        self.data_textbox = Text(self, borderwidth=2, relief='sunken')
        self.data_textbox.config(height=15, width=80)
        self.data_textbox.grid(row=2, column=0, sticky="new")
        self.scrollbar = Scrollbar(self, command=self.data_textbox.yview)
        self.scrollbar.grid(row=2, column=1, sticky='ns')
        self.data_textbox['yscrollcommand'] = self.scrollbar.set

        # Display regex results and Label section
        label_output = 'All the matches below were found using re.findall'
        self.label_output = tk.Label(self, text=label_output)
        self.label_output.grid(row=3, column=0, sticky="w")

        self.output_textbox = Text(self, borderwidth=2, relief='sunken')
        self.output_textbox.config(height=15, width=80)
        self.output_textbox.grid(row=4, column=0, sticky="new")
        self.scrollbar2 = Scrollbar(self, command=self.output_textbox.yview)
        self.scrollbar2.grid(row=4, column=1, sticky='ns')
        self.output_textbox['yscrollcommand'] = self.scrollbar2.set

        # Create Two Button Widgets
        self.find_btn = ttk.Button(self, text='Find', command=self.on_find)
        self.find_btn.grid(row=5, sticky='E')
        self.exit_btn = ttk.Button(self, text='Exit', command=self.on_exit)
        self.exit_btn.grid(row=5, column=0, sticky='W', pady=15)

        # Create a Checkbutton Widget
        self.auto_var = tk.IntVar()
        self.auto_find = Checkbutton(self, variable=self.auto_var,
                                     command=self.on_auto, background='pink')
        self.auto_find.config(text='Turns on Auto Search as you type')
        self.auto_find.grid(row=5, column=0, sticky='')
        self.auto_find.deselect()

    def create_right_click_menu(self):
        '''Creates and binds the right click popup menu'''
        # Instanciate the imported popup class
        self.popup = RightClickMenu(self.master, self.regex_pattern)
        self.popup2 = RightClickMenu(self.master, self.data_textbox)
        self.popup3 = RightClickMenu(self.master, self.output_textbox)
        # Bind the popup menus and Enter Key to the appropriate widgets.
        self.regex_string.bind("<Button-3>", self.popup.entry_popup)
        self.data_textbox.bind("<Button-3>", self.popup2.text_popup)
        self.output_textbox.bind("<Button-3>", self.popup3.text_popup)
        self.regex_string.bind("<Return>", lambda _: self.on_find())

    # Method for the find_btn, <Return> bind and Checkbutton
    def on_find(self, a=None, b=None, c=None):
        """
        Takes three arguments with default values: a, b, c
        These arguments are needed for the trace method of StringVar()

        Instanciate and use the Highlighter class
        """
        self.highlighter = Highlighter(self.regex_pattern, self.data_textbox,
                                       self.output_textbox)
        self.highlighter.find_matches()

    # Method for the self.auto_find checkbutton
    def on_auto(self):
        """
        If the self.auto_find Checkbox is selected,
        the find button is disabled and the <Return> key is unbound
        The self.regex_pattern.trace is created that calls the on_find
        method everytime the variable changes.

        If the self.auto_find Checkbox is unselected,
        the find button gets re-enabled and the <Return> key bind is set.
        And the self.regex_pattern.trace is deleted
        """
        trace_id = ''
        if self.auto_var.get() == 1:
            self.find_btn.config(state='disabled')
            self.regex_string.unbind("<Return>")
            self.regex_pattern.trace_id = self.regex_pattern.trace("w", self.on_find)
        else:
            self.find_btn.config(state='enabled')
            self.regex_string.bind("<Return>", lambda _: self.on_find())
            self.regex_pattern.trace_vdelete("w", self.regex_pattern.trace_id)

    # Exits the program. Linked to the Exit Button
    def on_exit(self):
        self.root.destroy()
Ejemplo n.º 53
0
    def run(self):
        width, height = 930, 790
        window = Tk()
        window.title(f"GUI Debugger for PyMODI (v{modi.__version__})")
        window.geometry(f"{width}x{height}")
        window.resizable(False, False)
        canvas = Canvas(window, width=width, height=height)
        canvas.create_rectangle(10, 40, 410, 340, outline='black')
        canvas.pack()

        # cmd (ins) field
        Label(window, text='c:').place(x=10, y=5)
        self.__cmd = Entry(window)
        self.__cmd.place(x=25, y=5, width=40)

        # sid field
        Label(window, text='s:').place(x=70, y=5)
        self.__sid = Entry(window)
        self.__sid.place(x=85, y=5, width=40)

        # did field
        Label(window, text='d:').place(x=130, y=5)
        self.__did = Entry(window)
        self.__did.place(x=145, y=5, width=40)

        # data field
        Label(window, text='b:').place(x=190, y=5)
        self.__data = Entry(window)
        self.__data.place(x=205, y=5, width=250)
        generate_button = Button(window, text="Generate", command=self.__parse)
        generate_button.place(x=455, y=5)

        # send field
        Label(window, text='msg:').place(x=545, y=5)
        self.__input_box = Entry(window)
        self.__input_box.place(x=580, y=5, width=250)
        self.__input_box["state"] = tk.DISABLED
        send_button = Button(window, text="Send", command=self.send)
        send_button.place(x=830, y=5)

        # TODO: Remove this __query related functions
        Label(window, text="Filter by Command: ").place(x=420, y=35)
        self.__query = Entry(window)
        self.__query.place(x=545, y=33, width=35)
        Button(window, text="Filter", command=self.__change_query).place(x=580,
                                                                         y=32)

        # log box (where MODI json messages are shown)
        self.__log = ScrolledText(window, wrap=WORD, font=('Helvetica', 12))
        self.__log.place(x=420, y=60, width=480, height=700)

        # spec box (where module information are shown)
        self.__spec = Label(window,
                            text=f"Running PyMODI (v{modi.__version__})",
                            bg='white',
                            anchor=NW,
                            justify='left',
                            font=('Helvetica', 15))
        self.__spec.place(x=10, y=350, width=400, height=390)

        # generate module button in the canvas
        for module in self.bundle.modules:
            self.__create_module_button(module, window)

        # run mainloop
        while True:
            try:
                window.update()
                self.__append_log()
                if self.__curr_module:
                    self.__change_spec(self.__curr_module)
            except TclError:
                break
            time.sleep(0.1)
Ejemplo n.º 54
0
    window, text="Prix Min (en €):")
lblPrixMin.grid(row=2, column=0)

lblRecherche = Label(
    window, text="Recherche :")
lblRecherche.grid(row=1, column=0)

lblMotsObligatoires = Label(
    window, text="Mots Obligatoires :")
lblMotsObligatoires.grid(row=4, column=0)

lblMotsInterdits = Label(
    window, text="Mots Interdits :")
lblMotsInterdits.grid(row=5, column=0)

recherche = Entry(window)
prixMin = Entry(window)
prixMax = Entry(window)
motObligatoires = Entry(window)
motInterdits = Entry(window)

recherche.grid(row=1, column=1)

prixMin.grid(row=2, column=1)
prixMax.grid(row=3, column=1)
motObligatoires.grid(row=4, column=1)
motInterdits.grid(row=5, column=1)

LBC_state = IntVar()
LBC = Checkbutton(window, text='LeBonCoin', variable=LBC_state)
LBC.select()
Ejemplo n.º 55
0
    def __init__(self, root):
        super().__init__(root)
        verify.__init__(self, root)

        self.name1 = Label(root,
                           text='First Name:',
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=80)
        self.name2 = Label(root,
                           text="Second Name:",
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=110)
        self.name3 = Label(root,
                           text="Third Name:",
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=140)
        self.name4 = Label(root,
                           text="Fourth Name:",
                           bg='#2B2B2B',
                           fg='#F9F0D9',
                           font='bold 10').place(x=10, y=170)
        self.year = Label(root,
                          text='Year:',
                          bg='#2B2B2B',
                          fg='#B0B9D9',
                          font='bold 10').place(x=10, y=220)
        self.topic = Label(root,
                           text="Topic(s):",
                           bg='#2B2B2B',
                           fg='#F8D8C0',
                           font='bold 10').place(x=10, y=250)
        self.book = Label(root,
                          text="Book(s):",
                          bg='#2B2B2B',
                          fg='#F8D8C0',
                          font='bold 10').place(x=10, y=330)
        self.volume = Label(root,
                            text="Volume(s):",
                            bg='#2B2B2B',
                            fg='#B0D9D9',
                            font='bold 10').place(x=10, y=430)
        self.issue = Label(root,
                           text="Issue(s):",
                           bg='#2B2B2B',
                           fg='#B0D9D9',
                           font='bold 10').place(x=10, y=460)
        self.page = Label(root,
                          text="Page(s)",
                          bg='#2B2B2B',
                          fg='#B0D9D9',
                          font='bold 10').place(x=10, y=490)

        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=85, y=80)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=100, y=110)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=85, y=140)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=95, y=170)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=70, y=250)
        self.req = Label(root, text='*', fg='orange', bg='#2B2B2B',
                         bd=0).place(x=70, y=330)

        vname1 = root.register(self.name1_entry)
        vname2 = root.register(self.name2_entry)
        vname3 = root.register(self.name3_entry)
        vname4 = root.register(self.name4_entry)
        vyear = root.register(self.year_entry)
        vtopic = root.register(self.topic_entry)
        vbook = root.register(self.book_entry)
        vvolume = root.register(self.volume_entry)
        vissue = root.register(self.issue_entry)
        vpage = root.register(self.page_entry)

        self.iname1 = Entry(root,
                            validate="key",
                            validatecommand=(vname1, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname1.place(x=110, y=80)
        self.iname2 = Entry(root,
                            validate="key",
                            validatecommand=(vname2, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname2.place(x=110, y=110)
        self.iname3 = Entry(root,
                            validate="key",
                            validatecommand=(vname3, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname3.place(x=110, y=140)
        self.iname4 = Entry(root,
                            validate="key",
                            validatecommand=(vname4, '%P'),
                            width=40,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black')
        self.iname4.place(x=110, y=170)
        self.year = Entry(root,
                          validate="key",
                          validatecommand=(vyear, '%P'),
                          width=20,
                          bg='#3C3F41',
                          fg='yellow',
                          relief=FLAT,
                          highlightbackground='#2B2B2B',
                          highlightthickness=0.5,
                          highlightcolor='black').place(x=90, y=220)
        self.topic = Entry(root,
                           validate="key",
                           validatecommand=(vtopic, '%P'),
                           bg='#3C3F41',
                           fg='yellow',
                           relief=FLAT,
                           highlightbackground='#2B2B2B',
                           highlightthickness=0.5,
                           highlightcolor='black').place(width=304,
                                                         height=70,
                                                         x=90,
                                                         y=250)
        self.book = Entry(root,
                          validate="key",
                          validatecommand=(vbook, '%P'),
                          bg='#3C3F41',
                          fg='yellow',
                          relief=FLAT,
                          highlightbackground='#2B2B2B',
                          highlightthickness=0.5,
                          highlightcolor='black').place(width=304,
                                                        height=70,
                                                        x=90,
                                                        y=330)
        self.volume = Entry(root,
                            validate="key",
                            validatecommand=(vvolume, '%P'),
                            width=20,
                            bg='#3C3F41',
                            fg='yellow',
                            relief=FLAT,
                            highlightbackground='#2B2B2B',
                            highlightthickness=0.5,
                            highlightcolor='black').place(x=90, y=430)
        self.issue = Entry(root,
                           validate="key",
                           validatecommand=(vissue, '%P'),
                           width=20,
                           bg='#3C3F41',
                           fg='yellow',
                           relief=FLAT,
                           highlightbackground='#2B2B2B',
                           highlightthickness=0.5,
                           highlightcolor='black').place(x=90, y=460)
        self.page = Entry(root,
                          validate="key",
                          validatecommand=(vpage, '%P'),
                          width=20,
                          bg='#3C3F41',
                          fg='yellow',
                          relief=FLAT,
                          highlightbackground='#2B2B2B',
                          highlightthickness=0.5,
                          highlightcolor='black').place(x=90, y=490)

        self.verify_name1.config(text='☐')
        self.verify_name2.config(text='☐')
        self.verify_name3.config(text='☐')
        self.verify_name4.config(text='☐')
        self.verify_year.config(text='☐')
        self.verify_volume.config(text='☐')
        self.verify_issue.config(text='☐')
        self.verify_page.config(text='☐')

        self.correctname1 = self.correctname2 = self.correctname3 = self.correctname4 = self.correcttopic = self.correctbook = self.correctyear = self.correctyear = self.correctissue = self.correctpage = ' '
Ejemplo n.º 56
0
    def __init__(self, master):
        ttk.Frame.__init__(self, master)
        self.master = master
        self.nb = ttk.Notebook(self.master)
        self.app = app
        self.main = Frame(self.nb)
        self.app.wm_title("Kiwa site calculations")
        self.app.resizable(1000, 1000)
        self.app.geometry("850x600")

        self.header_frame = Frame(self.main,
                                  width=600,
                                  height=50,
                                  borderwidth=5,
                                  relief='raised')
        self.calc_frame = Frame(self.main, width=500, height=50, borderwidth=1)
        self.header_frame.pack(side='top')
        self.calc_frame.pack(side='top')
        self.nb.add(self.main, text="Main Page")
        self.second_tab = SecondTab(self.nb)
        self.nb.add(self.second_tab, text="Second Page")
        self.nb.pack()

        self.L1 = Label(self.header_frame, text="Client", pady=15,
                        padx=10).grid(row=0, column=1)
        for i in range(5):
            Entry(self.header_frame).grid(row=1, column=1 + i)
        self.L2 = Label(self.header_frame, text="Site", pady=15,
                        padx=30).grid(row=0, column=2)

        self.L3 = Label(self.header_frame, text="Location", pady=15,
                        padx=30).grid(row=0, column=3)

        self.L4 = Label(self.header_frame, text="Job REF.", pady=15,
                        padx=30).grid(row=0, column=4)

        self.L5 = Label(self.header_frame, text="DATE", pady=15,
                        padx=30).grid(row=0, column=5)

        self.L6 = Label(self.header_frame,
                        text="Length under Test",
                        pady=5,
                        padx=0).grid(row=2, column=4)

        self.L7 = Label(self.header_frame,
                        text="Spec. load/m(Bedding)",
                        pady=5,
                        padx=0).grid(row=2, column=3)

        self.L7a = Label(self.header_frame, text="Kn/m", pady=0,
                         padx=0).grid(row=3, column=2)
        self.E7a = Entry(self.header_frame).grid(row=3, column=3)

        self.L7b = Label(self.header_frame, text="/m", pady=0,
                         padx=0).grid(row=4, column=2)
        self.E7b = Entry(self.header_frame).grid(row=4, column=3)

        self.L8 = Label(self.header_frame,
                        text="Spec. load/m(Proof)",
                        pady=0,
                        padx=0).grid(row=2, column=1)
        self.L8a = Label(self.header_frame, text="Kn/m", pady=0,
                         padx=0).grid(row=3, column=0)
        self.E8a = Entry(self.header_frame).grid(row=3, column=1)
        self.L8b = Label(self.header_frame, text="/m", pady=0,
                         padx=0).grid(row=4, column=0)
        self.E8b = Entry(self.header_frame).grid(row=4, column=1)

        self.L9 = Label(
            self.header_frame,
            text="Load at X(bedding)",
            pady=0,
            padx=0,
        ).grid(row=3, column=4)
        self.E9 = Entry(self.header_frame).grid(row=3, column=5)

        self.L10 = Label(
            self.header_frame,
            text="Load at X(Proof)",
            pady=0,
            padx=0,
        ).grid(row=4, column=4)
        self.E10 = Entry(self.header_frame).grid(row=4, column=5)

        self.l11 = Label(self.header_frame,
                         text="barrier type:",
                         pady=0,
                         padx=0).grid(row=3, column=6)
        barrier_menu = StringVar(self.header_frame)
        barriers = [
            "type 3 barrier", "type 4 barrier", "type 5 barrier",
            "type 6 barrier", "type 7 barrier", "type 8 barrier",
            "type 9 barrier"
        ]
        barrier_menu.set(barriers[0])
        drop_down_menu = OptionMenu(self.header_frame, barrier_menu, *barriers)
        drop_down_menu.grid(row=4, column=6)

        self.L11 = Label(self.calc_frame,
                         text="barrier, Span/ ",
                         pady=0,
                         padx=0).grid(row=0, column=0)
        self.sfL1 = Label(self.calc_frame,
                          text="BEDDING CYCLE",
                          pady=0,
                          padx=0).grid(row=1, column=0)
        self.sfL2 = Label(self.calc_frame, text="Max DEF.", pady=0,
                          padx=0).grid(row=2, column=0)
        self.sfL3 = Label(self.calc_frame,
                          text="Residual DEF.",
                          pady=0,
                          padx=0).grid(row=3, column=0)
        #For loop for full line entry boxes in second Frame
        for i in range(6):  #width of entry
            for j in range(9):  #height of entry
                if j == 1:  # skips row 2
                    continue
                if j == 4:
                    continue
                attraname = f"entry_column{i}_row{j}"
                setattr(self, attraname,
                        Entry(self.calc_frame).grid(row=0 + j, column=1 + i))

        self.sfL4 = Label(self.calc_frame, text="PROOF CYCLE", pady=2,
                          padx=0).grid(row=4, column=0)
        self.sfL5 = Label(self.calc_frame, text="Max DEF.", pady=0,
                          padx=0).grid(row=5, column=0)
        self.sfL6 = Label(self.calc_frame,
                          text="Residual DEF.",
                          pady=0,
                          padx=0).grid(row=6, column=0)
        self.sfL7 = Label(self.calc_frame, text="Recovery", pady=0,
                          padx=0).grid(row=7, column=0)
        self.sfL8 = Label(self.calc_frame, text="Recovery %", pady=0,
                          padx=0).grid(row=8, column=0)

        calc_button = Button(self.calc_frame,
                             text="submit",
                             command=self.store_entries).grid(row=9, column=3)

        menubar = Menu(app)
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="New")
        filemenu.add_command(label="Open")
        filemenu.add_command(label="Save")
        filemenu.add_command(label="Save as...")
        filemenu.add_command(label="Close")
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=app.quit)
        menubar.add_cascade(label="File", menu=filemenu)
        app.config(menu=menubar)
Ejemplo n.º 57
0
class DebuggerWindow:
    def __init__(self, bundle: MODI, buffer: StringIO):
        self._buffer = buffer
        self.bundle = bundle
        self.__input_box = None
        self._modules = []
        self.__log = None
        self.__spec = None
        self.__curr_module = None
        self.__curr_cmd = None
        self.__tell = 0
        self.__query = None
        self.__sid, self.__did, self.__cmd, self.__data = \
            None, None, None, None

    def run(self):
        width, height = 930, 790
        window = Tk()
        window.title(f"GUI Debugger for PyMODI (v{modi.__version__})")
        window.geometry(f"{width}x{height}")
        window.resizable(False, False)
        canvas = Canvas(window, width=width, height=height)
        canvas.create_rectangle(10, 40, 410, 340, outline='black')
        canvas.pack()

        # cmd (ins) field
        Label(window, text='c:').place(x=10, y=5)
        self.__cmd = Entry(window)
        self.__cmd.place(x=25, y=5, width=40)

        # sid field
        Label(window, text='s:').place(x=70, y=5)
        self.__sid = Entry(window)
        self.__sid.place(x=85, y=5, width=40)

        # did field
        Label(window, text='d:').place(x=130, y=5)
        self.__did = Entry(window)
        self.__did.place(x=145, y=5, width=40)

        # data field
        Label(window, text='b:').place(x=190, y=5)
        self.__data = Entry(window)
        self.__data.place(x=205, y=5, width=250)
        generate_button = Button(window, text="Generate", command=self.__parse)
        generate_button.place(x=455, y=5)

        # send field
        Label(window, text='msg:').place(x=545, y=5)
        self.__input_box = Entry(window)
        self.__input_box.place(x=580, y=5, width=250)
        self.__input_box["state"] = tk.DISABLED
        send_button = Button(window, text="Send", command=self.send)
        send_button.place(x=830, y=5)

        # TODO: Remove this __query related functions
        Label(window, text="Filter by Command: ").place(x=420, y=35)
        self.__query = Entry(window)
        self.__query.place(x=545, y=33, width=35)
        Button(window, text="Filter", command=self.__change_query).place(x=580,
                                                                         y=32)

        # log box (where MODI json messages are shown)
        self.__log = ScrolledText(window, wrap=WORD, font=('Helvetica', 12))
        self.__log.place(x=420, y=60, width=480, height=700)

        # spec box (where module information are shown)
        self.__spec = Label(window,
                            text=f"Running PyMODI (v{modi.__version__})",
                            bg='white',
                            anchor=NW,
                            justify='left',
                            font=('Helvetica', 15))
        self.__spec.place(x=10, y=350, width=400, height=390)

        # generate module button in the canvas
        for module in self.bundle.modules:
            self.__create_module_button(module, window)

        # run mainloop
        while True:
            try:
                window.update()
                self.__append_log()
                if self.__curr_module:
                    self.__change_spec(self.__curr_module)
            except TclError:
                break
            time.sleep(0.1)

    def __parse(self):
        try:
            # TODO: ensure each field is in a valid form
            cmd = eval(self.__cmd.get())
            sid = eval(self.__sid.get())
            did = eval(self.__did.get())
            data = eval(self.__data.get())
            msg = parse_message(cmd, sid, did, data)
            self.__input_box["state"] = tk.NORMAL
            self.__input_box.delete(0, END)
            self.__input_box.insert(0, msg)
            self.__input_box["state"] = tk.DISABLED
        except Exception as e:
            print("An exception in Tkinter callback has been raised:", e)
            self.__input_box["state"] = tk.NORMAL
            self.__input_box.delete(0, END)
            self.__input_box.insert(0, "Invalid Arguments")
            self.__input_box["state"] = tk.DISABLED

    def __query_log(self, line: str) -> bool:
        if ('recv' not in line and 'send' not in line) or \
            (self.__curr_module and str(self.__curr_module.id) not in line
                and self.__curr_module.module_type != 'network') \
                or (self.__curr_cmd and f'"c":{self.__curr_cmd},' not in line):
            return False
        return True

    def __change_query(self):
        self.__curr_cmd = self.__query.get()
        self.__update_log()

    def __update_log(self):
        self.__log.delete('0.0', END)
        log_text = self._buffer.getvalue()
        for line in log_text.split('\n'):
            if self.__query_log(line):
                self.__log.insert(INSERT, line + '\n')

    def __append_log(self):
        log_text = self._buffer.getvalue()
        new_text = log_text[self.__tell:]
        for line in new_text.split('\n'):
            if self.__query_log(line):
                self.__log.insert(INSERT, line + '\n')
            if line and 'send' not in line and 'recv' not in line:
                sys.__stdout__.write(line + '\n')
        self.__tell += len(new_text)
        self.__log.see(INSERT)

    def send(self):
        self.bundle.send(self.__input_box.get())

    def __change_spec(self, module):
        text = '\n'.join([
            f"Module Type: {module.module_type.upper()}", f"ID: {module.id}",
            f"UUID: {module.uuid}", f"STM32 Version: {module.version}",
            f"Contains User Code: {module.has_user_code}",
            f"Connected: {module.is_connected}"
        ])
        text += "\n[Properties]\n"
        # TODO: Fix code below to properly retrieve module properties
        for prop in module._properties:
            text += (f"{self.get_prop_name(prop, module)}: "
                     f"{module._properties[prop].value} "
                     f"last updated: "
                     f"{module._properties[prop].last_update_time}\n")
        self.__spec.configure(text=text)

    @staticmethod
    def get_prop_name(prop, module):
        module_props = module.__class__.__dict__
        for prop_key in module_props:
            if prop == module_props[prop_key]:
                return prop_key
        return prop

    def __create_module_button(self, module, window):
        module_button = Button(window,
                               text=f"{module.module_type}\n({module.id})")

        module_type = str(module.__class__)
        if 'output' in module_type:
            color = "orange"
        elif 'input' in module_type:
            color = "purple"
        else:
            color = "yellow"
        module_button.configure(bg=color,
                                command=lambda: self.__change_module(module))
        # TODO: Update button position as the module changes its position
        module_button.place(
            x=170 + 60 * module.position[0],
            y=180 - 40 * module.position[1],
            width=60,
            height=40,
        )
        # module button list
        self._modules.append(module_button)

    def __change_module(self, module):
        self.__curr_module = module
        self.__update_log()
Ejemplo n.º 58
0
class Window:
    def __init__(self, root):
        super().__init__()

        self.root = root
        self.label = Label(root,
                           text='Text_to_Speech',
                           font='arial 20 bold',
                           bg='white smoke',
                           fg='blue').pack()
        self.label2 = Label(root,
                            text='Data Flair',
                            font='arial 15 bold',
                            bg='white smoke',
                            fg='blue').pack(side=tk.BOTTOM)

        self.label3 = Label(root,
                            text='Enter Text',
                            font='arial 15 bold',
                            bg='white smoke').place(x=20, y=60)

        self.Msg = StringVar()
        self.E1 = Entry(root, textvariable=self.Msg, width='50')
        self.E1.place(x=20, y=100)

        self.btn = Button(root,
                          text="Play",
                          fg='green',
                          font="arial 15 bold",
                          command=self.Text_to_speech,
                          width=4)
        self.btn.place(x=25, y=140)
        self.btn2 = Button(root,
                           text="Exit",
                           font="arial 15 bold",
                           command=self.Exit,
                           bg='OrangeRed1')
        self.btn2.place(x=100, y=140)
        self.btn3 = Button(root,
                           text="Reset",
                           font="arial 15 bold",
                           command=self.Reset)
        self.btn3.place(x=175, y=140)
        self.btn4 = Button(root,
                           text="Text",
                           font="arial 15 bold",
                           command=self.Write_text)
        self.btn4.place(x=25, y=200)

    def Text_to_speech(self):
        self.Message = self.E1.get()
        self.speech = gTTS(text=self.Message, lang="tr")
        self.speech.save('DataFlair.mp3')
        mixer.init()
        mixer.music.load('./DataFlair.mp3')  #add path
        mixer.music.play()

    def Exit(self):
        self.root.destroy()

    def Reset(self):
        self.Msg.set("")

    def Write_text(self):
        self.newWindow = Toplevel(self.root)
        self.pencere = Other_Window(self.newWindow)
Ejemplo n.º 59
0
class calc:
    def getandreplace(self):
        # reemplaza x con * y ÷ con /
        self.expression = self.e.get()
        self.newtext = self.expression.replace('÷', '/')
        self.newtext = self.newtext.replace('x', '*')

    def equals(self):
        # Cuando presionas el boton =
        self.getandreplace()
        try:
            # evalua la expresion usando la funcion eval
            self.value = eval(self.newtext)
        except SyntaxError:
            self.e.delete(0, END)
            self.e.insert(0, 'Entrada inválida')
        else:
            self.e.delete(0, END)
            self.e.insert(0, self.value)

    def squareroot(self):
        # Raíz cuadrada
        self.getandreplace()
        try:
            # evalua la expresion usando la funcion eval
            self.value = eval(self.newtext)
        except SyntaxError:
            self.e.delete(0, END)
            self.e.insert(0, 'Entrada inválida')
        else:
            self.sqrtval = math.sqrt(self.value)
            self.e.delete(0, END)
            self.e.insert(0, self.sqrtval)

    def square(self):
        # Elevar al cuadrado
        self.getandreplace()
        try:
            # evalua la expresion usando la funcion eval
            self.value = eval(self.newtext)
        except SyntaxError:
            self.e.delete(0, END)
            self.e.insert(0, 'Entrada inválida')
        else:
            self.sqval = math.pow(self.value, 2)
            self.e.delete(0, END)
            self.e.insert(0, self.sqval)

    def clearall(self):
        # Limpia el cuadro de texto
        self.e.delete(0, END)

    def clear1(self):
        # elimina lo ultimo ingresado al cuadro de texto
        self.txt = self.e.get()[:-1]
        self.e.delete(0, END)
        self.e.insert(0, self.txt)

    def action(self, argi):
        # El valor del boton presionado es añadido al final del cuadro de texto
        self.e.insert(END, argi)

    def __init__(self, master):
        # Método constructor
        master.title('Caluladora')
        master.geometry()
        self.e = Entry(master)
        self.e.grid(row=0, column=0, columnspan=6, pady=3)
        self.e.focus_set()  # Pone el focus en el cuadro de texto

        # Botones
        Button(master, text="=", width=10,
               command=lambda: self.equals()).grid(row=4,
                                                   column=4,
                                                   columnspan=2)
        Button(master, text='AC', width=3,
               command=lambda: self.clearall()).grid(row=1, column=4)
        Button(master, text='C', width=3,
               command=lambda: self.clear1()).grid(row=1, column=5)
        Button(master, text="+", width=3,
               command=lambda: self.action('+')).grid(row=4, column=3)
        Button(master, text="x", width=3,
               command=lambda: self.action('x')).grid(row=2, column=3)
        Button(master, text="-", width=3,
               command=lambda: self.action('-')).grid(row=3, column=3)
        Button(master, text="÷", width=3,
               command=lambda: self.action('÷')).grid(row=1, column=3)
        Button(master, text="%", width=3,
               command=lambda: self.action('%')).grid(row=4, column=2)
        Button(master, text="7", width=3,
               command=lambda: self.action(7)).grid(row=1, column=0)
        Button(master, text="8", width=3,
               command=lambda: self.action(8)).grid(row=1, column=1)
        Button(master, text="9", width=3,
               command=lambda: self.action(9)).grid(row=1, column=2)
        Button(master, text="4", width=3,
               command=lambda: self.action(4)).grid(row=2, column=0)
        Button(master, text="5", width=3,
               command=lambda: self.action(5)).grid(row=2, column=1)
        Button(master, text="6", width=3,
               command=lambda: self.action(6)).grid(row=2, column=2)
        Button(master, text="1", width=3,
               command=lambda: self.action(1)).grid(row=3, column=0)
        Button(master, text="2", width=3,
               command=lambda: self.action(2)).grid(row=3, column=1)
        Button(master, text="3", width=3,
               command=lambda: self.action(3)).grid(row=3, column=2)
        Button(master, text="0", width=3,
               command=lambda: self.action(0)).grid(row=4, column=0)
        Button(master, text=".", width=3,
               command=lambda: self.action('.')).grid(row=4, column=1)
        Button(master, text="(", width=3,
               command=lambda: self.action('(')).grid(row=2, column=4)
        Button(master, text=")", width=3,
               command=lambda: self.action(')')).grid(row=2, column=5)
        Button(master, text="√", width=3,
               command=lambda: self.squareroot()).grid(row=3, column=4)
        Button(master, text="x²", width=3,
               command=lambda: self.square()).grid(row=3, column=5)
Ejemplo n.º 60
0
)
input_background_box_cursor.grid(column=0, row=0, sticky=(W, E, S))
input_background_box_cursor.insert("end", cursor_text)
input_background_box_cursor.config(foreground=order_font_data.foreground)

# 输入栏
order = StringVar()
order_font = font.Font(family=order_font_data.font,
                       size=order_font_data.font_size)
inputbox = Entry(
    input_background_box,
    borderwidth=0,
    insertborderwidth=0,
    selectborderwidth=0,
    highlightthickness=0,
    bg=order_font_data.background,
    foreground=order_font_data.foreground,
    selectbackground=order_font_data.selectbackground,
    textvariable=order,
    font=order_font,
    width=normal_config.config_normal.inputbox_width,
)
inputbox.grid(column=1, row=0, sticky=(N, E, S))

input_event_func = None
send_order_state = False
# when false, send 'skip'; when true, send cmd


def send_input(*args):
    """