示例#1
0
 def initUI(self):
   
     self.parent.title("Absolute positioning")
     self.pack(fill=BOTH, expand=1)
     
     style = Style()
     style.configure("TFrame", background="#333")        
     
     bard = Image.open("bardejov.jpg")
     bardejov = ImageTk.PhotoImage(bard)
     #We create an image object and a photo image object from an image in the current working directory.
     label1 = Label(self, image=bardejov)
     #We create a Label with an image. Labels can contain text or images.
     label1.image = bardejov
     #We must keep the reference to the image to prevent image from being garbage collected.
     label1.place(x=20, y=20)
     #The label is placed on the frame at x=20, y=20 coordinates.
     
     rot = Image.open("rotunda.jpg")
     rotunda = ImageTk.PhotoImage(rot)
     label2 = Label(self, image=rotunda)
     label2.image = rotunda
     label2.place(x=40, y=160)        
     
     minc = Image.open("mincol.jpg")
     mincol = ImageTk.PhotoImage(minc)
     label3 = Label(self, image=mincol)
     label3.image = mincol
     label3.place(x=170, y=50)        
 def initUI(self):
   
     self.parent.title("Absolute positioning")
     self.pack(fill=BOTH, expand=1)
     
     style = Style()
     style.configure("TFrame", background="#333")        
     
     bard = Image.open("bardejov.jpg")
     bardejov = ImageTk.PhotoImage(bard)
     label1 = Label(self, image=bardejov)
     label1.image = bardejov
     label1.place(x=20, y=20)
     
     rot = Image.open("rotunda.jpg")
     rotunda = ImageTk.PhotoImage(rot)
     label2 = Label(self, image=rotunda)
     label2.image = rotunda
     label2.place(x=40, y=160)        
     
     minc = Image.open("mincol.jpg")
     mincol = ImageTk.PhotoImage(minc)
     label3 = Label(self, image=mincol)
     label3.image = mincol
     label3.place(x=170, y=50)        
示例#3
0
class ticketWindow(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.title("Zendesk Views")
        self.style = Style()
        self.style.theme_use("default")
        self.style.configure("TFrame", background="#333")
        self.style.configure("TLabel", backgroun="#444")
        self.pack(fill=BOTH, expand=1)
        self.centerWindow()
        ticket1 = ticketViews(parent, 26887076)
        ticket2 = ticketViews(parent, 35868228)

    def centerWindow(self):
        w = 250
        h = 100

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        x = (sw) / 2
        y = (sh) / 2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def createQuit(self):
        quitButton = Button(self, text="Quit", command=self.quit)
        quitButton.place(x=50, y=50)
示例#4
0
def display_ClassConfigs(name,self,controller):
	i=1;j=2; # Column and row incrementers
	sty = Style(self); sty.configure("TSeparator", background="black");
	if name == "DetailsPage":
		inputdata = load_configdata(); set_configunits(); # Load data, store units
		for key in Application.key_order:
			if i>7:	i = 1; j = j+1; # Column limit exceeded, begin new row
			labelName = tk.Label(self,font = NORMAL_FONT,text=key + ":"); labelName.grid(column=i, row=j);
			fieldName = tk.Entry(self); fieldName.grid(column=i+2, row=j, rowspan=1);
			fieldName.insert(1,inputdata[key]);	fieldName.configure(state="readonly");
			if Application.units_set[key] != "None":
				unitsLabel = tk.Label(self,font = NORMAL_FONT,text="("+Application.units_set[key]+")"); unitsLabel.grid(column=i+4, row=j);
			sep = Separator(self, orient="vertical")
			sep.grid(column=6, row=j-1, rowspan=2, sticky="nsew")
			Application.DetailsPage_entries.append(fieldName); Application.DetailsPage_labels.append(labelName); # Store widgets 
			i = i+6 # Column for Second label/entry pair
		backbutton = tk.Button(self, bd = "2", fg = "white", bg = "blue", font = NORMAL_FONT, text="Back",command=lambda: controller.show_frame(SettingsPage)).grid(row=int(math.ceil(len(Application.key_order)/2))+2,column=13,rowspan=1)
		editbutton = tk.Button(self, bd = "2", fg = "white", bg = "gray", font = NORMAL_FONT, text="Edit",command=lambda: controller.show_frame(EditConfigsPage)).grid(row=int(math.ceil(len(Application.key_order)/2))+2,column=12,rowspan=1)
	else:
		for key in Application.key_order:
			if i>7: i = 1; j = j+1; # Column limit exceeded, begin new row
			labelName = tk.Label(self,font = NORMAL_FONT,text=key + ":"); labelName.grid(column=i, row=j);
			fieldName = tk.Entry(self); fieldName.grid(column=i+2, row=j);
			fieldName.insert(5,Application.configData[key]); # Create entry, add data
			if Application.units_set[key] != "None":
				unitsLabel = tk.Label(self,font = NORMAL_FONT,text="("+Application.units_set[key]+")"); unitsLabel.grid(column=i+4, row=j);
			sep = Separator(self, orient="vertical")
			sep.grid(column=6, row=j-1, rowspan=2, sticky="nsew")
			Application.EditPage_entries.append(fieldName); Application.EditPage_labels.append(labelName); # Store widgets
			i = i+6 # Column for Second label/entry pair
		Application.firstEdit = False # Config settings have been edited
	pad_children(self) # Assign padding to child widgets
示例#5
0
class ticketWindow(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.title("Zendesk Views")
        self.style = Style()
        self.style.theme_use("default")
        self.style.configure("TFrame", background="#333")
        self.style.configure("TLabel", backgroun="#444")
        self.pack(fill=BOTH, expand=1)
        self.centerWindow()
        ticket1 = ticketViews(parent, 26887076)
        ticket2 = ticketViews(parent, 35868228)

    def centerWindow(self):
        w = 250
        h = 100

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        
        x = (sw) /2
        y = (sh) /2
        self.parent.geometry('%dx%d+%d+%d' % (w, h ,x ,y))

    def createQuit(self):
        quitButton = Button(self, text="Quit", command=self.quit)
        quitButton.place(x=50, y=50)
示例#6
0
 def initUI(self):
   
     self.parent.title("Absolute positioning")
     self.pack(fill=BOTH, expand=1)
     
     style = Style()
     style.configure("TFrame", background="#333")        
示例#7
0
    def initUI(self):

        var = IntVar()

        #General stuff
        self.parent.title("I2C Command Manager")
        self.style = Style()
        self.style.theme_use("default")
        #self.pack(fill=BOTH, expand=1)
        self.parent.configure(background=Constants.BG_COL)

        s = Style()
        s.configure('C.TRadiobutton', background=Constants.BG_COL)

        #Quit button
        quitButton = Button(self.parent, text="Quit", command=self.quit)
        quitButton.place(x=Constants.QUIT_X, y=Constants.QUIT_Y)

        #Radiobuttons
        ledRadio = Radiobutton(
            self.parent,
            text="LED Strip",
            variable=var,
            value=1,
            command=lambda: self.instructor.setAddress(0x04),
            style='C.TRadiobutton')
        vertRadio = Radiobutton(
            self.parent,
            text="Vertical Motion",
            variable=var,
            value=2,
            command=lambda: self.instructor.setAddress(0x06),
            style='C.TRadiobutton')
        ledRadio.place(x=Constants.LED_X, y=Constants.LED_Y)
        vertRadio.place(x=Constants.VERT_X, y=Constants.VERT_Y)
        #ledRadio.configure(background = Constants.BG_COL)

        #Label
        sendLabel = Label(self.parent,
                          text="Enter command:",
                          background=Constants.BG_COL)
        sendLabel.place(x=Constants.SENDL_X, y=Constants.SENDL_Y)

        #Address label
        adLabel = Label(self.parent,
                        text="Select address:",
                        background=Constants.BG_COL)
        adLabel.place(x=Constants.ADL_X, y=Constants.ADL_Y)

        #Text entry box
        textBox = Entry(self.parent, bd=2, width=Constants.TEXT_W)
        textBox.place(x=Constants.TEXT_X, y=Constants.TEXT_Y)

        #Send command button
        sendButton = Button(self.parent,
                            text="Send",
                            command=lambda: self.assignCommand(textBox.get()))
        sendButton.place(x=Constants.SENDB_X, y=Constants.SENDB_Y)
示例#8
0
 def SetupStyles(self):
     if TTK:
         style = Style(self.master)
         style.configure('Color.TLabel', foreground=self.fg,
                         background=self.bg)
         style.configure('Color.TFrame', background=self.bg)
         self.ttkstyle = style
         self.style = lambda w, style: w.configure(style=style)
     else:
         self.style = PoorManStyle(self,
             styles={'Color.TLabel': {'fg': self.fg, 'bg': self.bg},
                     'Color.TFrame': {'bg': self.bg}}).style_it
示例#9
0
class TrackFrame(Frame):
    def __init__(self, master, track):
        Frame.__init__(self, master)
        self.track = track

        self.style_class = Style()
        self.style_class.configure('Track.TFrame',
                                   background='black',
                                   borderwidth=2,
                                   # relief='raised',
                                   )

        self.config(style='Track.TFrame')
示例#10
0
def test():
    tkroot = Tk()

    s = Style()

    s.configure('Title.TLabel', font="ariel 20 bold")
    s.configure('TButton', font="ariel 14 bold")
    tkroot.option_add("*TButton.Font", "ariel 12 bold")
    tkroot.option_add("*Label.Font", "Helvetica 10")

    fail_str = "LogFinalTestStatus RT_Final='FAIL'\n+++OUT OF RANGE+++ F1_TX0_IQOffset == -16.2532762607\n+++OUT OF RANGE+++ F1_TX1_PwrDac == 28\n+++OUT OF RANGE+++ F1_TX1_DataEvm == -31.6506357937\n+++OUT OF RANGE+++ F1_TX1_IQOffset == -2.30501317739\n+++OUT OF RANGE+++ F2_TX0_IQOffset == -15.214029339\n+++OUT OF RANGE+++ F2_TX1_DataEvm == -30.5567960708\n+++OUT OF RANGE+++ F2_TX1_IQOffset == -12.6593769606"

    StatusWindow( tkroot, "Test Status -- 00:27:22:DA:00:01", "PASS\n".rstrip() )
    StatusWindow( tkroot, "Test Status -- 00:27:22:DA:00:01", "FAIL\n".rstrip(), fail_str )
示例#11
0
def test():
    tkroot = Tk()

    s = Style()

    s.configure('Title.TLabel', font="ariel 20 bold")
    s.configure('TButton', font="ariel 14 bold")
    tkroot.option_add("*TButton.Font", "ariel 12 bold")
    tkroot.option_add("*Label.Font", "Helvetica 10")

    fail_str = "LogFinalTestStatus RT_Final='FAIL'\n+++OUT OF RANGE+++ F1_TX0_IQOffset == -16.2532762607\n+++OUT OF RANGE+++ F1_TX1_PwrDac == 28\n+++OUT OF RANGE+++ F1_TX1_DataEvm == -31.6506357937\n+++OUT OF RANGE+++ F1_TX1_IQOffset == -2.30501317739\n+++OUT OF RANGE+++ F2_TX0_IQOffset == -15.214029339\n+++OUT OF RANGE+++ F2_TX1_DataEvm == -30.5567960708\n+++OUT OF RANGE+++ F2_TX1_IQOffset == -12.6593769606"

    StatusWindow(tkroot, "Test Status -- 00:27:22:DA:00:01", "PASS\n".rstrip())
    StatusWindow(tkroot, "Test Status -- 00:27:22:DA:00:01", "FAIL\n".rstrip(),
                 fail_str)
示例#12
0
    def __init__(self, parent, dicogis_path="../../"):
        """Instanciating the output workbook."""
        self.parent = parent
        Frame.__init__(self)
        logging.info('Isogeo PySDK version: {0}'.format(pysdk_version))

        # logo
        ico_path = path.join(path.abspath(dicogis_path),
                             "data/img/DicoGIS_logo.gif")
        self.icone = PhotoImage(master=self,
                                file=ico_path)
        Label(self,
              borderwidth=2,
              image=self.icone).grid(row=1, columnspan=2,
                                     column=0, padx=2,
                                     pady=2, sticky=W)
        # credits
        s = Style(self)
        s.configure('Kim.TButton', foreground='DodgerBlue', borderwidth=0)
        btn_credits = Button(self,
                             text='by @GeoJulien\nGPL3 - 2017',
                             style='Kim.TButton',
                             command=lambda: open_new_tab('https://github.com/Guts/DicoGIS'))
        btn_credits.grid(row=2,
                         columnspan=2,
                         padx=2,
                         pady=2,
                         sticky="WE")

        # contact
        mailto = "mailto:DicoGIS%20Developer%20"\
                 "<*****@*****.**>?"\
                 "subject=[DicoGIS]%20Question"
        btn_contact = Button(self,
                             text="\U00002709 " + "Contact",
                             command=lambda: open_new_tab(mailto))

        # source
        url_src = "https://github.com/Guts/DicoGIS/issues"
        btn_src = Button(self,
                         text="\U000026A0 " + "Report",
                         command=lambda: open_new_tab(url_src))

        # griding
        btn_contact.grid(row=3, column=0, padx=2, pady=2,
                         sticky="WE")
        btn_src.grid(row=3, column=1, padx=2, pady=2,
                     sticky="EW")
示例#13
0
文件: biab.py 项目: ob/biab
 def layout_gui(self):
     master = self.master
     s = Style()
     s.theme_use('default')
     s.configure('TProgressbar', thickness=50)
     helv36 = tkFont.Font(family='Helvetica', size=36, weight='bold')
     b = Button(master, text="Quit", command=self.quit, width=10, height=2)
     b['font'] = helv36
     b.grid(row=0, column=0)
     pb = Progressbar(master,
                      orient=VERTICAL,
                      length=100,
                      mode='determinate',
                      style='TProgressbar')
     pb['value'] = 50
     pb.grid(row=0, column=1)
示例#14
0
文件: app.py 项目: claudemuller/pydle
    def _initUI(self):
        self.parent.title("Pydle v" + self.version)
        self.parent.minsize(width=str(self.screenWidth), height=str(self.screenHeight))
        # self.parent.config(border=0)

        # Styles
        style = Style()
        style.configure("TFrame", background="gray", border=0)
        style.configure("TButton", background="gray", foreground="lightgray", highlightforeground="black", highlightbackground="darkgray", compound=RIGHT, relief=FLAT)

        self.config(style="TFrame")
        self.pack(fill=BOTH, expand=1)

        # Menus
        mnuBar = Menu(self.parent)
        self.parent.config(menu=mnuBar)

        mnuFile = Menu(mnuBar, background="gray")
        mnuFile.add_command(label="Exit", command=self.onExitMnu)
        mnuBar.add_cascade(label="File", menu=mnuFile)

        mnuHelp = Menu(mnuBar, background="gray")
        mnuHelp.add_command(label="About", command=self.onAboutMnu)
        mnuBar.add_cascade(label="Help", menu=mnuHelp)

        # Frame content
        frmBooks = Frame(self, style="TFrame")
        frmBooks.pack(side=LEFT, anchor=N+W, fill=BOTH, expand=1, padx=(self.padding, self.padding / 2), pady=self.padding)

        self.lstBooks = Listbox(frmBooks)
        self.lstBooks.config(background="lightgray", foreground="black", borderwidth=0)
        self.lstBooks.pack(fill=BOTH, expand=1)

        frmButtons = Frame(self)
        frmButtons.pack(anchor=N+E, padx=(self.padding / 2, self.padding), pady=self.padding)

        btnLoadBooks = Button(frmButtons, text="Load Books", style="TButton", command=self.onLoadBooksBtn)
        btnLoadBooks.pack(side=TOP, fill=X)

        btnGetNotes = Button(frmButtons, text="Get Notes", style="TButton", command=self.onGetNotesBtn)
        btnGetNotes.pack(side=TOP, fill=X)

        btnBackupBook = Button(frmButtons, text="Backup Book", style="TButton", command=self.onBackupBtn)
        btnBackupBook.pack(side=TOP, fill=X)

        btnBackupAllBooks = Button(frmButtons, text="Backup All Books", style="TButton", command=self.onBackupAllBtn)
        btnBackupAllBooks.pack(side=TOP, fill=X)
    def initUI(self):
        self.parent.title("Minesweeper")
        s = Style()
        s.theme_use('classic')
        s.configure('TButton',
                    width=2,
                    padding=(0, 0, 0, 0),
                    background='#b9b9b9',
                    relief=tk.FLAT)
        s.map('TButton',
              background=[('disabled', '#555555'), ('pressed', '#777777'),
                          ('active', '#a8a8a8')])
        s.configure('Cleared.TButton', background='white')
        s.map('Cleared.TButton', background=[('active', 'white')])
        s.configure('Flagged.TButton', background='0066ff')
        s.map('Flagged.TButton', background=[('active', '#0044dd')])
        s.configure('Revealed.TButton', background='black')
        s.map('Revealed.TButton', background=[('active', 'black')])
        s.configure('Triggered.TButton', background='red')
        s.map('Triggered.TButton', background=[('active', 'red')])
        minefield = Minefield()
        self.__minefield = minefield

        # self.button_frame = Frame(self.parent)
        for i in range(minefield.get_row_count()):
            self.rowconfigure(i, pad=0)
        for i in range(minefield.get_column_count()):
            self.columnconfigure(i, pad=0)

        for row in range(minefield.get_row_count()):
            self.buttons.append(list())
            for column in range(minefield.get_column_count()):
                cell = minefield.get_cell([row, column])
                coordinates = cell.get_coordinates()
                button = Button(self, style='TButton')

                def run(event, self=self, internal_coordinates=coordinates):
                    return self.click_action(event, internal_coordinates)

                button.bind('<Button-1>', run)
                button.bind('<Button-2>', run)
                button.bind('<Button-3>', run)
                button.grid(row=row, column=column)
                self.buttons[row].append(button)

        self.pack()
示例#16
0
    def initUI(self, size):
        """
        Init application GUI
        :return void
        """
        self.root.title(self.title)

        self.root.minsize(400, 210)

        self.set_geometry(size)

        style = Style()
        style.configure("TFrame", background="#FFF")

        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        self.root.title(self.title)
        self.root.configure(background='#FFF')

        # Footer (with ok and quit buttons)
        self.footer = Frame(self.root)
        self.footer.pack(side=BOTTOM, expand=YES)

        self.mainFrame = Frame(self.root)
        self.mainFrame.pack(side=TOP, fill=BOTH)

        # Main canvas
        self.canvas = Canvas(self.mainFrame,
                             bd=1,
                             scrollregion=(0, 0, 1000, 1000),
                             height=600)
        self.canvas.pack(side=TOP, fill=BOTH)

        # creates canvas so that screen can be scrollable
        self.scrollbar = Scrollbar(self.mainFrame, command=self.canvas.yview)
        self.canvas.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.pack(side=RIGHT, fill=Y)
        self.canvas.pack(expand=YES, fill=BOTH)

        # Settings frame
        self.scrolledFrame = Frame(self.canvas, width=100, height=100)
        self.scrolledFrame.pack(expand=1, fill=BOTH)

        self.canvas.create_window(0, 0, anchor=NW, window=self.scrolledFrame)

        self.populate()
示例#17
0
    def createWidgets(self, master):

        #-Set-progress-bar-style-for-custom-thickness--
        s = Style()
        s.theme_use("default")
        s.configure("TProgressbar", thickness=5)
        #----------------------------------------------

        master.grid_rowconfigure(0, weight=1)
        master.grid_columnconfigure(0, weight=1)

        # +++++++++++++++++++++++++++++++

        row = 0
        col = 0
        w = LabelFrame(master, text='Sample positioner status')
        w.grid(row=row, column=col, sticky=NSEW, padx=5, pady=5)
        self.populateDisplayPanel(w)
示例#18
0
def test():
    global ButtonFont, TitleFont
    root = Tk()
    s = Style()

    s.configure('Title.TLabel', font="ariel 20 bold")
    s.configure('TButton', font="ariel 14 bold")

    #    pw = EntryWindow( root, "Scan UUT barcode ", 'Enter UUT serial number', '002722DA0000')
    #    print pw.answer.get()
    #    pw = PromptWindow( root,"**** Ready UUT for test ****",
    #                       "1) Place board in test fixture\n" + \
    #                       "2) Connect the cables\n\n",
    #                       yestxt = "Start Test", notxt = "Exit Program")
    #    print pw.answer.get()

    pw = InfoWindow(
        None, 'Ready board %s for test' % '0123456789AB',
        "1) Place board in test fixture\n2) Connect the cables\nOK when ready")
示例#19
0
    def __init__(self, parent, dicogis_path="../../"):
        """Instanciating the output workbook."""
        self.parent = parent
        Frame.__init__(self)
        logging.info('Isogeo PySDK version: {0}'.format(pysdk_version))

        # logo
        ico_path = path.join(path.abspath(dicogis_path),
                             "data/img/DicoGIS_logo.gif")
        self.icone = PhotoImage(master=self, file=ico_path)
        Label(self, borderwidth=2, image=self.icone).grid(row=1,
                                                          columnspan=2,
                                                          column=0,
                                                          padx=2,
                                                          pady=2,
                                                          sticky=W)
        # credits
        s = Style(self)
        s.configure('Kim.TButton', foreground='DodgerBlue', borderwidth=0)
        btn_credits = Button(
            self,
            text='by @GeoJulien\nGPL3 - 2017',
            style='Kim.TButton',
            command=lambda: open_new_tab('https://github.com/Guts/DicoGIS'))
        btn_credits.grid(row=2, columnspan=2, padx=2, pady=2, sticky="WE")

        # contact
        mailto = "mailto:DicoGIS%20Developer%20"\
                 "<*****@*****.**>?"\
                 "subject=[DicoGIS]%20Question"
        btn_contact = Button(self,
                             text="\U00002709 " + "Contact",
                             command=lambda: open_new_tab(mailto))

        # source
        url_src = "https://github.com/Guts/DicoGIS/issues"
        btn_src = Button(self,
                         text="\U000026A0 " + "Report",
                         command=lambda: open_new_tab(url_src))

        # griding
        btn_contact.grid(row=3, column=0, padx=2, pady=2, sticky="WE")
        btn_src.grid(row=3, column=1, padx=2, pady=2, sticky="EW")
示例#20
0
def test():
    tkroot = Tk()
    s = Style()

    s.configure('Title.TLabel', font="ariel 20 bold")
    s.configure('TButton', font="ariel 14 bold")

    tkroot.option_add("*TButton.Font", "ariel 12 bold")
    tkroot.option_add("*Label.Font", "Helvetica 12 bold")

    #    tkroot.tk.call('wm', 'iconbitmap', tkroot._w, '-default', './bmp/scope.ico')

    tkroot.title('test_station.ini Test')
    cfg = test_station_cfg()
    cfg.print_cfg()
    frame = ConfigFrame(tkroot, cfg)
    frame.grid()

    tkroot.mainloop()
示例#21
0
文件: main.py 项目: OanaRatiu/Licenta
class FirstWindow(Frame):
    def __init__(self, parent, controller, listener):
        Frame.__init__(self, parent)

        self.parent = parent
        self.controller = controller
        self.listener = listener
        self.controller.add_listener(self.listener)
        self.initUI()

    def initUI(self):
        self.centerWindow()

        self.parent.title("Cursor")
        self.style = Style()
        self.style.theme_use("clam")
        self.style.configure("TFrame")

        self.pack(fill=BOTH, expand=1)

        self.label = Label(self)
        self.label.configure(text="Hold your hand above the device for two seconds...")
        self.label.place(x=50, y=50)

        quitButton = Button(self, text="Quit",
                            command=self.quit)
        quitButton.place(x=50, y=100)

    def update_label(self):
        self.label.configure(text="You can now use the cursor.")

    def remove(self):
        self.controller.remove_listener(self.listener)

    def centerWindow(self):
        w, h = 450, 180

        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()

        x = (sw - w)/2
        y = (sh - h)/2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
示例#22
0
def test():
    tkroot = Tk()
    s = Style()

    s.configure('Title.TLabel', font="ariel 20 bold")
    s.configure('TButton', font="ariel 14 bold")

    tkroot.option_add("*TButton.Font", "ariel 12 bold")
    tkroot.option_add("*Label.Font", "Helvetica 12 bold")

#    tkroot.tk.call('wm', 'iconbitmap', tkroot._w, '-default', './bmp/scope.ico')


    tkroot.title('test_station.ini Test')
    cfg = test_station_cfg()
    cfg.print_cfg()
    frame = ConfigFrame(tkroot, cfg)
    frame.grid()

    tkroot.mainloop()
示例#23
0
 def initUI(self):
     self.parent.title("Absolute positioning")
     self.pack(fill=BOTH, expand=1)
     style = Style()
     style.configure("TFrame", background="#333")
     bard = Image.open("bardejov.jpg")
     bardejov = ImageTk.PhotoImage(bard)
     label1 = Label(self, image=bardejov)
     label1.image = bardejov
     label1.place(x=20, y=20)
     rot = Image.open("rotunda.jpg")
     rotunda = ImageTk.PhotoImage(rot)
     label2 = Label(self, image=rotunda)
     label2.image = rotunda
     label2.place(x=40, y=160)
     minc = Image.open("mincol.jpg")
     mincol = ImageTk.PhotoImage(minc)
     label3 = Label(self, image=mincol)
     label3.image = mincol
     label3.place(x=170, y=50)
示例#24
0
 def SetupStyles(self):
     if TTK:
         style = Style(self.master)
         style.configure('Color.TLabel',
                         foreground=self.fg,
                         background=self.bg)
         style.configure('Color.TFrame', background=self.bg)
         self.ttkstyle = style
         self.style = lambda w, style: w.configure(style=style)
     else:
         self.style = PoorManStyle(self,
                                   styles={
                                       'Color.TLabel': {
                                           'fg': self.fg,
                                           'bg': self.bg
                                       },
                                       'Color.TFrame': {
                                           'bg': self.bg
                                       }
                                   }).style_it
示例#25
0
class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.quote = "I was supposed to be a cool quote . But then internet abandoned me !"
        self.author = "Aditya"
        self.project = [{"name":"Portfolio","location": "F:\git\portfolio","command": "http://localhost:8080"},{"name":"JStack","location":"F:\git\JStack" ,"command": "http://localhost:8080"},{"name":"GPS_Track","location": "F:\git\GPS_Track","command": "http://localhost:8080"}]
        self.getQuote()

    def initUI(self):

        self.parent.title("Buttons")
        self.style = Style()
        self.style.theme_use("alt")

        # Styling
        self.style.configure('.', font=('Helvetica', 12), background="#300A24")
        self.style.configure(
            "PW.TLabel", foreground="#fff", background="#300A24", padding=20, justify=CENTER, wraplength="350")
        self.style.configure(
            "Medium.TButton", foreground="#300A24", background="#fff", borderwidth=0, padding=8, font=('Helvetica', 9))
        # Styling Ends

        quoteLabel = Label(self, text=self.quote, style="PW.TLabel")
        quoteLabel.pack()
        authorLabel = Label(self, text=self.author, style="PW.TLabel")
        authorLabel.pack()

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

        closeButton = Button(self, text="Close This",
                             style="Medium.TButton", command=self.parent.quit)
        closeButton.pack(side=RIGHT)
        projectButton = Button(self, text=self.project[0]["name"],
                          style="Medium.TButton", command=lambda: self.btnFn(0))
        projectButton.pack(side=RIGHT)
        projectButton = Button(self, text=self.project[1]["name"],
                          style="Medium.TButton", command=lambda: self.btnFn(1))
        projectButton.pack(side=RIGHT)
        projectButton = Button(self, text=self.project[2]["name"],
                          style="Medium.TButton", command=lambda: self.btnFn(2))
        projectButton.pack(side=RIGHT)

    def getQuote(self):
        # j = json.loads(requests.get(
            # "http://quotes.stormconsultancy.co.uk/random.json").text)
        # self.quote = j["quote"]
        # self.author = j["author"]
        self.initUI()

    def btnFn(self,index):
        subprocess.Popen(
            ['explorer', self.project[index]["location"]])
        subprocess.Popen(
            ['subl', self.project[index]["location"]])
        subprocess.Popen(
            ['console'], cwd=self.project[index]["location"])
        subprocess.Popen(
            ['chrome', self.project[index]["command"]])
示例#26
0
    def initUI(self):
        self.parent.title("Absolute positioning")
        self.pack(fill=BOTH, expand=1)

        style = Style()
        style.configure("TFrame", background="lightgreen")

        image1=Image.open("images.jpg")
        images = ImageTk.PhotoImage(image1)
        label1=Label(self, image = images)
        label1.image = images
        label1.place(x=20,y=20)

        image1=Image.open("images.jpg")
        images = ImageTk.PhotoImage(image1)
        label2=Label(self, image = images)
        label2.image = images
        label2.place(x=20,y=215)

        image1=Image.open("images.jpg")
        images = ImageTk.PhotoImage(image1)
        label3=Label(self, image = images)
        label3.image = images
        label3.place(x=280,y=20)
    def initUI(self):

        #Parent Frame
        self.parent.title("Test Stand Control Panel")
        self.style = Style()
        self.style.theme_use("default")

        self.pack(fill=BOTH, expand=1)


        # Frame 1 (top)
        frame1 = Frame(self)
        frame1.pack(fill=X, expand=1)

            #Start motor button
        startButton = Button(frame1, text="Start Motor",
            command=self.startMotor)
        startButton.pack(side=LEFT, padx=5, pady=5)     


            #Throttle slider
        lbl1 = Label(frame1, text="Throttle (0-100):", width=14)
        lbl1.pack(side=LEFT, padx=5, pady=5)
        
        self.scale = Scale(frame1, from_=0, to=100, 
            command=self.onScaleThrottle)
        self.scale.pack(side=LEFT, padx=15)
        
        self.label = Label(frame1, text="throttle", textvariable=self.throttlevar, width=5)        
        self.label.pack(side=LEFT)

            #Throttlesweep checkbutton
        self.autovar = BooleanVar()
        cb = Checkbutton(frame1, text="Throttle Sweep",
            variable=self.autovar, command=self.onClickAuto)
        cb.pack(side=LEFT, padx=15)

            #Com port selection field
        droplbl = Label(frame1, text="Serial Port:", width=10)
        droplbl.pack(side=LEFT, padx=5, pady=5)
        self.selected_s_Port = StringVar()
        self.s_Ports = []
        self.drop = OptionMenu(frame1,self.selected_s_Port,"None",*self.s_Ports)
        self.drop.pack(side=LEFT, padx=5)

            #baudrate selection field (disabled)
##       drop2lbl = Label(frame1, text="Baudrate:", width=9)
##        drop2lbl.pack(side=LEFT, padx=5, pady=5)
##        self.baudrate = StringVar()
##        baudrates = [9600, 19200, 38400, 57600, 115200]
##        drop2 = OptionMenu(frame1,self.baudrate,*baudrates)
##        drop2.pack(side=LEFT, padx=5)

            #Start serial button
        comsButton = Button(frame1, text="Start Serial",
            command=self.startSerial)
        comsButton.pack(side=LEFT, padx=5, pady=5)

            #Stop serial button
        comsStopButton = Button(frame1, text="Stop Serial",
            command=self.stopSerial)
        comsStopButton.pack(side=LEFT, padx=5, pady=5)

        # Frame 2 (second line)
        frame2 = Frame(self)
        frame2.pack(fill=X, expand=1)

            #Amperage entry
        lbl2 = Label(frame2, text="Max Motor Current (A):", width=21)
        lbl2.pack(side=LEFT, padx=5, pady=5)
        
        self.MaxA_Entry = Entry(frame2)
        self.MaxA_Entry.pack(side="left", fill=X, padx=5, expand=False)
        self.MaxA_Entry.insert(0, 10)

            #Voltage entry
        lbl3 = Label(frame2, text="Max Motor Voltage (V):", width=20)
        lbl3.pack(side=LEFT, padx=5, pady=5)
        
        self.MaxV_Entry = Entry(frame2)
        self.MaxV_Entry.pack(side="left", fill=X, padx=5, expand=False)
        self.MaxV_Entry.insert(0, 14)

            #Update button
        updateButton = Button(frame2, text="Update Values",
            command=self.updateValues)
        updateButton.pack(side=LEFT, padx=5, pady=5)
        
        # Graph Frame
        framegraph = Frame(self)
        framegraph.pack(fill=X, expand=1)

            #Init figures
        f = Figure(figsize=(4,4), dpi=100)
        self.a = f.add_subplot(2, 2, 1)
        self.d = f.add_subplot(2, 2, 4)
        self.c = f.add_subplot(2, 2, 3)
        self.b = f.add_subplot(2, 2, 2)
        
        f.set_tight_layout(True)

        self.canvas = matplotlib.backends.backend_tkagg.FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)

            #Display Toolbar
        toolbar = NavigationToolbar2TkAgg(self.canvas, framegraph)
        toolbar.update()
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=True)
        
        # Frame 0 (Bottom text)
        frame0 = Frame(self)
        frame0.pack(side="bottom", fill="x", expand=1)

            #Display text (allows to give user information)
        self.textboxvar = StringVar()
        self.info = Label(frame0, textvariable=self.textboxvar)
        self.info.pack(side=LEFT, padx=5, pady=5)

        # Button Frame (large buttons, near bottom)
        s = Style() #has its own style
        s.configure('My.TFrame',background='#f7edc3') #fancy colors
        framered = Frame(self, style='My.TFrame')
        framered.pack(side="bottom", fill="x", expand=1)
        #used the tk instead of ttk library for this, allows font and color mods

            #Save Button
        self.saveButton = tk.Button(framered, text="Save Data", bg='green', font=('Arial',20,'bold'),
            command=self.saveData)
        self.saveButton.pack(side="left", padx=5, pady=5)

            #Log button
        self.logButton = tk.Button(framered, text="Start Data Logging", bg="blue", font=('Arial',20,'bold'),
            command=self.logData)
        self.logButton.pack(side="left", padx=5, pady=5)

            #Stop button
        self.stopButton = tk.Button(framered, text="Stop Motor", bg='red', font=('Arial',20,'bold'),
            command=self.stopMotor)
        self.stopButton.pack(side="right", padx=5, pady=5)
示例#28
0
class Gui(threading.Thread):
    """
    Gui class contains tkinter gui attributes and logic.
    When gui closed, is_running flag set to false to end
    bot actions when possible. Gui remains open until
    bot thread reaches end of run and sets driver to None.
    """
    def __init__(self):
        threading.Thread.__init__(self)

        # Reference to bot object. Allows bi-directional
        # communication between gui and bot objects
        self.bot = None

        # Bot checks this variable to see status
        self.is_running = True
        self.secret_key_initialized = False

        # Integer value of time till next refresh of search results
        # Value is set after 'do_update()' completes scraping results.
        # Reduces by 1 every second in gui loop while gui is running.
        # If gui is no longer running, bot ends gui loop and thread.
        self.countdown = 0
        self.countdown_max = 0

        # Setup root
        self.root = Tk()
        self.root.geometry("+50+50")
        self.root.resizable(0, 0)
        self.root.title("Teams Praise Counter")
        self.root.after(100, self.change_icon)
        self.root.attributes('-topmost', True)
        self.root.protocol('WM_DELETE_WINDOW', self.confirm_quit)

        # Setup frame
        self.root.frame = Frame(self.root)
        self.root.frame.pack(expand=1, side="top", fill="x")

        self.progress_frame = Frame(self.root)
        self.progress_frame.pack(expand=1, side="top", fill="x")

        self.button_frame = Frame(self.root)
        self.button_frame.pack(expand=1, side="top", fill="x")

        # Console label
        self.console_label = Label(self.root.frame,
                                   text="Console: ",
                                   justify="left",
                                   anchor="w")

        # Console text area
        self.console_text_frame = Frame(self.root.frame)
        self.console_text_frame.pack(side="top",
                                     expand="yes",
                                     fill="x",
                                     padx=10,
                                     pady=(10, 10))

        # Vertical Scroll Bar
        self.console_y_scroll_bar = Scrollbar(self.console_text_frame)
        self.console_y_scroll_bar.pack(side="right", fill="y")

        # Set text area to text widget
        self.console_text_area = Text(
            self.console_text_frame,
            width=80,
            height=10,
            yscrollcommand=self.console_y_scroll_bar.set,
            font=("Helvetica", 7))
        self.console_text_area.pack(side="top")

        # Configure the scrollbars
        self.console_y_scroll_bar.config(command=self.console_text_area.yview)

        # Refresh timer progress bar
        self.progress_bar_style = Style(self.root)
        self.progress_bar_style.theme_use("default")
        self.progress_bar = None
        self.root.after(100, self.load_progress_bar)

        # Initialize buttons and status label - Settings, Status, Start
        self.settings_button = Button(self.button_frame,
                                      text="Settings",
                                      width=28,
                                      height=2,
                                      command=self.start_stop_bot)
        self.settings_button.pack(side="left",
                                  padx=(10, 5),
                                  pady=(10, 10),
                                  fill="x",
                                  expand=1)

        self.start_stop_button = Button(self.button_frame,
                                        text="Start",
                                        width=28,
                                        height=2,
                                        command=self.start_stop_bot)
        self.start_stop_button.pack(side="left",
                                    padx=(5, 10),
                                    pady=(10, 10),
                                    fill="x",
                                    expand=1)

    def load_progress_bar(self):
        """
        Load progress bar method used with root.after.
        If root.after not used, gui will not load.
        """
        self.progress_bar_style.layout("progress_bar", [
            ("progress_bar.trough", {
                "children": [("progress_bar.pbar", {
                    "side": "left",
                    "sticky": "ns"
                }), ("progress_bar.label", {
                    "sticky": ""
                })],
                "sticky":
                "nswe",
            })
        ])

        self.progress_bar = Progressbar(self.progress_frame,
                                        orient="horizontal",
                                        style="progress_bar")
        self.progress_bar.pack(expand=1,
                               fill="x",
                               side="left",
                               padx=10,
                               ipadx=3,
                               ipady=3)
        self.progress_bar["value"] = 0

        self.progress_bar_style.configure("progress_bar",
                                          background="deepskyblue",
                                          font=('Helvetica', 8),
                                          pbarrelief="flat",
                                          troughrelief="flat",
                                          troughcolor="ghostwhite")
        self.update_progress_label("Press Start to Launch Automation")

    def update_progress_bar(self, current_time, max_time):
        """
        Update progress bar using current and max time with percentage
        :param current_time: integer current time till refresh in seconds
        :param max_time: integer max time till refresh in seconds
        """
        try:
            self.update_progress_label(
                "{} seconds until next refresh".format(current_time))
            self.progress_bar["value"] = (
                (max_time - current_time) / float(max_time)) * 100
        except TclError:
            # Invalid command name "configure" for progress_bar["value"]
            pass

    def update_progress_label(self, text):
        """
        Wrapper used to call actual method using root.after
        :param text: string text used for progress label
        """
        self.root.after(100, lambda: self.update_progress_label_after(text))

    def update_progress_label_after(self, text):
        """
        Set progress bar label text. Must be called using root.after
        :param text: string text used for progress label
        """
        # Spaces added after text to center string on progress bar
        self.progress_bar_style.configure("progress_bar",
                                          text="{}     ".format(text))

    def change_icon(self):
        """
        Change icon outside of main thread. If after is not used,
        application will hang when an icon change attempt is made
        """
        self.root.iconbitmap(self.resource_path("icon.ico"))

    @staticmethod
    def resource_path(relative_path):
        """
        When EXE generated, icon is bundled. When EXE executed, icon
        and other resources placed in temp folder. Function identifies
        whether to use current working directory or temp folder.
        :param relative_path: string relative path of file name
        :return: full path name of file including resource directory
        """
        if hasattr(sys, '_MEIPASS'):
            # noinspection PyProtectedMember
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

    def start_stop_bot(self):
        """
        Start or stop bot. Runtime error thrown if thread already started.
        """
        try:
            if self.bot.is_open():

                # Not in 'stop_bot()' to allow faster disabling of button
                self.start_stop_button["text"] = "Stopping ..."
                self.disable(self.start_stop_button)

                # After disabling button, driver is closed. After driver
                # closes successfully, buttons enabled and text changed.
                self.root.after(10, self.stop_bot)

        except AttributeError:
            # Bot object set to none exception
            self.start_bot()
        except RuntimeError:
            # Thread already running exception
            pass

    def start_bot(self):
        """
        Method called by start_stop_button to start bot.
        It creates a new bot instance and sets circular
        reference in gui and bot objects. After bot has
        been started, button text changed to Stop.
        """
        self.bot = Bot()
        self.bot.gui = self
        self.bot.start()
        self.start_stop_button["text"] = "Stop"

    def stop_bot(self):
        """
        Method called by root.after to close driver and
        change button text from Stopping to Start. Called
        by root.after to allow root to update while closing.
        """
        try:
            self.bot.driver.quit()
            self.bot = None
            self.enable(self.start_stop_button)
            self.start_stop_button["text"] = "Start"
            self.update_progress_label("Automation stopped")
        except (AttributeError, TclError):
            # Bot has already been closed
            pass

    def start_refresh_countdown(self):
        self.root.after(100, self.refresh_countdown)

    def refresh_countdown(self):
        if self.bot is None:
            self.update_progress_label("Automation stopped")
            return

        if self.countdown > 0:
            self.countdown = self.countdown - 1
            self.root.after(
                100, lambda: self.update_progress_bar(self.countdown, self.
                                                      countdown_max))
            self.root.after(1000, self.refresh_countdown)
        else:
            self.update_progress_label("Running refresh automation ...")

    def log(self, text, timestamp=True):
        """
        Add text to gui console log given string parameter.
        :param text: string text to be added to gui console
        :param timestamp: boolean is timestamp added to text
        :return: boolean True if gui is running, otherwise
            return False. If required in case gui has been
            closed and bot attempts to add to log.
        """
        if not self.is_running:
            return False

        # Add timestamp to beginning of text string
        if timestamp:
            text = datetime.datetime.now().strftime(
                "%Y-%m-%d %H:%M:%S") + " : " + text

        # Enable text area, add text, move cursor to end, disable text area
        self.enable(self.console_text_area)
        self.console_text_area.insert("insert", text)
        self.console_text_area.see("end")
        self.disable(self.console_text_area)

        return True

    @staticmethod
    def enable(widget):
        """
        Enables tkinter widget. Primarily used to enable
        text widgets to allow writing text into widget.
        :param widget: tkinter widget object
        """
        try:
            widget.config(state="normal")
        except tkinter.TclError:
            # Widget not found exception
            pass

    @staticmethod
    def disable(widget):
        """
        Disable tkinter widget. Primarily used to disable
        text widgets so user is not allowed to edit text area.
        :param widget: tkinter widget object
        """
        try:
            widget.config(state="disabled")
        except tkinter.TclError:
            # Widget not found exception
            pass

    def confirm_quit(self):
        """
        Handle gui close logic. Sets 'is_running' variable to
        False. When bot sees gui is no longer running, bot
        begins closing thread process and driver is set to None.
        Root is destroyed once bot thread has ended gracefully.
        """
        if tkMessageBox.askokcancel("Quit", "Do you really wish to quit?"):
            self.log("Closing application. Please wait ...")
            # Update required to show message in console log
            self.root.update()
            self.is_running = False
            try:
                # Wait for bot driver to close
                while self.bot.driver is not None:
                    pass
            except AttributeError:
                # Bot stopped and set to None
                pass
            self.root.destroy()

    def run(self):
        """
        Gui threading class start thread method.
        Performed when Threading.start() performed.
        """
        self.root.mainloop()
示例#29
0
class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.quote = "I was supposed to be a cool quote . But then internet abandoned me !"
        self.author = "Aditya"
        self.initUI()
        # self.getQuote()

    def initUI(self):

        self.parent.title("Buttons")
        self.style = Style()
        self.style.theme_use("alt")

        # Styling
        self.style.configure('.', font=('Helvetica', 12), background="#300A24")
        self.style.configure(
            "PW.TLabel", foreground="#fff", background="#300A24", padding=20, justify=CENTER, wraplength="350")
        self.style.configure(
            "Medium.TButton", foreground="#300A24", background="#fff", borderwidth=0, padding=8, font=('Helvetica', 9))
        # Styling Ends

        quoteLabel = Label(self, text=self.quote, style="PW.TLabel")
        quoteLabel.pack()
        authorLabel = Label(self, text=self.author, style="PW.TLabel")
        authorLabel.pack()

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

        closeButton = Button(self, text="Close This",
                             style="Medium.TButton", command=self.parent.quit)
        closeButton.pack(side=RIGHT)
        okButton = Button(
            self, text="Portfolio", style="Medium.TButton", command=self.btnOneFn)
        okButton.pack(side=RIGHT)
        okButton = Button(self, text="JStack",
                          style="Medium.TButton", command=self.btnTwoFn)
        okButton.pack(side=RIGHT)
        okButton = Button(self, text="Python",
                          style="Medium.TButton", command=self.btnThreeFn)
        okButton.pack(side=RIGHT)

    def hello(self):
        print("Print Hello")

    def getQuote(self):
        j = json.loads(requests.get(
            "http://quotes.stormconsultancy.co.uk/random.json").text)
        self.quote = j["quote"]
        self.author = j["author"]

    def btnOneFn(self):
        subprocess.Popen(
            ['nautilus', "/mnt/864A162B4A16190F/git/portfolio"])
        subprocess.Popen(
            ['gnome-terminal'], cwd=r'/mnt/864A162B4A16190F/git/portfolio')

    def btnTwoFn(self):
        subprocess.Popen(
            ['nautilus', "/mnt/864A162B4A16190F/git/JStack"])
        subprocess.Popen(
            ['gnome-terminal'], cwd=r'/mnt/864A162B4A16190F/git/JStack')

    def btnThreeFn(self):
        subprocess.Popen(
            ['nautilus', "/mnt/864A162B4A16190F/git/Python"])
        subprocess.Popen(
            ['gnome-terminal'], cwd=r'/mnt/864A162B4A16190F/git/Python')
示例#30
0
文件: gui.py 项目: superizer/Python-
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.quote = "I was supposed to be a cool quote . But then internet abandoned me !"
        self.author = "Aditya"
        self.project = [{
            "name": "Portfolio",
            "location": "F:\git\portfolio",
            "command": "http://localhost:8080"
        }, {
            "name": "JStack",
            "location": "F:\git\JStack",
            "command": "http://localhost:8080"
        }, {
            "name": "GPS_Track",
            "location": "F:\git\GPS_Track",
            "command": "http://localhost:8080"
        }]
        self.getQuote()

    def initUI(self):

        self.parent.title("Buttons")
        self.style = Style()
        self.style.theme_use("alt")

        # Styling
        self.style.configure('.', font=('Helvetica', 12), background="#300A24")
        self.style.configure("PW.TLabel",
                             foreground="#fff",
                             background="#300A24",
                             padding=20,
                             justify=CENTER,
                             wraplength="350")
        self.style.configure("Medium.TButton",
                             foreground="#300A24",
                             background="#fff",
                             borderwidth=0,
                             padding=8,
                             font=('Helvetica', 9))
        # Styling Ends

        quoteLabel = Label(self, text=self.quote, style="PW.TLabel")
        quoteLabel.pack()
        authorLabel = Label(self, text=self.author, style="PW.TLabel")
        authorLabel.pack()

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

        closeButton = Button(self,
                             text="Close This",
                             style="Medium.TButton",
                             command=self.parent.quit)
        closeButton.pack(side=RIGHT)
        projectButton = Button(self,
                               text=self.project[0]["name"],
                               style="Medium.TButton",
                               command=lambda: self.btnFn(0))
        projectButton.pack(side=RIGHT)
        projectButton = Button(self,
                               text=self.project[1]["name"],
                               style="Medium.TButton",
                               command=lambda: self.btnFn(1))
        projectButton.pack(side=RIGHT)
        projectButton = Button(self,
                               text=self.project[2]["name"],
                               style="Medium.TButton",
                               command=lambda: self.btnFn(2))
        projectButton.pack(side=RIGHT)

    def getQuote(self):
        # j = json.loads(requests.get(
        # "http://quotes.stormconsultancy.co.uk/random.json").text)
        # self.quote = j["quote"]
        # self.author = j["author"]
        self.initUI()

    def btnFn(self, index):
        subprocess.Popen(['explorer', self.project[index]["location"]])
        subprocess.Popen(['subl', self.project[index]["location"]])
        subprocess.Popen(['console'], cwd=self.project[index]["location"])
        subprocess.Popen(['chrome', self.project[index]["command"]])
示例#31
0
def calc_pad(data):
    """Функция, вызывающая окно новой записи в таблице расходов и реализующая
    эту запись"""

    def press_number(but):

        if calc_pad.new:
            if but <> '.':
                calc_pad.string.set(but)
                calc_pad.new = FALSE
            else:
                calc_pad.string.set('0.')
                calc_pad.new = FALSE
                calc_pad.cent = 1
        else:
            if (len(calc_pad.string.get()) < 11) and (calc_pad.cent < 3):
                if but <> '.':
                    calc_pad.string.set(calc_pad.string.get() + but)
                    if calc_pad.cent:
                        calc_pad.cent += 1
                else:
                    if '.' not in calc_pad.string.get():
                        calc_pad.string.set(calc_pad.string.get() + '.')
                        calc_pad.cent = 1


    def press_operation(but): # ('C', '<', '=')

        if but == 'C':
            calc_pad.operation = ''
            calc_pad.number = 0
            calc_pad.new = True
            calc_pad.cent = 0
            calc_pad.string.set('0')

        elif but == '<':
            if not calc_pad.new:
                st = calc_pad.string.get()
                calc_pad.string.set(st[:-1])
                if calc_pad.cent:
                    calc_pad.cent -= 1
                if calc_pad.string.get() == '0':
                    calc_pad.new = True
                if calc_pad.string.get() == '':
                    calc_pad.new = True
                    calc_pad.string.set('0')

        elif but == u'Ввод':
            selected = listbox.curselection()
            summ = float(calc_pad.string.get())

            if not selected:
                tkMessageBox.showerror(u'Ошибка!', u'Выберите причину расходов')
            elif summ == 0:
                window_calc.destroy()
                tkMessageBox.showinfo(u'Обращаю внимание',
               u'Учитывая, что сумма расходов равна нулю, запись не проведена.')
            elif tkMessageBox.askokcancel(u'Внимание!', u'Вы уверены, что' +
                               u'хотите добавить сумму %.2f в Расходы?' % summ):
                reason = reasons[int(selected[0])]
                comment = memo.get(1.0,END)
                queries.cash_out(reason, summ, comment)
                window_calc.destroy()

        elif but == 'X':
            window_calc.destroy()


    def b_up():
        """Срабатывает при нажатии кнопки 'вверх'"""

        selected = listbox.curselection()
        if selected:
            index = int(selected[0])
            if index > 0:
                listbox.selection_clear(index)
                listbox.selection_set(index-1)
                listbox.see(index-2)
        else:
            count = listbox.size()
            if count:
                listbox.selection_set(count - 1)
                listbox.see(count - 1)


    def b_down():
        """Срабатывает при нажатии кнопки 'вниз'"""

        selected = listbox.curselection()
        if selected:
            index = int(selected[0])
            if index < listbox.size() - 1:
                listbox.selection_clear(index)
                listbox.selection_set(index + 1)
                listbox.see(index + 1)
        else:
            if listbox.size():
                listbox.selection_set(0)
                listbox.see(0)

    #-----------------------------------------------------------------


    calc_pad.button_text = ('1', '2', '3', 'C',
                        '4', '5', '6', '<',
                        '7', '8', '9', 'X',
                        '0', '.',  u'Ввод')

    calc_pad.button_text_operation = ('C', 'X', '<', u'Ввод')

    calc_pad.operation = ''
    calc_pad.number = 0
    calc_pad.new = True
    calc_pad.cent = 0

    window_calc = Toplevel()
    window_calc.resizable(False, False)
    window_calc.title(u'Расходы')
    window_calc.geometry('+%d+%d' % (calc_pad.x, calc_pad.y))

    # потом переписать в общие стили
    style = Style(window_calc)
    style.configure('Number.TButton', foreground='blue', justify='center',
                                    font=('Lucida Console', CALC_SCALE, 'bold'))
    style.configure('Operation.TButton', foreground='red', justify='center',
                                    font=('Lucida Console', CALC_SCALE, 'bold'))
    #=======

    calc_pad.string = StringVar()
    calc_pad.string.set('0')

    label = Label(window_calc, textvariable = calc_pad.string,
                  width=13, bg='white', justify=RIGHT,
                  font=('Lucida Console', CALC_SCALE, 'bold'), anchor=E)
    label.grid(column=0, row=0, columnspan=4, padx=CALC_PAD, pady=CALC_PAD*2)

    buttons = []
    for but in calc_pad.button_text:
        if but in calc_pad.button_text_operation:
            buttons.append(Button(window_calc, text=but,
                                  style='Operation.TButton', width=1,
                                  command=lambda but=but: press_operation(but)))
        else:
            buttons.append(Button(window_calc,
                                  text=but,
                                  style='Number.TButton',
                                  width=1,
                                  command=lambda but=but: press_number(but)))

    for y in range(1, 4):
        for x in range(0, 3):
            buttons[x+(y-1)*4].grid(column=x, row=y, padx=CALC_PAD,
                        pady=CALC_PAD, ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2)
    buttons[3].grid(column=3, row=1, padx=CALC_PAD, pady=CALC_PAD,
                                       ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2)
    buttons[7].grid(column=3, row=2, padx=CALC_PAD, pady=CALC_PAD,
                                       ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2)
    buttons[11].grid(column=3, row=3, padx=CALC_PAD, pady=CALC_PAD,
                                       ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2)
    buttons[12].grid(column=0, row=4, padx=CALC_PAD, pady=CALC_PAD,
                                       ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2)
    buttons[13].grid(column=1, row=4, padx=CALC_PAD, pady=CALC_PAD,
                                       ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2)
    buttons[14].grid(column=2, row=4, padx=CALC_PAD, pady=CALC_PAD, sticky='we',
                         columnspan=2, ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2)

    rightFrame = Frame(window_calc)
    rightFrame.grid(column=4, row=0, padx=CALC_PAD, pady=CALC_PAD,
                                                       sticky='nwes', rowspan=5)

    memo = Text(rightFrame, height=3,font=('Lucida Console', BILL_FONT_SIZE),
                                                                       width=20)
    memo.pack(side=BOTTOM, fill=X, expand=NO)
    Label(rightFrame, text=u'Дополнительный комментарий:',
        font=('Lucida Console', FONT_SIZE)).pack(side=BOTTOM, pady=5)

    frame_left_button = Frame(rightFrame)
    frame_left_button.pack(side=RIGHT, fill=Y)
    button_up = Button(frame_left_button, image=data.IMG_INTERFACE[2],
                                                                   command=b_up)
    button_up.pack(side=TOP, padx=5, pady=10)
    button_down = Button(frame_left_button, image=data.IMG_INTERFACE[1],
                                                                 command=b_down)
    button_down.pack(side=TOP, padx=5, pady=0)

    scrollbar = Scrollbar(rightFrame)
    listbox = Listbox(rightFrame,
                       yscrollcommand=scrollbar.set,
                       width = 25,
                       activestyle='dotbox',
                       font=('Lucida Console', BILL_FONT_SIZE))
    listbox.pack(side=LEFT, fill=BOTH)
    scrollbar.config(command=listbox.yview)
    scrollbar.pack(side=RIGHT, fill=Y)

    reasons = []

    for item in queries.cash_out_reasons():
        if item.active:
            reasons.append(item)
            listbox.insert(END, ' ' + item.text)

    window_calc.update()
    parent_name = window_calc.winfo_parent()
    parent = window_calc._nametowidget(parent_name)
    parentX, parentY = parent.winfo_width(), parent.winfo_height()
    childX, childY = window_calc.winfo_width(), window_calc.winfo_height()
    calc_pad.x = (parentX - childX)/2
    calc_pad.y = (parentY - childY)/2

    window_calc.geometry('+%d+%d' % (calc_pad.x, calc_pad.y))
    window_calc.grab_set()
    window_calc.focus_set()
    window_calc.wait_window()
示例#32
0
    def __init__(self, master, columns, data=None, command=None, sort=True, select_mode=None, heading_anchor = CENTER, cell_anchor=W, style=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, field_background=None, heading_font= None, heading_background=None, heading_foreground=None, cell_pady=2, cell_background=None, cell_foreground=None, cell_font=None, headers=True):

        self._stripped_rows = stripped_rows

        self._columns = columns
        
        self._number_of_rows = 0
        self._number_of_columns = len(columns)
        
        self.row = self.List_Of_Rows(self)
        self.column = self.List_Of_Columns(self)
        
        s = Style()

        if style is None:
            style_name = "Multicolumn_Listbox%s.Treeview"%self._style_index
            self._style_index += 1
        else:
            style_name = style
        
        style_map = {}
        if selection_background is not None:
            style_map["background"] = [('selected', selection_background)]
            
        if selection_foreground is not None:
            style_map["foeground"] = [('selected', selection_foreground)]

        if style_map:
            s.map(style_name, **style_map)

        style_config = {}
        if cell_background is not None:
            style_config["background"] = cell_background

        if cell_foreground is not None:
            style_config["foreground"] = cell_foreground

        if cell_font is None:
            font_name = s.lookup(style_name, "font")
            cell_font = nametofont(font_name)
        else:
            if not isinstance(cell_font, Font):
                if isinstance(cell_font, basestring):
                    cell_font = nametofont(cell_font)
                else:
                    if len(font) == 1:
                        cell_font = Font(family=cell_font[0])
                    elif len(font) == 2:
                        cell_font = Font(family=cell_font[0], size=cell_font[1])
                        
                    elif len(font) == 3:
                        cell_font = Font(family=cell_font[0], size=cell_font[1], weight=cell_font[2])
                    else:
                        raise ValueError("Not possible more than 3 values for font")
        
            style_config["font"] = cell_font
        
        self._cell_font = cell_font

        self._rowheight = cell_font.metrics("linespace")+cell_pady
        style_config["rowheight"]=self._rowheight

        if field_background is not None:
            style_config["fieldbackground"] = field_background

        s.configure(style_name, **style_config)

        heading_style_config = {}
        if heading_font is not None:
            heading_style_config["font"] = heading_font
        if heading_background is not None:
            heading_style_config["background"] = heading_background
        if heading_foreground is not None:
            heading_style_config["foreground"] = heading_foreground

        heading_style_name = style_name + ".Heading"
        s.configure(heading_style_name, **heading_style_config)

        treeview_kwargs = {"style": style_name}

        if height is not None:
            treeview_kwargs["height"] = height
            
        if padding is not None:
            treeview_kwargs["padding"] = padding
            
        if headers:
            treeview_kwargs["show"] = "headings"
        else:
            treeview_kwargs["show"] = ""
        
        if select_mode is not None:
            treeview_kwargs["selectmode"] = select_mode

        self.interior = Treeview(master, columns=columns, **treeview_kwargs)
        
        if command is not None:
            self._command = command
            self.interior.bind("<<TreeviewSelect>>", self._on_select)

        for i in range(0, self._number_of_columns):

            if sort:
                self.interior.heading(i, text=columns[i], anchor=heading_anchor, command=lambda col=i: self.sort_by(col, descending=False))
            else:
                self.interior.heading(i, text=columns[i], anchor=heading_anchor)
                
            if adjust_heading_to_content:
                self.interior.column(i, width=Font().measure(columns[i]))

            self.interior.column(i, anchor=cell_anchor)
            
        if data is not None:
            for row in data:
                self.insert_row(row)
示例#33
0
    def build(self):
        self.root = Tk()
        self.root.geometry("800x622+200+200")
        self.root.title("SecureMe")
        self.root.resizable(width=FALSE, height=FALSE)

        menubar = Menu(self.root)
        optionsmenu = Menu(menubar, tearoff=0)
        optionsmenu.add_command(label="Refresh (Ctrl+r)",
                                command=lambda: self.refresh("NONE"))
        optionsmenu.add_command(label="Exit", command=lambda: self.quitMenu())
        menubar.add_cascade(label="Options", menu=optionsmenu)
        self.root.config(menu=menubar)

        self.toolbar = ToolBar(self.root, self)

        style = Style()
        style.configure("BW.TLabel",
                        foreground="black",
                        background="slate gray",
                        borderwidth=2)

        mFrame = Frame(self.root, bg="slate gray", padx=25, pady=25)
        mFrame.pack(fill=BOTH)
        self.notebook = ttk.Notebook(mFrame, height=500, style="BW.TLabel")
        primaryFrame = Frame(self.notebook, padx=25, pady=25)
        usersFrame = Frame(self.notebook, padx=25, pady=25)
        firewallFrame = Frame(self.notebook, padx=25, pady=25)
        servicesFrame = Frame(self.notebook, padx=25, pady=25)
        processesFrame = Frame(self.notebook, padx=25, pady=25)
        self.notebook.add(primaryFrame, text='Primary')
        self.notebook.add(usersFrame, text='Users')
        self.notebook.add(firewallFrame, text='Firewall')
        self.notebook.add(servicesFrame, text='Services')
        self.notebook.add(processesFrame, text='Processes')
        self.notebook.pack(fill=X)

        self.updatebar = Frame(self.root)
        self.updatebar.pack(side=BOTTOM, fill=X)
        self.left_label = Label(self.updatebar, text="Status: None")
        self.left_label.pack(side=LEFT, fill=X)

        # Primary Panel
        primary_label = Label(primaryFrame,
                              text='Primary Settings',
                              font=self.liberation_font_15)
        primary_label.grid(row=0, column=0, columnspan=2, sticky=N + S + E + W)

        actionspanel = LabelFrame(primaryFrame,
                                  text='System Actions',
                                  padx=10,
                                  pady=10)
        actionspanel.grid(row=1, column=0, sticky=E + N, padx=25, pady=25)

        openterminal = Button(actionspanel,
                              text='Open Terminal',
                              command=lambda: self.openTerminal())
        openterminal.pack(padx=5, pady=5)

        opencontrol = Button(actionspanel,
                             text='Open Control Panel',
                             command=lambda: self.openControlPanel())
        opencontrol.pack(padx=5, pady=5)

        shutdown = Button(actionspanel,
                          text='Shutdown',
                          command=lambda: self.shutdown())
        shutdown.pack(padx=5, pady=5)

        rebootButton = Button(actionspanel,
                              text='Reboot',
                              command=lambda: self.reboot())
        rebootButton.pack(padx=5, pady=5)

        updatespanel = LabelFrame(primaryFrame,
                                  text='System Updates',
                                  padx=10,
                                  pady=10)
        updatespanel.grid(row=1, column=1, sticky=W + N, padx=25, pady=25)

        update_button = Button(updatespanel,
                               text='Basic Update',
                               command=lambda: self.basicUpdate())
        update_button.pack(padx=5, pady=5)

        upgrade_button = Button(updatespanel,
                                text='Basic Upgrade',
                                command=lambda: self.basicUpgrade())
        upgrade_button.pack(padx=5, pady=5)

        packageupdate_button = Button(updatespanel,
                                      text='Package Update',
                                      command=lambda: self.packageUpdate())
        packageupdate_button.pack(padx=5, pady=5)

        # Users Panel
        users_label = Label(usersFrame,
                            text='User Security Settings',
                            font=self.liberation_font_15)
        users_label.pack()

        editusers = Frame(usersFrame)
        editusers.pack()

        addusr = Button(editusers,
                        text='Add User...',
                        command=lambda: self.addUser())
        addusr.grid(row=0, column=0, padx=5, pady=5)

        delusr = Button(editusers,
                        text='Del User...',
                        command=lambda: self.delUser())
        delusr.grid(row=0, column=1, padx=5, pady=5)

        userpanel = LabelFrame(usersFrame, text="Users", padx=10, pady=10)
        userpanel.pack(side=TOP, fill=BOTH)

        self.uText = self.getUserText()
        self.users_listlabel = Label(userpanel,
                                     text=self.uText,
                                     padx=10,
                                     pady=10)
        self.users_listlabel.pack(side=LEFT)

        groupspanel = LabelFrame(usersFrame, text="Groups", padx=10, pady=10)
        groupspanel.pack(side=TOP, fill=BOTH)

        self.gText = self.getGroupText()
        self.groups_text = CustomText(groupspanel)
        self.groups_text.resetText(self.gText)
        self.groups_text.type(DISABLED)
        self.groups_text.pack(fill=BOTH)

        # Firewall Label
        firewall_label = Label(firewallFrame,
                               text='Firewall Settings',
                               font=self.liberation_font_15)
        firewall_label.pack()

        edFrame = Frame(firewallFrame)
        fwEnable = Button(edFrame,
                          text='Enable',
                          command=lambda: self.enableFirewall())
        fwEnable.pack(side=LEFT, padx=10, pady=10, fill=X)
        fwDisable = Button(edFrame,
                           text='Disable',
                           command=lambda: self.disableFirewall())
        fwDisable.pack(side=RIGHT, padx=10, pady=10, fill=X)
        edFrame.pack()

        firewallpanel = LabelFrame(firewallFrame,
                                   text='Firewall Status',
                                   height=100,
                                   width=450,
                                   padx=10,
                                   pady=10)
        firewallpanel.pack(side=TOP, fill=X)

        self.fText = self.getFirewallStatus()
        self.firewall_text = CustomText(firewallpanel)
        self.firewall_text.resetText(self.fText)
        self.firewall_text.type(DISABLED)
        self.firewall_text.pack(fill=X)

        # Services Pane
        services_label = Label(servicesFrame,
                               text='System Services',
                               font=self.liberation_font_15)
        services_label.pack()

        servicespanel = LabelFrame(servicesFrame,
                                   text="Services",
                                   padx=10,
                                   pady=10)
        servicespanel.pack(side=TOP, fill=BOTH)
        self.sText = self.getServicesText()
        self.services_text = CustomText(servicespanel)
        self.services_text.resetText(self.sText)
        self.services_text.type(DISABLED)
        self.services_text.pack(fill=BOTH)

        # Processes Pane
        processes_label = Label(processesFrame,
                                text='System Processes',
                                font=self.liberation_font_15)
        processes_label.pack()

        processespanel = LabelFrame(processesFrame,
                                    text='Processes',
                                    padx=10,
                                    pady=10)
        processespanel.pack(side=TOP, fill=BOTH)
        self.pText = self.getProcessesText()
        self.processes_text = CustomText(processespanel)
        self.processes_text.resetText(self.pText)
        self.processes_text.type(DISABLED)
        self.processes_text.pack(fill=BOTH)

        self.root.bind('<Control-r>', self.refresh)

        self.root.mainloop()
示例#34
0
try:
    from ttk import Style
except:
    from tkinter.ttk import Style

frc = '#b0d0b0'  # Frame, Notebook, Checkbutton
tbc = '#eaeaea'  # Toolbar, Button
figc = '#70a0c0' # Figure

sty = Style()
#sty.theme_use('classic')
sty.theme_use('alt')
sty.configure('TNotebook.Tab', background=frc, width=12)
sty.configure('TFrame', background=frc)
sty.configure('TCheckbutton', background=frc)
sty.configure('TButton', background=tbc, width=10)
sty.configure('TLabel', background=frc, relief='groove')
sty.configure('TEntry', background=frc)
示例#35
0
    def build_credits(self):

        if getattr(self, "home", False): self.home.pack_forget()
        if getattr(self, "license", False): self.license.pack_forget()

        self.credits = Frame(self.parent)
        self.credits.pack(expand=True, fill=BOTH)

        Label(self.credits, text="Credits",
              **self.style_text).pack(side=TOP, expand=True, fill=X)

        style = Style()
        style.configure("BW.TNotebook",
                        background=self.parent.cget("bg"),
                        borderwidth=1,
                        relief=SUNKEN,
                        highlightthickness=1)

        notebook = Notebook(self.credits, style="BW.TNotebook")

        write = (
            "Jean-Pierre Mandon",
            "Régis Blanchot",
            "Marcus Fazzi",
            "Jesus Carmona Esteban",
            "Alfred Broda",
            "Yeison Cardona",
            "Henk Van Beek",
            "Björn Pfeiffer",
            "Alexis Sánchez",
        )

        label_write = Label(self.credits, text="\n\n".join(write))
        label_write.pack(side=TOP, expand=True, fill=BOTH)
        notebook.add(label_write, text="Write by")

        doc = (
            "Benoit Espinola",
            "Sebastien Koechlin",
            "Ivan Ricondo",
            "Jesus Carmona Esteban",
            "Marcus Fazzi",
            "Régis Blanchot",
        )

        label_doc = Label(self.credits, text="\n\n".join(doc))
        label_doc.pack(side=TOP, expand=True, fill=BOTH)
        notebook.add(label_doc, text="Documented by")

        trans = (
            "Joan Espinoza",
            "Alexis Sánchez",
            "Régis Blanchot",
            "Moreno Manzini",
            "Yeison Cardona",
            "\"Avrin\"",
        )

        label_trans = Label(self.credits, text="\n\n".join(trans))
        label_trans.pack(side=TOP, expand=True, fill=BOTH)
        notebook.add(label_trans, text="Translated by")

        art = (
            "France Cadet",
            "Laurent Cos--tes",
            "Daniel Rodri­guez",
        )

        label_art = Label(self.credits, text="\n\n".join(art))
        label_art.pack(side=TOP, expand=True, fill=BOTH)
        notebook.add(label_art, text="Art by")

        notebook.pack(side=TOP, fill=BOTH, expand=True)

        self.panel_buttons = Frame(self.credits)
        self.panel_buttons.pack(side=BOTTOM, fill=BOTH, expand=True)

        Button(self.panel_buttons, text="Close",
               command=self.quit).pack(side=RIGHT, fill=X, expand=True)
        Button(self.panel_buttons, text="License",
               command=self.build_license).pack(side=LEFT, fill=X, expand=True)
示例#36
0
    def __init__(self, parent):
        Frame.__init__(self, parent)

        # variables
        self.input_fn = None
        self.input_img = None

        # top level UI
        self.parent = parent
        self.parent.title("Trader Joe")
        self.pack(fill=BOTH, expand=1)
        style = Style()
        style.configure("TFrame", background="#333")

        # Menu bar
        menubar = Menu(self.parent)
        self.parent.config(menu=menubar)
        fileMenu = Menu(menubar)
        fileMenu.add_command(label="Open", command=self.open_file_handler)
        menubar.add_cascade(label="File", menu=fileMenu)

        #
        # Init the Price Chart
        # init_matplotlib()
        self.fig = Figure(figsize=(16, 6))
        self.ax = self.fig.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.parent)
        self.canvas.get_tk_widget().place(x=0, y=0)

        # TODO: how to setup min price unit
        self.fig.tight_layout(
            pad=2, h_pad=1,
            w_pad=2)  # This should be called after all axes have been added
        self.ax.grid(True)
        self.ax.set_autoscalex_on(False)  # turn off auto scale
        self.ax.set_autoscaley_on(False)  # turn off auto scale
        self.ax.spines['top'].set_visible(False)
        self.ax.spines['right'].set_visible(False)
        self.ax.xaxis.set_tick_params(top='off', direction='out', width=1)
        self.ax.yaxis.set_tick_params(right='off', direction='out', width=1)
        self.ax.set_ylim([10000, 10400])

        # Define time series (X)
        date_str = datetime.now().strftime('%Y%m%d')
        ts = pd.date_range(start=date_str + ' 0900',
                           end=date_str + ' 1500',
                           freq='T')
        self.price_chart_df = pd.DataFrame(
            np.nan,
            index=ts,
            columns=['Open', 'High', 'Low', 'Close', 'Volume'])
        # config X limits according to TS
        self.ax.set_xlim([ts.values[0], ts.values[-1]])
        self.ani = animation.FuncAnimation(self.fig,
                                           self.update_price_chart,
                                           frames=np.arange(100000),
                                           init_func=self.init_price_chart,
                                           interval=1 * 1000,
                                           repeat=True)

        # Buttons
        btn_con = Button(self,
                         text='连接主机',
                         command=self.button_connect_handler,
                         width=16)
        btn_con.place(x=1, y=550)
        # Button - buy
        btn_discon = Button(self,
                            text="断开连接",
                            command=self.button_disconnect_handler,
                            width=16)
        btn_discon.place(x=20 * 8, y=550)
        # Button - buy
        btn_buy = Button(self,
                         text="买",
                         command=self.button_buy_handler,
                         width=16)
        btn_buy.place(x=20 * 16, y=550)
        # Button - sell
        btn_sell = Button(self,
                          text="卖",
                          command=self.button_sell_handler,
                          width=16)
        btn_sell.place(x=20 * 24, y=550)
        # Button - sell
        btn_close = Button(self,
                           text="平仓",
                           command=self.button_close_handler,
                           width=16)
        btn_close.place(x=20 * 32, y=550)

        # bind key
        self.bind_all("<Control-b>", self.key_buy_handler)
        self.bind_all("<Control-s>", self.key_sell_handler)
        self.bind_all("<Control-p>", self.button_close_handler)

        #
        self.parent.protocol("WM_DELETE_WINDOW", self.exit_handler)

        # Add txt box for system message output/displace
        Label(self, text='System Message', font='courier').place(x=1000, y=550)
        self.output_txtbox = ScrolledText(self.parent,
                                          width=30,
                                          height=10,
                                          font='courier')
        self.output_txtbox.place(x=1000, y=570)
        self.output_txtbox.insert('1.0', 'sample txt ouptput, %d\n' % (10))
示例#37
0
	def build(self):
		self.root = Tk()
		self.root.geometry("800x622+200+200")
		self.root.title("SecureMe")
		self.root.resizable(width=FALSE, height=FALSE)

		menubar = Menu(self.root)
		optionsmenu = Menu(menubar, tearoff=0)
		optionsmenu.add_command(label="Refresh (Ctrl+r)", command=lambda : self.refresh("NONE"))
		optionsmenu.add_command(label="Exit", command=lambda : self.quitMenu())
		menubar.add_cascade(label="Options", menu=optionsmenu)
		self.root.config(menu=menubar)

		self.toolbar = ToolBar(self.root, self)

		style = Style()
		style.configure("BW.TLabel", foreground="black", background="slate gray", borderwidth=2)

		mFrame = Frame(self.root, bg="slate gray", padx=25, pady=25)
		mFrame.pack(fill=BOTH)
		self.notebook = ttk.Notebook(mFrame, height=500, style="BW.TLabel")
		primaryFrame = Frame(self.notebook, padx=25, pady=25)
		usersFrame = Frame(self.notebook, padx=25, pady=25)
		firewallFrame = Frame(self.notebook, padx=25, pady=25)
		servicesFrame = Frame(self.notebook, padx=25, pady=25)
		processesFrame = Frame(self.notebook, padx=25, pady=25)
		self.notebook.add(primaryFrame, text='Primary')
		self.notebook.add(usersFrame, text='Users')
		self.notebook.add(firewallFrame, text='Firewall')
		self.notebook.add(servicesFrame, text='Services')
		self.notebook.add(processesFrame, text='Processes')
		self.notebook.pack(fill=X)

		self.updatebar = Frame(self.root)
		self.updatebar.pack(side=BOTTOM, fill=X)
		self.left_label = Label(self.updatebar, text="Status: None")
		self.left_label.pack(side=LEFT, fill=X)

		# Primary Panel
		primary_label = Label(primaryFrame, text='Primary Settings', font=self.liberation_font_15)
		primary_label.grid(row=0, column=0, columnspan=2, sticky=N+S+E+W)

		actionspanel = LabelFrame(primaryFrame, text='System Actions', padx=10, pady=10)
		actionspanel.grid(row=1, column=0, sticky=E+N, padx=25, pady=25)

		openterminal = Button(actionspanel, text='Open Terminal', command=lambda : self.openTerminal())
		openterminal.pack(padx=5, pady=5)

		opencontrol = Button(actionspanel, text='Open Control Panel', command=lambda : self.openControlPanel())
		opencontrol.pack(padx=5, pady=5)

		shutdown = Button(actionspanel, text='Shutdown', command=lambda : self.shutdown())
		shutdown.pack(padx=5, pady=5)

		rebootButton = Button(actionspanel, text='Reboot', command=lambda : self.reboot())
		rebootButton.pack(padx=5, pady=5)

		updatespanel = LabelFrame(primaryFrame, text='System Updates', padx=10, pady=10)
		updatespanel.grid(row=1, column=1, sticky=W+N, padx=25, pady=25)

		update_button = Button(updatespanel, text='Basic Update', command=lambda : self.basicUpdate())
		update_button.pack(padx=5, pady=5)

		upgrade_button = Button(updatespanel, text='Basic Upgrade', command=lambda : self.basicUpgrade())
		upgrade_button.pack(padx=5, pady=5)

		packageupdate_button = Button(updatespanel, text='Package Update', command=lambda : self.packageUpdate())
		packageupdate_button.pack(padx=5, pady=5)

		# Users Panel
		users_label = Label(usersFrame, text='User Security Settings', font=self.liberation_font_15)
		users_label.pack()

		editusers = Frame(usersFrame)
		editusers.pack()

		addusr = Button(editusers, text='Add User...', command=lambda : self.addUser())
		addusr.grid(row=0, column=0, padx=5, pady=5)

		delusr = Button(editusers, text='Del User...', command=lambda : self.delUser())
		delusr.grid(row=0, column=1, padx=5, pady=5)

		userpanel = LabelFrame(usersFrame, text="Users", padx=10, pady=10)
		userpanel.pack(side=TOP, fill=BOTH)

		self.uText = self.getUserText()
		self.users_listlabel = Label(userpanel, text=self.uText, padx=10, pady=10)
		self.users_listlabel.pack(side=LEFT)

		groupspanel = LabelFrame(usersFrame, text="Groups", padx=10, pady=10)
		groupspanel.pack(side=TOP, fill=BOTH)

		self.gText = self.getGroupText()
		self.groups_text = CustomText(groupspanel)
		self.groups_text.resetText(self.gText)
		self.groups_text.type(DISABLED)
		self.groups_text.pack(fill=BOTH)

		# Firewall Label
		firewall_label = Label(firewallFrame, text='Firewall Settings', font=self.liberation_font_15)
		firewall_label.pack()

		edFrame = Frame(firewallFrame)
		fwEnable = Button(edFrame, text='Enable', command=lambda : self.enableFirewall())
		fwEnable.pack(side=LEFT, padx=10, pady=10, fill=X)
		fwDisable = Button(edFrame, text='Disable', command=lambda : self.disableFirewall())
		fwDisable.pack(side=RIGHT, padx=10, pady=10, fill=X)
		edFrame.pack()

		firewallpanel = LabelFrame(firewallFrame, text='Firewall Status', height=100, width=450, padx=10, pady=10)
		firewallpanel.pack(side=TOP, fill=X)

		self.fText = self.getFirewallStatus()
		self.firewall_text = CustomText(firewallpanel)
		self.firewall_text.resetText(self.fText)
		self.firewall_text.type(DISABLED)
		self.firewall_text.pack(fill=X)

		# Services Pane
		services_label = Label(servicesFrame, text='System Services', font=self.liberation_font_15)
		services_label.pack()

		servicespanel = LabelFrame(servicesFrame, text="Services", padx=10, pady=10)
		servicespanel.pack(side=TOP, fill=BOTH)
		self.sText = self.getServicesText()
		self.services_text = CustomText(servicespanel)
		self.services_text.resetText(self.sText)
		self.services_text.type(DISABLED)
		self.services_text.pack(fill=BOTH)

		# Processes Pane
		processes_label = Label(processesFrame, text='System Processes', font=self.liberation_font_15)
		processes_label.pack()

		processespanel = LabelFrame(processesFrame, text='Processes', padx=10, pady=10)
		processespanel.pack(side=TOP, fill=BOTH)
		self.pText = self.getProcessesText()
		self.processes_text = CustomText(processespanel)
		self.processes_text.resetText(self.pText)
		self.processes_text.type(DISABLED)
		self.processes_text.pack(fill=BOTH)

		self.root.bind('<Control-r>', self.refresh)

		self.root.mainloop()
示例#38
0
    def build_credits(self):

        if getattr(self, "home", False): self.home.pack_forget()
        if getattr(self, "license", False): self.license.pack_forget()

        self.credits = Frame(self.parent)
        self.credits.pack(expand=True, fill=BOTH)

        Label(self.credits, text="Credits", **self.style_text).pack(side=TOP, expand=True, fill=X)

        style = Style()
        style.configure("BW.TNotebook", background=self.parent.cget("bg"), borderwidth=1, relief=SUNKEN, highlightthickness=1)


        notebook = Notebook(self.credits, style="BW.TNotebook")

        write = ("Jean-Pierre Mandon",
                 "Régis Blanchot",
                 "Marcus Fazzi",
                 "Jesus Carmona Esteban",
                 "Alfred Broda",
                 "Yeison Cardona",
                 "Henk Van Beek",
                 "Björn Pfeiffer",
                 "Alexis Sánchez",
                 )

        label_write = Label(self.credits, text="\n\n".join(write))
        label_write.pack(side=TOP, expand=True, fill=BOTH)
        notebook.add(label_write, text="Write by")

        doc = ("Benoit Espinola",
               "Sebastien Koechlin",
               "Ivan Ricondo",
               "Jesus Carmona Esteban",
               "Marcus Fazzi",
               "Régis Blanchot",
               )

        label_doc = Label(self.credits, text="\n\n".join(doc))
        label_doc.pack(side=TOP, expand=True, fill=BOTH)
        notebook.add(label_doc, text="Documented by")

        trans = ("Joan Espinoza",
                 "Alexis Sánchez",
                 "Régis Blanchot",
                 "Moreno Manzini",
                 "Yeison Cardona",
                 "\"Avrin\"",
                )

        label_trans = Label(self.credits, text="\n\n".join(trans))
        label_trans.pack(side=TOP, expand=True, fill=BOTH)
        notebook.add(label_trans, text="Translated by")

        art = ("France Cadet",
               "Laurent Cos--tes",
               "Daniel Rodri­guez",
               )

        label_art = Label(self.credits, text="\n\n".join(art))
        label_art.pack(side=TOP, expand=True, fill=BOTH)
        notebook.add(label_art, text="Art by")

        notebook.pack(side=TOP, fill=BOTH, expand=True)

        self.panel_buttons = Frame(self.credits)
        self.panel_buttons.pack(side=BOTTOM, fill=BOTH, expand=True)

        Button(self.panel_buttons, text="Close", command=self.quit).pack(side=RIGHT, fill=X, expand=True)
        Button(self.panel_buttons, text="License", command=self.build_license).pack(side=LEFT, fill=X, expand=True)
示例#39
0
文件: gui.py 项目: sychov/conditer
    def styles():
        """Просто определяем все стили ttk в одной функции"""

        style = Style(root)
        style.configure('Chosen.TButton', foreground='#9900BB',
                      background='#9900BB', font=('verdana', FONT_SIZE, 'bold'))

        style.configure('Default.TButton', font=('verdana', FONT_SIZE))
        if USE_BACKGROUND:
            style.configure('Default.TButton', background='#aaaaaa')

        style.configure('Eat.TButton', font=('lucida console', FONT_SIZE_BIG))
        if USE_BACKGROUND:
            style.configure('Eat.TButton', background='#aaaaaa')

        style.configure('Eat2.TButton', font=('lucida console', FONT_SIZE_BIG),
                         foreground='#9300B3')
        if USE_BACKGROUND:
            style.configure('Eat2.TButton', background='#aaaaaa')

        style.configure('Little.TButton', font=('verdana', FONT_SIZE),
                        justify='center')
        style.configure('TMenubutton', font=('lucida console', FONT_SIZE_BIG),
                        justify='left')
        if TABS_HIDE:
            style.layout('Hidden.TNotebook.Tab', '')
        else:
            style.configure('Hidden.TNotebook.Tab',font=('verdana', FONT_SIZE))
        style.configure('Custom.TNotebook.Tab', font=('verdana', FONT_SIZE))
        style.configure('TButton', font=('verdana', FONT_SIZE),justify='center')
示例#40
0
def panel():
    def press_number(but):

        if panel.new:
            if but <> "0":
                itogo_variable.set(but)
                panel.new = FALSE
            else:
                itogo_variable.set("0")

        else:
            if len(itogo_variable.get()) < 11:
                itogo_variable.set(itogo_variable.get() + but)

    def press_operation(but):

        if but == "C":
            panel.new = True
            itogo_variable.set("0")

        elif but == "<":
            if not panel.new:
                st = itogo_variable.get()
                itogo_variable.set(st[:-1])
                if itogo_variable.get() == "0":
                    panel.new = True
                if itogo_variable.get() == "":
                    panel.new = True
                    itogo_variable.set("0")

        elif but == "+":
            value = int(itogo_variable.get())
            itogo_variable.set(str(value + 1))

        elif but == "-":
            value = int(itogo_variable.get())
            if value > 0:
                itogo_variable.set(str(value - 1))
                if value == 1:
                    panel.new = True

    def the_end():
        window_panel.destroy()

    # =============================================================

    panel.new = True

    window_panel = Toplevel()
    window_panel.resizable(False, False)
    window_panel.title(u"Ввод количества")
    window_panel.geometry("+%d+%d" % (panel.x, panel.y))

    style = Style(window_panel)
    style.configure("Number.TButton", font=("Lucida Console", CALC_SCALE, "bold"), foreground="blue", justify="center")
    style.configure(
        "Operation.TButton", font=("Lucida Console", CALC_SCALE, "bold"), foreground="red", justify="center"
    )
    style.configure(
        "Control.TButton", font=("Lucida Console", CALC_SCALE, "bold"), foreground="#00aa00", justify="center"
    )

    itogo_variable = StringVar()
    itogo_variable.set("1")

    Label(
        window_panel,
        font=("Lucida Console", FONT_SIZE_BIG, "italic"),
        text="Введите количество:",
        width=13,
        justify=RIGHT,
        anchor=E,
    ).grid(column=0, row=0, columnspan=4, padx=CALC_PAD, pady=CALC_PAD * 2, sticky="NWES")

    label1 = Label(
        window_panel,
        font=("Lucida Console", CALC_SCALE, "bold"),
        textvariable=itogo_variable,
        width=13,
        justify=RIGHT,
        bg="white",
        anchor=E,
    )
    label1.grid(column=0, row=1, columnspan=4, padx=CALC_PAD, pady=CALC_PAD * 2)

    for q in range(1, 10):
        Button(
            window_panel, text=str(q), style="Number.TButton", width=1, command=lambda q=q: press_number(str(q))
        ).grid(
            column=(q - 1) % 3,
            row=2 + (q - 1) // 3,
            padx=CALC_PAD,
            pady=CALC_PAD,
            ipadx=CALC_SCALE / 3 * 2,
            ipady=CALC_SCALE / 2,
            sticky="NWES",
        )

    Button(window_panel, text="0", style="Number.TButton", width=1, command=lambda: press_number("0")).grid(
        column=1, row=5, padx=CALC_PAD, pady=CALC_PAD, ipadx=CALC_SCALE / 3 * 2, ipady=CALC_SCALE / 2, sticky="NWES"
    )

    Button(window_panel, text="+", style="Control.TButton", width=1, command=lambda: press_operation("+")).grid(
        column=3, row=3, padx=CALC_PAD, pady=CALC_PAD, ipadx=CALC_SCALE / 3 * 2, ipady=CALC_SCALE / 2, sticky="NWES"
    )

    Button(window_panel, text="-", style="Control.TButton", width=1, command=lambda: press_operation("-")).grid(
        column=3, row=4, padx=CALC_PAD, pady=CALC_PAD, ipadx=CALC_SCALE / 3 * 2, ipady=CALC_SCALE / 2, sticky="NWES"
    )

    Button(window_panel, text="C", style="Operation.TButton", width=1, command=lambda: press_operation("C")).grid(
        column=3, row=2, padx=CALC_PAD, pady=CALC_PAD, ipadx=CALC_SCALE / 3 * 2, ipady=CALC_SCALE / 2, sticky="NWES"
    )

    Button(window_panel, text="<", style="Operation.TButton", width=1, command=lambda: press_operation("<")).grid(
        column=0, row=5, padx=CALC_PAD, pady=CALC_PAD, ipadx=CALC_SCALE / 3 * 2, ipady=CALC_SCALE / 2, sticky="NWES"
    )

    Button(window_panel, text="Ввод", style="Control.TButton", width=1, command=the_end).grid(
        column=2,
        row=5,
        padx=CALC_PAD,
        pady=CALC_PAD,
        ipadx=CALC_SCALE / 3 * 2,
        ipady=CALC_SCALE / 2,
        columnspan=2,
        sticky="NWES",
    )

    window_panel.update()
    parent_name = window_panel.winfo_parent()
    parent = window_panel._nametowidget(parent_name)
    parentX, parentY = parent.winfo_width(), parent.winfo_height()
    childX, childY = window_panel.winfo_width(), window_panel.winfo_height()
    panel.x = (parentX - childX) / 2
    panel.y = (parentY - childY) / 2

    window_panel.geometry("+%d+%d" % (panel.x, panel.y))
    window_panel.grab_set()
    window_panel.focus_set()
    window_panel.wait_window()

    return int(itogo_variable.get())
示例#41
0
    def initUI(self):

        self.style = Style().configure("TFrame",
                                       background=self.sys.win_cfg.cBackground)
        self.pack(fill=BOTH, expand=1)

        titleLabel = Label(self,
                           text=self.sys.win_cfg.sStage,
                           background=self.sys.win_cfg.cBackground,
                           width=12,
                           height=1)
        titleLabel.place(x=5, y=5)

        # setup labels
        self.StageConfigured = Label(self,
                                     width=15,
                                     background=self.sys.win_cfg.cUnknown,
                                     text="Not Configured")
        self.StageConfigured.place(x=100, y=5)

        yoffset = 20
        #right column
        self.xActualLabel = Label(
            self,
            text="",
            background=self.sys.win_cfg.cTextBackgroundLocked,
            width=10,
            height=1)
        self.xActualLabel.place(x=200, y=30 + yoffset)

        self.yActualLabel = Label(
            self,
            text="",
            background=self.sys.win_cfg.cTextBackgroundLocked,
            width=10,
            height=1)
        self.yActualLabel.place(x=200, y=60 + yoffset)

        self.zActualLabel = Label(
            self,
            text="",
            background=self.sys.win_cfg.cTextBackgroundLocked,
            width=10,
            height=1)
        self.zActualLabel.place(x=200, y=90 + yoffset)

        self.xMovingLabel = Label(self,
                                  width=3,
                                  background=self.sys.win_cfg.cStageMoving,
                                  text="X")
        self.xMovingLabel.place(x=270, y=30 + yoffset)

        self.yMovingLabel = Label(self,
                                  width=3,
                                  background=self.sys.win_cfg.cStageMoving,
                                  text="Y")
        self.yMovingLabel.place(x=270, y=60 + yoffset)

        self.zMovingLabel = Label(self,
                                  width=3,
                                  background=self.sys.win_cfg.cStageMoving,
                                  text="Z")
        self.zMovingLabel.place(x=270, y=90 + yoffset)
        '''
        self.chkAutoUpdate = IntVar()
        self.chkAutoUpdate.set(1)
        self.autoUpdateCheckbutton = Checkbutton(self, text="Auto Update",
                                                 backgroun=self.sys.win_cfg.cBackground,
                                                 variable=self.chkAutoUpdate)
        self.autoUpdateCheckbutton.place(x=200, y=120+yoffset)
        '''

        self.testButton = Button(self,
                                 text="test",
                                 command=self.testNight,
                                 width=10)
        self.testButton.place(x=200, y=130 + yoffset)

        locationButton = Button(self,
                                text="Location",
                                command=self.update_actual_location,
                                width=10)
        locationButton.place(x=200, y=160 + yoffset)

        lockButton = Button(self, text="Lock", command=self.lock, width=10)
        lockButton.place(x=200, y=190 + yoffset)
        unlockButton = Button(self,
                              text="Unlock",
                              command=self.unlock,
                              width=10)
        unlockButton.place(x=200, y=220 + yoffset)

        style = Style()
        style.configure("Red.TButton",
                        foreground=self.sys.win_cfg.cBad,
                        background=self.sys.win_cfg.cBad)

        abortButton = Button(self,
                             text="\nAbort!\n",
                             command=self.abort_stage,
                             width=10)
        abortButton.configure(style="Red.TButton")
        abortButton.place(x=200, y=280 + yoffset)

        # setup buttons
        xLabel = Label(self,
                       text="X (mm): ",
                       background=self.sys.win_cfg.cBackground,
                       width=6,
                       height=1)
        xLabel.place(x=10, y=30 + yoffset)
        self.xEntry = Entry(self,
                            width=12,
                            background=self.sys.win_cfg.cTextBackground)
        self.xEntry.place(x=85, y=30 + yoffset)

        yLabel = Label(self,
                       text="Y (mm): ",
                       background=self.sys.win_cfg.cBackground,
                       width=6,
                       height=1)
        yLabel.place(x=10, y=60 + yoffset)
        self.yEntry = Entry(self,
                            width=12,
                            background=self.sys.win_cfg.cTextBackground)
        self.yEntry.place(x=85, y=60 + yoffset)
        zLabel = Label(self,
                       text="Z (mm): ",
                       background=self.sys.win_cfg.cBackground,
                       width=6,
                       height=1)
        zLabel.place(x=10, y=90 + yoffset)
        self.zEntry = Entry(self,
                            width=12,
                            background=self.sys.win_cfg.cTextBackground)
        self.zEntry.place(x=85, y=90 + yoffset)

        # buttons
        moveStagesButton = Button(self,
                                  text="Move Stages",
                                  command=self.move_stages,
                                  width=17)
        moveStagesButton.place(x=30, y=120 + yoffset)

        homeStagesButton = Button(self,
                                  text="Home Stages ",
                                  command=self.home_stages,
                                  width=17)
        homeStagesButton.place(x=30, y=260 + yoffset)

        homeStageButton = Button(self,
                                 text="Scan Array ",
                                 command=self.scan_array,
                                 width=10)
        homeStageButton.place(x=30, y=295 + yoffset)
        self.frameCount = Entry(self,
                                width=5,
                                background=self.sys.win_cfg.cTextBackground)
        self.frameCount.place(x=110, y=298 + yoffset)

        # buttons
        JogXPlusButton = Button(self,
                                text="X +",
                                command=self.jog_x_up,
                                width=5)
        JogXPlusButton.place(x=10, y=160 + yoffset)

        self.JogX = Entry(self,
                          width=8,
                          background=self.sys.win_cfg.cTextBackground)
        self.JogX.place(x=65, y=163 + yoffset)

        JogXMinuxButton = Button(self,
                                 text="X -",
                                 command=self.jog_x_down,
                                 width=5)
        JogXMinuxButton.place(x=130, y=160 + yoffset)

        JogYPlusButton = Button(self,
                                text="Y +",
                                command=self.jog_y_up,
                                width=5)
        JogYPlusButton.place(x=10, y=190 + yoffset)

        self.JogY = Entry(self,
                          width=8,
                          background=self.sys.win_cfg.cTextBackground)
        self.JogY.place(x=65, y=193 + yoffset)

        JogYMinuxButton = Button(self,
                                 text="Y -",
                                 command=self.jog_y_down,
                                 width=5)
        JogYMinuxButton.place(x=130, y=190 + yoffset)

        JogZPlusButton = Button(self,
                                text="Z +",
                                command=self.jog_z_up,
                                width=5)
        JogZPlusButton.place(x=10, y=220 + yoffset)

        self.JogZ = Entry(self,
                          width=8,
                          background=self.sys.win_cfg.cTextBackground)
        self.JogZ.place(x=65, y=223 + yoffset)

        JogZMinuxButton = Button(self,
                                 text="Z -",
                                 command=self.jog_z_down,
                                 width=5)
        JogZMinuxButton.place(x=130, y=220 + yoffset)
        # close buttons
        closeButton = Button(self,
                             text="Close",
                             command=self.close_window,
                             width=17)
        closeButton.place(x=30, y=350)

        # on absolute entries only, enter key moves to positions
        self.xEntry.bind("<KeyRelease-Return>", self.move_stages_return)
        self.yEntry.bind("<KeyRelease-Return>", self.move_stages_return)
        self.zEntry.bind("<KeyRelease-Return>", self.move_stages_return)
        # on absolute entries only, enter key moves to positions
        self.JogX.bind("<KeyRelease-Return>", self.jog_x_return)
        self.JogY.bind("<KeyRelease-Return>", self.jog_y_return)
        self.JogZ.bind("<KeyRelease-Return>", self.jog_z_return)

        self.JogX.bind("<KeyRelease-Shift_L>", self.jog_x_inverse)
        self.JogX.bind("<KeyRelease-Shift_R>", self.jog_x_inverse)
        self.JogY.bind("<KeyRelease-Shift_L>", self.jog_y_inverse)
        self.JogY.bind("<KeyRelease-Shift_R>", self.jog_y_inverse)
        self.JogZ.bind("<KeyRelease-Shift_L>", self.jog_z_inverse)
        self.JogZ.bind("<KeyRelease-Shift_R>", self.jog_z_inverse)
示例#42
0
    u"\u03C0", 'e', 'Proton/Neutron Mass (kg)', 'Electron Mass (kg)',
    'Avagadro\'s Number (1/mol)', 'Electron Charge (C)', 'Protron Charge (C)',
    'G (N*m^2/kg^2)', 'g (m/s^2)', u"\u03B5" + u"\u2080", "k",
    u"\u03BC" + u"\u2080", "Mass of the earth (kg)", "Mass of the Sun (kg)"
]

#Values of the constants
constant_values = [
    '3.14159', '2.71828', '1.67*10^-27', '9.11*10^-31', '6.02*10^23',
    '-1.6*10^-19', '1.6*10^-19', '6.67*10^-11', '9.81', '8.85*10^-12',
    '8.99*10^9', '4' + u"\u03C0" + "*10^-7", "5.972*10^24", "1.989*10^30"
]

#Style for the seperator lines in the sections
s = Style()
s.configure('TSeparator', background='black')


#Method for finding the direction of the force on a particle given a field and velocity
def rhr_force():

    #Setting the frame to make cleanup easier
    frame = Frame(root)
    frame.grid(row=0, column=0, sticky='w')

    Separator(frame, style='TSeparator', orient='vertical').grid(row=0,
                                                                 column=1,
                                                                 rowspan=7,
                                                                 sticky='ns')

    #Setting the variables
示例#43
0
    def __init__(self, master):

        plat = platform.system()
        if plat == 'Darwin':

            try:
                system(
                    '''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' '''
                )
                print("Trying to force Python window to the front on macOS")
            except:
                system(
                    '''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python2.7" to true' '''
                )
                print(
                    "Trying to force Python 2.7 window to the front on macOS")

        self.master = master
        frame = Frame(master)
        frame.config(background="#dcdcdc")
        frame.config(borderwidth=5, relief=GROOVE)
        frame.place(relx=0.5, rely=0.5, anchor=CENTER)
        master.title('Verify v. 0.2')  #   Main frame title
        master.config(background="#dcdcdc")
        master.geometry('820x750')
        menubar = Menu(master)
        """statmenu = Menu(menubar,tearoff=0)
        statmenu.add_command(label="Fieller", command=self.on_fieller)
        
        statmenu.rantest = Menu(statmenu)
        statmenu.rantest.add_command(label="Continuously variable data", command=self.on_rantest_continuous)
        statmenu.rantest.add_command(label="Binomial data (each result= yes or no)", command=self.on_rantest_binomial)
        statmenu.add_cascade(label="Randomisation test", menu=statmenu.rantest)
        
        statmenu.add_command(label="Help", command=self.on_help, state=DISABLED)
        statmenu.add_command(label="Quit", command=master.quit)
        
        menubar.add_cascade(label="Statistical Tests", menu=statmenu)
        master.config(menu=menubar)
      """
        b3 = Button(frame,
                    text="Load traces",
                    width=20,
                    command=self.callback3,
                    highlightbackground="#dcdcdc")
        b3.grid(row=0, column=0, columnspan=2, padx=10, pady=8, sticky=W)

        self.b4 = Button(frame,
                         text="Verify traces variance",
                         width=20,
                         state=DISABLED,
                         command=self.callback2,
                         highlightbackground="#dcdcdc")
        self.b4.grid(row=1, padx=10, pady=8, column=0, columnspan=2)

        self.b5 = Button(frame,
                         text="Plot Variance vs. current",
                         width=20,
                         state=DISABLED,
                         command=self.callback5,
                         highlightbackground="#dcdcdc")
        self.b5.grid(row=2, padx=10, pady=8, column=0, columnspan=2)

        #need to remove Pack to use separator
        s1 = Separator(frame, orient=VERTICAL)
        s1.grid(column=2, row=0, rowspan=40, pady=10, sticky=N + W + S)

        self.input_filename_label = StringVar()
        self.input_filename_label.set("No data loaded yet")
        self.l1 = Label(frame,
                        textvariable=self.input_filename_label,
                        width=40,
                        bg="#dcdcdc")
        self.l1.grid(row=0, column=2, columnspan=4, pady=5)

        Label(frame, text="Baseline range (pts)",
              bg="#dcdcdc").grid(row=1,
                                 column=2,
                                 columnspan=2,
                                 pady=5,
                                 sticky=E)
        self.br = Entry(frame,
                        justify=CENTER,
                        width=5,
                        highlightbackground="#dcdcdc")
        self.br.grid(row=1, column=4, sticky=W, pady=5)
        self.br.insert(END, '0, 50')

        Label(frame, text="Decimation", bg="#dcdcdc").grid(row=2,
                                                           column=2,
                                                           columnspan=2,
                                                           pady=5,
                                                           sticky=E)
        self.de = Entry(frame,
                        justify=CENTER,
                        width=5,
                        highlightbackground="#dcdcdc")
        self.de.grid(row=2, column=4, sticky=W, pady=5)
        self.de.insert(END, '1')

        Label(frame, text="Unitary current amplitude (pA)",
              bg="#dcdcdc").grid(row=3,
                                 column=2,
                                 columnspan=2,
                                 pady=5,
                                 sticky=E)
        self.ua = Entry(frame,
                        justify=CENTER,
                        width=5,
                        highlightbackground="#dcdcdc")
        self.ua.grid(row=3, column=4, sticky=W, pady=5)
        self.ua.insert(END, '1')
        #default unitary current is 1 pA

        Label(frame, text="Output filename", bg="#dcdcdc").grid(row=4,
                                                                column=2,
                                                                columnspan=2,
                                                                pady=5)

        style = Style()
        style.theme_use('clam')
        style.configure("w.TRadiobutton",
                        padding=2,
                        background="#dcdcdc",
                        foreground="black",
                        width=15)
        style.configure("TRadiobutton",
                        padding=2,
                        background="#dcdcdc",
                        foreground="black",
                        width=8)

        MODES = [("verified.txt", 3), ("Save as...", 2), ("v_[infile]", 1),
                 ("[date:time]_v_[infile]", 0)]

        self.v = IntVar()
        self.v.set(0)  # initialize

        #note this is the ttk radiobutton, the tk one doesn't select at first
        for text, mode in MODES:
            b = Radiobutton(frame,
                            text=text,
                            command=self.callback_fname,
                            variable=self.v,
                            value=mode,
                            state=NORMAL)
            b.grid(row=5, padx=10, column=mode + 2, sticky=E)

        #the last button in the loop (0) is the wide one, so gets the wide style.
        b.configure(style='w.TRadiobutton')

        self.traceHost = Frame(frame)
        self.traceHost.grid(row=15, column=0, columnspan=3)
        self.p = Plot(self.traceHost)

        self.Host2D = Frame(frame)
        self.Host2D.grid(row=15, column=3, columnspan=3)
        self.pcv = Plot(self.Host2D)

        s2 = Separator(frame)
        s2.grid(row=25, columnspan=6, sticky=S + E + W)

        message = Message(frame,
                          text=self.introduction,
                          width=800,
                          font=("Courier", 12),
                          bg="#dcdcdc")
        message.grid(row=26, rowspan=8, columnspan=6, sticky=EW)

        s3 = Separator(frame)
        s3.grid(row=35, columnspan=6, sticky=E + W)

        version_text = "https://github.com/aplested/verify\nPython version:\t" + sys.version.replace(
            "\n", "\t")
        version = Message(frame,
                          width=800,
                          text=version_text,
                          justify=LEFT,
                          background="#dcdcdc",
                          font=("Courier", 12))
        version.grid(row=36, columnspan=5, sticky=EW)

        self.b6 = Button(frame,
                         text="Quit",
                         command=master.quit,
                         width=10,
                         highlightbackground="#dcdcdc")
        self.b6.grid(row=36, padx=10, pady=8, column=5, sticky=W)
示例#44
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()
        
    def initUI(self):
        self.parent.title("Network/Port Scan")
        self.style = Style()
        self.style.configure("TFrame", background = "#000000")
        self.style.configure("TCheckbutton", background = "#000000")
        self.style.configure("TButton", background = "#000000") 
        self.pack(fill=BOTH, expand=1)
        
        # Configure layout
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.rowconfigure(5, weight = 1)
        self.rowconfigure(6, weight = 1)
        
        # Title of program
        lbl = Label(self, text="Network/Port Scan")
        lbl.grid(sticky = W, pady=5, padx=5)

        # Text Box
        area = ScrolledText(self, height = 20)
        area.grid(row=1, column=0, columnspan=3, rowspan=4, padx=3, sticky = N+S+E+W)
        self.area = area

        # IP Address Button
        self.ip = BooleanVar()
        ip_add_button = Checkbutton(self, text="IP Address",variable=self.ip, width=10)
        ip_add_button.grid(row = 1, column = 3, sticky = N)
        ip_add_button.config(anchor = W, activebackground = "red")

        # Port Button
        self.port = BooleanVar()
        port_button = Checkbutton(self, text="Ports", variable=self.port, width=10)
        port_button.grid(row = 1, column = 3)
        port_button.config(anchor = W, activebackground = "orange")
        
        # Host Name Button
        self.host = BooleanVar()
        host_name_button = Checkbutton(self, text="Host Name",variable=self.host, width=10)
        host_name_button.grid(row = 1, column = 3, sticky = S)
        host_name_button.config(anchor = W, activebackground = "yellow")
        
        # Gateway Button
        self.gateway = BooleanVar()
        gateway_btn = Checkbutton(self, text="Gateway", variable=self.gateway, width=10)
        gateway_btn.grid(row = 2, column = 3, sticky = N)
        gateway_btn.config(anchor = W, activebackground = "green")

        # Services Button
        self.service = BooleanVar()
        service_btn = Checkbutton(self, text="Services", variable = self.service, width=10)
        service_btn.grid(row = 2, column = 3)
        service_btn.config(anchor = W, activebackground = "blue")

        # Starting IP label
        ip_label = Label(self, text = "Starting IP:  ")
        ip_label.grid(row = 5, column = 0, pady = 1, padx = 3, sticky = W)
        self.ip_from = Entry(self, width = 15)
        self.ip_from.insert(0, start_ip)
        self.ip_from.grid(row = 5 , column = 0, pady = 1, padx = 3, sticky = E)

        # Ending IP label
        ip_label_two = Label(self, text = "Ending IP:  ")
        ip_label_two.grid(row = 5, column = 1, pady = 1, padx = 5, sticky = W)
        self.ip_to = Entry(self, width = 15)
        self.ip_to.insert(0, end_ip)
        self.ip_to.grid(row = 5 , column = 1, pady = 1, padx = 5, sticky = E)
        
        # Starting Port Label
        port_label = Label(self, text = "Starting Port:  ")
        port_label.grid(row = 5, column = 0, pady = 3, padx = 5, sticky = S+W)
        self.port_from = Entry(self, width = 15)
        self.port_from.insert(0, 0)
        self.port_from.grid(row = 5 , column = 0, pady = 1, padx = 5, sticky = S+E)

        # Ending Port Label
        port_label_two = Label(self, text = "Ending Port:  ")
        port_label_two.grid(row = 5, column = 1, pady = 3, padx = 5, sticky = S+W)
        self.port_to = Entry(self, width = 15)
        self.port_to.insert(0, 1025)
        self.port_to.grid(row = 5 , column = 1, pady = 1, padx = 5, sticky = S+E)

        # Scan Me 
        self_scan_button = Button(self, text="Scan Me", command = lambda : self.onClick(1), width = 33)
        self_scan_button.grid(row = 6, column = 1, sticky = N)

        # Scan near me Button
        scan_other_button = Button(self, text="Scan Near Me", width = 33, command = lambda : self.onClick(2))
        scan_other_button.grid(row = 6, column = 0, pady=1, sticky = N)
        
        # Clear button
        clear_button = Button(self, text="Clear text", command = self.clear_text, width = 12)
        clear_button.grid(row = 6, column = 3, pady=1, sticky = N)

        # Progress Bar
        self.label_scanning = Progressbar(self, orient = HORIZONTAL, length = 175)
        self.label_scanning.grid(row = 6, column = 0, columnspan = 4, padx = 7, pady = 7, sticky = E+S+W)
        self.label_scanning.config(mode = "determinate")

     
    # Clear what is in the text box.   
    def clear_text(self):
        self.area.delete(0.0, 'end')
        # empty my lists.
        my_ports[:] = []
        ip_address_up[:] = []
        target_host_name[:] = []
        target_port_up[:] = []
        
    # On click methods for scan me and scan others.
    def onClick(self, button_id):
        
        if button_id == 1:
            
            # Check to see if host button is marked
            if self.host.get() == 1:
                message = my_host_name()
                self.area.insert(0.0, message, ("warning"))
                self.area.tag_configure("warning", foreground = "blue")    
                
            # Check to see if ports button is marked   
            if self.port.get() == 1:
                # Check port entry widgets. 
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()                
                        message, total = scan_my_ports(int(starting_port), int(ending_port))
                        for i in message:
                            new_message = "My TCP " + i + "\n"
                            self.area.insert(0.0, new_message, ("ports"))
                            #self.area.tag_configure("ports", foreground = "green")
                    
                    time = "The TCP port scan completed in: " + str(total) + "\n"
                    self.area.insert(0.0, time, ("timing"))
                    self.area.tag_configure("timing", foreground = "red")
                else:
                    self.area.insert(0.0, "No valid ports specified.")
                
            # Check to see if IP button is marked     
            if self.ip.get() == 1:
                message = my_ip()
                self.area.insert(0.0, message)
            
            # Check if gateway button is marked.
            if self.gateway.get() == 1:
                message = my_gateway()
                self.area.insert(0.0, message)

            # Check if service button is marked.
            if self.service.get() == 1:
                message, time = scan_my_services()
                for i in message:
                    new_message = i + "\n"
                    self.area.insert(0.0, new_message)
                new_time = "The local scan completed in: " + str(time) + "\n"
                self.area.insert(0.0. new_time, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
        # If Scan other button is clicked. 
        elif button_id == 2:
            
            # Check other IP's 
            if self.ip.get() == 1:
                # Check the entry widgets.
                if self.ip_from:
                    if self.ip_to:
                        # Get the ranges from the entry widgets
                        starting_ipv4_address = self.ip_from.get()
                        ending_ipv4_address = self.ip_to.get()
                        
                        # Pass the values from the entry widgets into the function to scan nearby IP addresses.
                        message, time = ping_ip_other(starting_ipv4_address, ending_ipv4_address)
                        if message:
                            for i in message:
                                new_message = "The address:     {:>15} {:>15}".format(i,"is UP\n")
                                self.area.insert(0.0, new_message)
                        
                        total_time =  "Range scanned: " + str(starting_ipv4_address) +" to " + str(ending_ipv4_address) + "\n" + "The IP scan completed in:  " + str(time) + "\n"
                        self.area.insert(0.0, total_time, ("timing"))
                        self.area.tag_configure("timing", foreground = "red")

                else:
                    self.area.insert(0.0, "No Ip range is specified.")
                
                
            # Check others Ports
            if self.port.get() == 1:
                # Check port entry widgets. 
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()
                        
                        
                        message, time = scan_ports_other(int(starting_port), int(ending_port))
                        if message:
                            for i in message:
                                new_msg = "The " + i +"\n"
                                self.area.insert(0.0, new_msg)
                        else:
                            new_msg = "Must scan nearby IP addresses first.\n"
                    
                    total_time = "TCP Port scan completed in: " + str(time) + "\n"
                    self.area.insert(0.0, total_time, ("timing"))
                    self.area.tag_configure("timing", foreground = "red")
                    
                else:
                    self.area.insert(0.0, "No Port range specified.")
            
            # Check other host names. Based on IP's scanned.
            if self.host.get() == 1:
                message, time = scan_host_other(ip_address_up)
                # Check that IP's of other computers were collected 
                if message:
                    for i in message:
                        new_message = "Host name: "+ str(i) + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "Must scan nearby IP addresses first. \n"
                    self.area.insert(0.0, new_msg)
                    
                total = "The host scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, total, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
            # Check gateway return the gateway of the host machine again.
            if self.gateway.get() == 1:
                message = "\n" + str(my_gateway())
                self.area.insert(0.0, message)

            # Check what services are running on which IP and port.
            if self.service.get() == 1:
                message, time = services_other()
                if message:
                    for i in message:
                        new_message = i + "\n"
                        self.area.insert(0.0, new_message)
                    
                else:
                    new_msg = "The IP addresses and ports must be scanned first."
                    self.area.insert(0.0, new_msg)
                    
                new_time = "The service scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, new_time, ("timing"))
                self.area.tag_configure("timing", foreground = "red")
                
        else:
            pass
示例#45
0
        # workaround for bug #1878298 at tktoolkit sf bug tracker
        self.event_generate('<Expose>')

    def last_page(self):
        """Return the last page in the notebook."""
        return self.pages[self.tab(self.index('end') - 1)['text']]

if __name__ == '__main__':
    from Tkinter import Tk
    from Tkconstants import TOP, BOTH
    from ttk import Label, Entry, Button, Style
    # test dialog
    root=Tk()
    style = Style()
    style.configure('C.TLabel', padding=20)
    tabPage=TabbedPageSet(root, page_names=['Foobar','Baz'])
    tabPage.pack(side=TOP, expand=True, fill=BOTH)
    Label(tabPage.pages['Foobar'].frame, text='Foo', style='C.TLabel').pack()
    Label(tabPage.pages['Foobar'].frame, text='Bar', style='C.TLabel').pack()
    Label(tabPage.pages['Baz'].frame, text='Baz').pack()
    entryPgName=Entry(root)
    buttonAdd=Button(root, text='Add Page',
            command=lambda:tabPage.add_page(entryPgName.get()))
    buttonRemove=Button(root, text='Remove Page',
            command=lambda:tabPage.remove_page(entryPgName.get()))
    labelPgName=Label(root, text='name of page to add/remove:')
    buttonAdd.pack(padx=5, pady=5)
    buttonRemove.pack(padx=5, pady=5)
    labelPgName.pack(padx=5)
    entryPgName.pack(padx=5)
示例#46
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        #         self.quote = "I was supposed to be a cool quote . But then internet abandoned me !"
        #         self.author = "Aditya"
        self.getQuote()
        self.initUI()

    def initUI(self):

        self.parent.title("Buttons")
        self.style = Style()
        self.style.theme_use("alt")

        # Styling
        self.style.configure('.', font=('Helvetica', 12), background="#300A24")
        self.style.configure("PW.TLabel",
                             foreground="#fff",
                             background="#300A24",
                             padding=20,
                             justify=CENTER,
                             wraplength="350")
        self.style.configure("Medium.TButton",
                             foreground="#300A24",
                             background="#fff",
                             borderwidth=0,
                             padding=8,
                             font=('Helvetica', 9))
        # Styling Ends

        quoteLabel = Label(self, text=self.quote, style="PW.TLabel")
        quoteLabel.pack()
        authorLabel = Label(self, text=self.author, style="PW.TLabel")
        authorLabel.pack()

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

        closeButton = Button(self,
                             text="Close This",
                             style="Medium.TButton",
                             command=self.parent.quit)
        closeButton.pack(side=RIGHT)
        okButton = Button(self,
                          text="Portfolio",
                          style="Medium.TButton",
                          command=self.btnOneFn)
        okButton.pack(side=RIGHT)
        okButton = Button(self,
                          text="JStack",
                          style="Medium.TButton",
                          command=self.btnTwoFn)
        okButton.pack(side=RIGHT)
        okButton = Button(self,
                          text="Python",
                          style="Medium.TButton",
                          command=self.btnThreeFn)
        okButton.pack(side=RIGHT)

    def hello(self):
        print("Print Hello")

    def getQuote(self):
        j = json.loads(
            requests.get(
                "http://quotes.stormconsultancy.co.uk/random.json").text)
        self.quote = j["quote"]
        self.author = j["author"]

    def btnOneFn(self):
        subprocess.Popen(['nautilus', "/mnt/864A162B4A16190F/git/portfolio"])
        subprocess.Popen(['gnome-terminal'],
                         cwd=r'/mnt/864A162B4A16190F/git/portfolio')

    def btnTwoFn(self):
        subprocess.Popen(['nautilus', "/mnt/864A162B4A16190F/git/JStack"])
        subprocess.Popen(['gnome-terminal'],
                         cwd=r'/mnt/864A162B4A16190F/git/JStack')

    def btnThreeFn(self):
        subprocess.Popen(['nautilus', "/mnt/864A162B4A16190F/git/Python"])
        subprocess.Popen(['gnome-terminal'],
                         cwd=r'/mnt/864A162B4A16190F/git/Python')
示例#47
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

    def initUI(self):

        self.parent.title("PORT SCANNER")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.style.configure("TFrame", background="#2E2E2E")

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(3, weight=1)
        self.rowconfigure(5, pad=7)

        def syn():
            import os
            addr = E1.get()
            os.system("./tcp-syn " + addr + " >test1.txt")
            with open("test1.txt") as f:
                content = f.readlines()
            for i in range(len(content)):
                area1.insert(INSERT, content[i])
                area1.insert(INSERT, "\n")

        def tcp():
            import os
            addr = E1.get()
            os.system("./tcp " + addr + " >test1.txt")
            with open("test1.txt") as f:
                content = f.readlines()
            for i in range(len(content)):
                area1.insert(INSERT, content[i])
                area1.insert(INSERT, "\n")

        def udp():
            import os
            str1 = E1.get()
            os.system("./udp " + str1 + " >test1.txt")
            with open("test1.txt") as f:
                content = f.readlines()
            for i in range(len(content)):
                area1.insert(INSERT, content[i])
                area1.insert(INSERT, "\n")

        def ping():
            import os
            str1 = E1.get()
            os.system("./ping " + str1 + " >test1.txt")
            with open("test1.txt") as f:
                content = f.readlines()
            for i in range(len(content)):
                area1.insert(INSERT, content[i])
                area1.insert(INSERT, "\n")

        def clear_text():
            area1.delete(1.0, END)

        label1 = Label(root, text="IP ADDRESS")
        root.configure(background="#8A0829")
        E1 = Entry(root, bd=10)
        label1.pack()
        E1.pack(pady=30, padx=1, ipadx=5)

        area1 = Text(self)
        area1.grid(row=1,
                   column=0,
                   columnspan=1,
                   rowspan=2,
                   padx=2,
                   pady=3,
                   sticky=W + N)
        area1.configure(background='#F5A9BC')

        syn_btn = Button(self, text="TCP/SYN SCAN", command=syn)
        syn_btn.grid(row=1, column=3, sticky=N)

        tcp_btn = Button(self, text="TCP SCAN", command=tcp)
        tcp_btn.grid(row=2, column=3, pady=5)

        udp = Button(self, text="UDP SCAN", command=udp)
        udp.grid(row=3, column=3, pady=5)

        ping = Button(self, text="PING", command=ping)
        ping.grid(row=4, column=3, pady=10)

        tr = Button(self, text="TRACEROUTE")
        tr.grid(row=5, column=3, pady=10)

        tr = Button(self, text="CLEAR SCREEN", command=clear_text)
        tr.grid(row=6, column=3, pady=10, sticky=S)
class menu(window):
    def __init__(self, parent):
        window.__init__(self,parent)
        self.initUI()
    def save(self,derechas,izquierdas,saltos,disparos):
        derechas = retornarkeyascii(derechas)
        izquierdas = retornarkeyascii(izquierdas)
        saltos = retornarkeyascii(saltos)
        disparos = retornarkeyascii(disparos)
        if(not(derechas == None or izquierdas==None or saltos == None or disparos==None)):
            try:
                Config.set('Movimientos', 'derecha', derechas)
                Config.set('Movimientos', 'izquierda', izquierdas)
                Config.set('Movimientos', 'salto', saltos)
                Config.set('Movimientos', 'disparo', disparos)
                with open('config.ini', 'w') as configfile:
                    Config.write(configfile)
            except:
                print "Error en la escritura"
        else:
            print "error"
    def initUI(self):

        Config.read("config.ini")
        Config.sections()
        derecha = ConfigSectionMap("Movimientos")['derecha']
        izquierda = ConfigSectionMap("Movimientos")['izquierda']
        disparo = ConfigSectionMap("Movimientos")['disparo']
        salto = ConfigSectionMap("Movimientos")['salto']

        derecha=int(derecha)
        izquierda=int(izquierda)
        disparo=int(disparo)
        salto=int(salto)

        self.parent.title("Place of dead - [Configuration]")
        self.style = Style()
        #self.style.theme_use("default")
        self.style.configure('My.TFrame', background='gray')
        #Layouts
        frame1 = Frame(self)
        frame1.pack(fill=Y)
        frame2 = Frame(self)
        frame2.pack(fill=Y)
        frame3 = Frame(self)
        frame3.pack(fill=Y)
        frame4 = Frame(self)
        frame4.pack(fill=Y)
        frame5 = Frame(self)
        frame5.pack(fill=Y)
        frame6 = Frame(self)
        frame6.pack(fill=Y)

        self.pack(fill=BOTH, expand=1)
        self.labela = Label(frame2, text="Movimiento a la derecha: ")#, textvariable=self.var)
        self.labela.pack(side=LEFT)
        derechae = Entry(frame2,width=9)
        derechae.insert(END, str(retornarletra(derecha)))
        derechae.pack(side=LEFT,padx=1, pady=1, expand=True)

        self.labelb = Label(frame3, text="Movimiento a la derecha: ")#, textvariable=self.var)
        self.labelb.pack(side=LEFT)
        izquierdae = Entry(frame3,width=9)
        izquierdae.insert(END, str(retornarletra(izquierda)))
        izquierdae.pack(side=LEFT,padx=1, pady=1, expand=True)

        self.labelc = Label(frame4, text="Salto: ")#, textvariable=self.var)
        self.labelc.pack(side=LEFT)
        saltoe = Entry(frame4,width=9)
        saltoe.insert(END, str(retornarletra(salto)))
        saltoe.pack(side=LEFT,padx=1, pady=1, expand=True)

        self.labeld = Label(frame5, text="Ataque: ")#, textvariable=self.var)
        self.labeld.pack(side=LEFT)
        disparoe = Entry(frame5,width=9)
        disparoe.insert(END, str(retornarletra(disparo)))
        disparoe.pack(side=LEFT,padx=1, pady=1, expand=True)

        okButton = Button(frame6, text="Save", command=lambda: self.save(derechae.get(),izquierdae.get(),saltoe.get(),disparoe.get()))
        okButton.pack(side=RIGHT)
示例#49
0
# Initial attempt at a display of random numbers over time on a pi
from Tkinter import *
from ttk import Progressbar
from ttk import Style
import random
import time

window = Tk()
text = StringVar()
text.set('loading...')
status = IntVar()
window.configure(background='black')
window.wm_attributes('-type', 'splash')
window.geometry('350x200')
def changeText():
    randomNum = random.randrange(1,15, 1)
    text.set(randomNum)
    progress['value'] = randomNum * .15 * 100
    window.after(100, changeText)

lbl = Label(window, compound=CENTER, textvariable=text, bg="black", fg="orange", font=("Arial Bold", 50))
lbl.place(x=175, y=100, anchor="center")
style = Style()
style.theme_use('default')
style.configure("orange.Horizontal.TProgressbar", troughcolor='black', foreground='orange', background='orange', troughrelief="flat" )
progress=Progressbar(window, orient=HORIZONTAL, style='orange.Horizontal.TProgressbar', length=200, mode='determinate')
progress.pack()
window.after(100, changeText)
window.mainloop()
示例#50
0
class ScaleWindow(Toplevel):
    def __init__(self, master):
        Toplevel.__init__(self, master)
        self.keyboard_view = KeyboardView(self)
        self.keyboard_view.grid(column=1, row=0, sticky='nesw')
        self.keyboard_view.focus_set()
        self.row = 1
        self.instruments = []
        self.scale_plots = []
        self.control_frames = []
        self.activate_buttons = []

        self.radio_btn_var = IntVar()

        self.control_frames_style = Style()
        self.control_frames_style.configure('Active.TFrame', background=CONTROL_FRAME_ACTIVE)
        self.control_frames_style.configure('Inactive.TFrame', background=CONTROL_FRAME_INACTIVE)

    def activate_instrument(self):
        indx = self.radio_btn_var.get()
        for cf in self.control_frames:
            cf.config(style='Inactive.TFrame')
        self.control_frames[indx].config(style='Active.TFrame')

        instrument = self.instruments[indx]
        self.keyboard_view.set_instrument(instrument)

    def add_instrument(self, instrument):
        if not isinstance(instrument, ScaleSynth):
            return

        index = len(self.instruments)
        self.instruments.append(instrument)

        scale_plot = ScalePlot(self)
        scale_plot.draw_scale(instrument.scale)
        scale_plot.grid(column=1, row=self.row, sticky='nesw')
        self.scale_plots.append(scale_plot)
        instrument.add_observer(scale_plot)

        control_frame = Frame(self)
        self.control_frames.append(control_frame)

        activate_button = Radiobutton(control_frame,
                                      # text=str(instrument.name),
                                      textvar=instrument.id_variable,
                                      variable=self.radio_btn_var,
                                      value=index,
                                      command=self.activate_instrument,
                                      width=15,
                                      )
        activate_button.pack()

        self.radio_btn_var.set(index)
        self.activate_instrument()

        control_frame.grid(column=0, row=self.row, sticky='nesw')

        self.row += 1

    def destroy(self):
        for sp in self.scale_plots:
            sp.destroy()
        return Toplevel.destroy(self)
示例#51
0
class ManagerUI(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        # make Esc exit the program
        self.parent.bind('<Escape>', lambda e: self._quit_timer())
        self._start = 0.0
        self._elapsedtime = 0.0
        self._running = 0
        self.style = None
        self.timestr = StringVar()
        self.init_ui()

    def timer_widget(self):
        """ Make the time lable. """
        l = Label(self,
                  textvariable=self.timestr,
                  background="White",
                  font=('Helvetica', 32),
                  anchor='center',
                  relief='sunken')
        self._set_time(self._elapsedtime)
        l.pack(fill=X, expand=NO, pady=50, padx=50)

    def control_button_widget(self):
        frame = Frame(self, style='button.TFrame', padding=10)
        frame.pack(side='top', fill=BOTH)

        buttons = Button(frame, text="Start", command=self._start_timer)
        buttons.pack(padx=5, side='left')
        buttons = Button(frame, text="Stop", command=self._stop_timer)
        buttons.pack(padx=5, side='left')
        buttons = Button(frame, text="Reset", command=self._reset_timer)
        buttons.pack(padx=5, side='left')
        buttons = Button(frame, text="Quit", command=self._quit_timer)
        buttons.pack(padx=5, side='left')

    def goal_button_widget(self):
        frame = Frame(self)
        frame.pack(padx=0, pady=0, side='top')

        buttons = Button(frame,
                         text="Home Goal",
                         command=lambda: self._goal_scored('home'),
                         style="goal.TButton")
        buttons.pack(padx=5, pady=20, side='top')
        buttons = Button(frame,
                         text="Away Goal",
                         command=lambda: self._goal_scored('away'),
                         style="goal.TButton")
        buttons.pack(padx=5, pady=20, side='top')

    def _update(self):
        """ Update the label with elapsed time. """
        self._elapsedtime = time.time() - self._start
        self._set_time(self._elapsedtime)
        self._timer = self.after(50, self._update)

    def _set_time(self, elap):
        """ Set the time string to Minutes:Seconds:Hundreths """
        minutes = int(elap / 60)
        seconds = int(elap - minutes * 60.0)
        hseconds = int((elap - minutes * 60.0 - seconds) * 100)
        self.timestr.set('%02d:%02d' % (minutes, seconds))
        return '%02d:%02d:%02d' % (minutes, seconds, hseconds)

    def _reset_timer(self):
        """ Reset the stopwatch. """
        _logger(('RESET', self._set_time(self._elapsedtime)))
        self._start = time.time()
        self._elapsedtime = 0.0
        self._set_time(self._elapsedtime)

    def _start_timer(self):
        """ Start the stopwatch, ignore if running. """
        if not self._running:
            _logger(('START', self._set_time(self._elapsedtime)))
            self._start = time.time() - self._elapsedtime
            self._update()
            self._running = 1

    def _stop_timer(self):
        """ Stop the stopwatch, ignore if stopped. """
        if self._running:
            _logger(('STOP', self._set_time(self._elapsedtime)))
            self.after_cancel(self._timer)
            self._elapsedtime = time.time() - self._start
            self._set_time(self._elapsedtime)
            self._running = 0

    def _goal_scored(self, which_side_scored):
        if self._running:
            _logger(('GOAL:%s' % which_side_scored,
                     self._set_time(self._elapsedtime)))
            tkMessageBox.showinfo("%s Goal!!!" % which_side_scored,
                                  self._set_time(self._elapsedtime))

    def _quit_timer(self):
        ans = tkMessageBox.askokcancel("", "Quit the app?", icon="warning")
        if ans:
            _logger(('QUIT:yes', self._set_time(self._elapsedtime)))
            self.parent.destroy()
        else:
            _logger(('QUIT:no', self._set_time(self._elapsedtime)))

    def init_ui(self):
        self.parent.title("Match Manager")
        self.style = Style()
        self.style.theme_use("clam")
        self.style.configure('TButton', width=10, padx=5, pady=5)
        self.style.configure('button.TFrame', background="Grey")
        self.style.configure('goal.TButton',
                             font=('Helvetica', 24),
                             width=10,
                             relief="raised")

        self.pack(fill=BOTH, expand=1)

        self.control_button_widget()

        self.timer_widget()

        self.goal_button_widget()
示例#52
0
sentSubPlt.set_yticks(np.arange(5))
sentSubPlt.set_yticklabels([sentData.index[0],' ',' ',' ',' '])
bottomLeft = FigureCanvasTkAgg(sentFig, master=leftPan)
bottomLeft.show()
bottomLeft.get_tk_widget().pack()
sentFig.tight_layout()

#Top Keywords
lab3=tk.Label(rightPan,text="Most Frequent Unmodeled Keywords",font='arial 10 bold')
rightPan.add(lab3)
lab3.pack()

keywords=Treeview(rightPan)
keywords["columns"]=["Frequency"]
style = Style(root)
style.configure('Treeview', rowheight=29,font='arial 10 bold')

keywords.heading("#0", text="Word")
keywords.heading("Frequency", text="Frequency")
keywords.column("#0", anchor=tk.CENTER)
keywords.column("Frequency", anchor=tk.CENTER)
keywordIndex={}
top10Words=topWords[-10:]

tree_i=0
for index,row in top10Words.iteritems():
    treeind=keywords.insert(parent="",index=0,text=str(index), values=(str(row)))
    keywordIndex[tree_i]=treeind
    tree_i+=1
    
rightPan.add(keywords)
示例#53
0
    def create_styles(self):
        """"""

        styles = Style()
        styles.configure("TNotebook", background="#afc8e1", borderwidth=0, relief=FLAT, highlightthickness=0)
示例#54
0
    def initUI(self):
        self.parent.title("calculator")
        style=Style()
        style.configure("TButton",padding=(0,5,0,5),font = 'serif 10')

        self.columnconfigure(0,pad=3)
        self.columnconfigure(1,pad=3)
        self.columnconfigure(2,pad=3)
        self.columnconfigure(3,pad=3)

        self.rowconfigure(0,pad=3)
        self.rowconfigure(1,pad=3)
        self.rowconfigure(2,pad=3)
        self.rowconfigure(3,pad=3)
        self.rowconfigure(4,pad=3)

        entry = Entry(self)
        entry.grid(row=0,columnspan=4,sticky=W+E)
        cls = Button(self, text = "Cls")
        cls.grid(row=1, column=0)
        bck = Button(self, text = "Back")
        bck.grid(row=1, column=1)
        lbl = Button(self,)
        lbl.grid(row=1, column=2)
        clo = Button(self, text = "CLOSE")
        clo.grid(row=1, column=3)
        sev = Button(self, text = "7")
        sev.grid(row=2, column=0)
        eig = Button(self, text = "8")
        eig.grid(row=2, column=1)
        nin = Button(self, text = "9")
        nin.grid(row=2, column=2)
        div = Button(self, text = "/")
        div.grid(row=2, column=3)

        fou = Button(self, text = "4")
        fou.grid(row=3, column=0)
        fiv = Button(self, text = "5")
        fiv.grid(row=3, column=1)
        six = Button(self, text = "6")
        six.grid(row=3, column=2)
        mul = Button(self, text = "*")
        mul.grid(row=3, column=3)

        one = Button(self, text = "1")
        one.grid(row=4, column=0)
        two = Button(self, text = "2")
        two.grid(row=4, column=1)
        thr = Button(self, text = "3")
        thr.grid(row=4, column=2)
        mns = Button(self, text = "-")
        mns.grid(row=4, column=3)

        zer = Button(self, text = "0")
        zer.grid(row=5, column=0)
        dot = Button(self, text = ".")
        dot.grid(row=5, column=1)
        equ = Button(self, text = "=")
        equ.grid(row=5, column=2)
        pls = Button(self, text = "+")
        pls.grid(row=5, column=3)

        self.pack()
示例#55
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("Network/Port Scan")
        self.style = Style()
        self.style.configure("TFrame", background="#000000")
        self.style.configure("TCheckbutton", background="#000000")
        self.style.configure("TButton", background="#000000")
        self.pack(fill=BOTH, expand=1)

        # Configure layout
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.columnconfigure(2, weight=1)
        self.rowconfigure(5, weight=1)
        self.rowconfigure(6, weight=1)

        # Title of program
        lbl = Label(self, text="Network/Port Scan")
        lbl.grid(sticky=W, pady=5, padx=5)

        # Text Box
        area = ScrolledText(self, height=20)
        area.grid(row=1,
                  column=0,
                  columnspan=3,
                  rowspan=4,
                  padx=3,
                  sticky=N + S + E + W)
        self.area = area

        # IP Address Button
        self.ip = BooleanVar()
        ip_add_button = Checkbutton(self,
                                    text="IP Address",
                                    variable=self.ip,
                                    width=10)
        ip_add_button.grid(row=1, column=3, sticky=N)
        ip_add_button.config(anchor=W, activebackground="red")

        # Port Button
        self.port = BooleanVar()
        port_button = Checkbutton(self,
                                  text="Ports",
                                  variable=self.port,
                                  width=10)
        port_button.grid(row=1, column=3)
        port_button.config(anchor=W, activebackground="orange")

        # Host Name Button
        self.host = BooleanVar()
        host_name_button = Checkbutton(self,
                                       text="Host Name",
                                       variable=self.host,
                                       width=10)
        host_name_button.grid(row=1, column=3, sticky=S)
        host_name_button.config(anchor=W, activebackground="yellow")

        # Gateway Button
        self.gateway = BooleanVar()
        gateway_btn = Checkbutton(self,
                                  text="Gateway",
                                  variable=self.gateway,
                                  width=10)
        gateway_btn.grid(row=2, column=3, sticky=N)
        gateway_btn.config(anchor=W, activebackground="green")

        # Services Button
        self.service = BooleanVar()
        service_btn = Checkbutton(self,
                                  text="Services",
                                  variable=self.service,
                                  width=10)
        service_btn.grid(row=2, column=3)
        service_btn.config(anchor=W, activebackground="blue")

        # Starting IP label
        ip_label = Label(self, text="Starting IP:  ")
        ip_label.grid(row=5, column=0, pady=1, padx=3, sticky=W)
        self.ip_from = Entry(self, width=15)
        self.ip_from.insert(0, start_ip)
        self.ip_from.grid(row=5, column=0, pady=1, padx=3, sticky=E)

        # Ending IP label
        ip_label_two = Label(self, text="Ending IP:  ")
        ip_label_two.grid(row=5, column=1, pady=1, padx=5, sticky=W)
        self.ip_to = Entry(self, width=15)
        self.ip_to.insert(0, end_ip)
        self.ip_to.grid(row=5, column=1, pady=1, padx=5, sticky=E)

        # Starting Port Label
        port_label = Label(self, text="Starting Port:  ")
        port_label.grid(row=5, column=0, pady=3, padx=5, sticky=S + W)
        self.port_from = Entry(self, width=15)
        self.port_from.insert(0, 0)
        self.port_from.grid(row=5, column=0, pady=1, padx=5, sticky=S + E)

        # Ending Port Label
        port_label_two = Label(self, text="Ending Port:  ")
        port_label_two.grid(row=5, column=1, pady=3, padx=5, sticky=S + W)
        self.port_to = Entry(self, width=15)
        self.port_to.insert(0, 1025)
        self.port_to.grid(row=5, column=1, pady=1, padx=5, sticky=S + E)

        # Scan Me
        self_scan_button = Button(self,
                                  text="Scan Me",
                                  command=lambda: self.onClick(1),
                                  width=33)
        self_scan_button.grid(row=6, column=1, sticky=N)

        # Scan near me Button
        scan_other_button = Button(self,
                                   text="Scan Near Me",
                                   width=33,
                                   command=lambda: self.onClick(2))
        scan_other_button.grid(row=6, column=0, pady=1, sticky=N)

        # Clear button
        clear_button = Button(self,
                              text="Clear text",
                              command=self.clear_text,
                              width=12)
        clear_button.grid(row=6, column=3, pady=1, sticky=N)

        # Progress Bar
        self.label_scanning = Progressbar(self, orient=HORIZONTAL, length=175)
        self.label_scanning.grid(row=6,
                                 column=0,
                                 columnspan=4,
                                 padx=7,
                                 pady=7,
                                 sticky=E + S + W)
        self.label_scanning.config(mode="determinate")

    # Clear what is in the text box.
    def clear_text(self):
        self.area.delete(0.0, 'end')
        # empty my lists.
        my_ports[:] = []
        ip_address_up[:] = []
        target_host_name[:] = []
        target_port_up[:] = []

    # On click methods for scan me and scan others.
    def onClick(self, button_id):

        if button_id == 1:

            # Check to see if host button is marked
            if self.host.get() == 1:
                message = my_host_name()
                self.area.insert(0.0, message, ("warning"))
                self.area.tag_configure("warning", foreground="blue")

            # Check to see if ports button is marked
            if self.port.get() == 1:
                # Check port entry widgets.
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()
                        message, total = scan_my_ports(int(starting_port),
                                                       int(ending_port))
                        for i in message:
                            new_message = "My TCP " + i + "\n"
                            self.area.insert(0.0, new_message, ("ports"))
                            #self.area.tag_configure("ports", foreground = "green")

                    time = "The TCP port scan completed in: " + str(
                        total) + "\n"
                    self.area.insert(0.0, time, ("timing"))
                    self.area.tag_configure("timing", foreground="red")
                else:
                    self.area.insert(0.0, "No valid ports specified.")

            # Check to see if IP button is marked
            if self.ip.get() == 1:
                message = my_ip()
                self.area.insert(0.0, message)

            # Check if gateway button is marked.
            if self.gateway.get() == 1:
                message = my_gateway()
                self.area.insert(0.0, message)

            # Check if service button is marked.
            if self.service.get() == 1:
                message, time = scan_my_services()
                for i in message:
                    new_message = i + "\n"
                    self.area.insert(0.0, new_message)
                new_time = "The local scan completed in: " + str(time) + "\n"
                self.area.insert(0.0.new_time, ("timing"))
                self.area.tag_configure("timing", foreground="red")

        # If Scan other button is clicked.
        elif button_id == 2:

            # Check other IP's
            if self.ip.get() == 1:
                # Check the entry widgets.
                if self.ip_from:
                    if self.ip_to:
                        # Get the ranges from the entry widgets
                        starting_ipv4_address = self.ip_from.get()
                        ending_ipv4_address = self.ip_to.get()

                        # Pass the values from the entry widgets into the function to scan nearby IP addresses.
                        message, time = ping_ip_other(starting_ipv4_address,
                                                      ending_ipv4_address)
                        if message:
                            for i in message:
                                new_message = "The address:     {:>15} {:>15}".format(
                                    i, "is UP\n")
                                self.area.insert(0.0, new_message)

                        total_time = "Range scanned: " + str(
                            starting_ipv4_address) + " to " + str(
                                ending_ipv4_address
                            ) + "\n" + "The IP scan completed in:  " + str(
                                time) + "\n"
                        self.area.insert(0.0, total_time, ("timing"))
                        self.area.tag_configure("timing", foreground="red")

                else:
                    self.area.insert(0.0, "No Ip range is specified.")

            # Check others Ports
            if self.port.get() == 1:
                # Check port entry widgets.
                if self.port_from:
                    if self.port_to:
                        # Get the user input
                        starting_port = self.port_from.get()
                        ending_port = self.port_to.get()

                        message, time = scan_ports_other(
                            int(starting_port), int(ending_port))
                        if message:
                            for i in message:
                                new_msg = "The " + i + "\n"
                                self.area.insert(0.0, new_msg)
                        else:
                            new_msg = "Must scan nearby IP addresses first.\n"

                    total_time = "TCP Port scan completed in: " + str(
                        time) + "\n"
                    self.area.insert(0.0, total_time, ("timing"))
                    self.area.tag_configure("timing", foreground="red")

                else:
                    self.area.insert(0.0, "No Port range specified.")

            # Check other host names. Based on IP's scanned.
            if self.host.get() == 1:
                message, time = scan_host_other(ip_address_up)
                # Check that IP's of other computers were collected
                if message:
                    for i in message:
                        new_message = "Host name: " + str(i) + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "Must scan nearby IP addresses first. \n"
                    self.area.insert(0.0, new_msg)

                total = "The host scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, total, ("timing"))
                self.area.tag_configure("timing", foreground="red")

            # Check gateway return the gateway of the host machine again.
            if self.gateway.get() == 1:
                message = "\n" + str(my_gateway())
                self.area.insert(0.0, message)

            # Check what services are running on which IP and port.
            if self.service.get() == 1:
                message, time = services_other()
                if message:
                    for i in message:
                        new_message = i + "\n"
                        self.area.insert(0.0, new_message)

                else:
                    new_msg = "The IP addresses and ports must be scanned first."
                    self.area.insert(0.0, new_msg)

                new_time = "The service scan completed in: " + str(time) + "\n"
                self.area.insert(0.0, new_time, ("timing"))
                self.area.tag_configure("timing", foreground="red")

        else:
            pass
示例#56
0
文件: calc3.py 项目: sychov/conditer
def calc(itogo):

    def press_number(but):

        if calc.new:
            if but <> '.':
                if but <> '0':
                    calc.string2.set(but)
                    calc.new = FALSE
            else:
                calc.string2.set('0.')
                calc.new = FALSE
                calc.cent = 1
        else:
            if (len(calc.string2.get()) < 11) and (calc.cent < 3):
                if but <> '.':
                    calc.string2.set(calc.string2.get() + but)
                    if calc.cent:
                        calc.cent += 1
                else:
                    if '.' not in calc.string2.get():
                        calc.string2.set(calc.string2.get() + '.')
                        calc.cent = 1


    def press_operation(but):

        if but == 'C':
            calc.operation = ''
            calc.number = 0
            calc.new = True
            calc.cent = 0
            calc.string2.set('0')
            calc.string3.set('0')

        elif but == '<':
            if not calc.new:
                st = calc.string2.get()
                calc.string2.set(st[:-1])
                if calc.cent:
                    calc.cent -= 1
                if calc.string2.get() == '0':
                    calc.new = True
                if calc.string2.get() == '':
                    calc.new = True
                    calc.string2.set('0')
        elif but == '=':
            calc.new = True
            calc.cent = 0
            calc.string_now = float(calc.string2.get())
            result = calc.string_now - float(itogo_variable.get())
            if result == round(result):
                calc.string3.set(str(result)[:-2])
            else:
                calc.string3.set('%11.2f' % result)

    #=============================================================

    calc.new = True
    calc.cent = 0

    window_calc = Toplevel()
    window_calc.resizable(False, False)
    window_calc.title(u'Калькулятор сдачи')
    window_calc.geometry('+%d+%d' % (-500, -500))
    window_calc.focus_set()

    style = Style(window_calc)
    style.configure('Number.TButton', font=('Lucida Console', CALC_SCALE, 'bold'),
                    foreground='blue', justify='center')
    style.configure('Operation.TButton', font=('Lucida Console', CALC_SCALE, 'bold'),
                    foreground='red', justify='center')

    itogo_variable = StringVar()
    itogo_variable.set('%.2f' % itogo)
    calc.string2 = StringVar()
    calc.string2.set('0')
    calc.string3 = StringVar()
    calc.string3.set('0')


    Label(window_calc, font=('Lucida Console', FONT_SIZE_BIG, 'italic'),
            text='Итог по счету:', width=13, justify=RIGHT, anchor=E).grid(
                column=0, row=0, columnspan=4,
                padx=CALC_PAD, pady=CALC_PAD*2, sticky='NWES')


    label1 = Label(window_calc, font=('Lucida Console', CALC_SCALE, 'bold'),
                        textvariable=itogo_variable, width=13, justify=RIGHT,
                        bg='white', anchor=E, fg='grey')
    label1.grid(column=0, row=1, columnspan=4, padx=CALC_PAD, pady=CALC_PAD*2)

    Label(window_calc, font=('Lucida Console', FONT_SIZE_BIG, 'italic'),
            text='Получено:', width=13, justify=RIGHT, anchor=E).grid(
                column=0, row=2, columnspan=4,
                padx=CALC_PAD, pady=CALC_PAD*2, sticky='NWES')

    label2 = Label(window_calc, font=('Lucida Console', CALC_SCALE, 'bold'),
                                        textvariable=calc.string2, width=13,
                                        justify=RIGHT, bg='white', anchor=E)
    label2.grid(column=0, row=3, columnspan=4, padx=CALC_PAD, pady=CALC_PAD*2)

    Label(window_calc, font=('Lucida Console', FONT_SIZE_BIG, 'italic'),
            text='Сдача:', width=13, justify=RIGHT, anchor=E).grid(
                column=0, row=8, columnspan=4,
                padx=CALC_PAD, pady=CALC_PAD*2, sticky='NWES')

    label3 = Label(window_calc, font=('Lucida Console', CALC_SCALE, 'bold'),
                                        textvariable = calc.string3, width=13,
                                        justify=RIGHT, bg='white', anchor=E)
    label3.grid(column=0, row=9, columnspan=4, padx=CALC_PAD, pady=CALC_PAD*2)

    for q in range(1,10):
        Button(window_calc, text=str(q), style='Number.TButton', width=1,
                    command=lambda q=q: press_number(str(q))).grid(
                    column=(q-1)%3, row=4+(q-1)//3, padx=CALC_PAD, pady=CALC_PAD,
                    ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2, sticky='NWES')

    Button(window_calc, text='0', style='Number.TButton', width=1,
                    command=lambda: press_number('0')).grid(
                    column=0, row=7, padx=CALC_PAD, pady=CALC_PAD,
                    ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2, columnspan=2,
                    sticky='NWES')

    Button(window_calc, text='.', style='Number.TButton', width=1,
                    command=lambda: press_number('.')).grid(
                    column=2, row=7, padx=CALC_PAD, pady=CALC_PAD,
                    ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2, sticky='NWES')

    Button(window_calc, text='C', style='Operation.TButton', width=1,
                    command=lambda: press_operation('C')).grid(
                    column=3, row=4, padx=CALC_PAD, pady=CALC_PAD,
                    ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2, sticky='NWES')

    Button(window_calc, text='<', style='Operation.TButton', width=1,
                    command=lambda: press_operation('<')).grid(
                    column=3, row=5, padx=CALC_PAD, pady=CALC_PAD,
                    ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2, sticky='NWES')

    Button(window_calc, text='=', style='Operation.TButton', width=1,
                    command=lambda: press_operation('=')).grid(
                    column=3, row=6, padx=CALC_PAD, pady=CALC_PAD,
                    ipadx=CALC_SCALE/3*2, ipady=CALC_SCALE/2, rowspan=2,
                    sticky='NWES')

    window_calc.update()
    parent_name = window_calc.winfo_parent()
    parent = window_calc._nametowidget(parent_name)
    parentX = parent.winfo_width()
    childX = window_calc.winfo_width()
    calc_x = parentX - childX- 100

    window_calc.geometry('+%d+50' % calc_x)

    return window_calc, itogo_variable, calc.string2, calc.string3
    def __init__(self,
                 master,
                 columns,
                 data=None,
                 command=None,
                 sort=True,
                 select_mode=None,
                 heading_anchor=CENTER,
                 cell_anchor=W,
                 style=None,
                 height=None,
                 padding=None,
                 adjust_heading_to_content=False,
                 stripped_rows=None,
                 selection_background=None,
                 selection_foreground=None,
                 field_background=None,
                 heading_font=None,
                 heading_background=None,
                 heading_foreground=None,
                 cell_pady=2,
                 cell_background=None,
                 cell_foreground=None,
                 cell_font=None,
                 headers=True):

        self._stripped_rows = stripped_rows

        self._columns = columns

        self._number_of_rows = 0
        self._number_of_columns = len(columns)

        self.row = self.List_Of_Rows(self)
        self.column = self.List_Of_Columns(self)

        s = Style()

        if style is None:
            style_name = "Multicolumn_Listbox%s.Treeview" % self._style_index
            self._style_index += 1
        else:
            style_name = style

        style_map = {}
        if selection_background is not None:
            style_map["background"] = [('selected', selection_background)]

        if selection_foreground is not None:
            style_map["foeground"] = [('selected', selection_foreground)]

        if style_map:
            s.map(style_name, **style_map)

        style_config = {}
        if cell_background is not None:
            style_config["background"] = cell_background

        if cell_foreground is not None:
            style_config["foreground"] = cell_foreground

        if cell_font is None:
            font_name = s.lookup(style_name, "font")
            cell_font = nametofont(font_name)
        else:
            if not isinstance(cell_font, Font):
                if isinstance(cell_font, basestring):
                    cell_font = nametofont(cell_font)
                else:
                    if len(font) == 1:
                        cell_font = Font(family=cell_font[0])
                    elif len(font) == 2:
                        cell_font = Font(family=cell_font[0],
                                         size=cell_font[1])

                    elif len(font) == 3:
                        cell_font = Font(family=cell_font[0],
                                         size=cell_font[1],
                                         weight=cell_font[2])
                    else:
                        raise ValueError(
                            "Not possible more than 3 values for font")

            style_config["font"] = cell_font

        self._cell_font = cell_font

        self._rowheight = cell_font.metrics("linespace") + cell_pady
        style_config["rowheight"] = self._rowheight

        if field_background is not None:
            style_config["fieldbackground"] = field_background

        s.configure(style_name, **style_config)

        heading_style_config = {}
        if heading_font is not None:
            heading_style_config["font"] = heading_font
        if heading_background is not None:
            heading_style_config["background"] = heading_background
        if heading_foreground is not None:
            heading_style_config["foreground"] = heading_foreground

        heading_style_name = style_name + ".Heading"
        s.configure(heading_style_name, **heading_style_config)

        treeview_kwargs = {"style": style_name}

        if height is not None:
            treeview_kwargs["height"] = height

        if padding is not None:
            treeview_kwargs["padding"] = padding

        if headers:
            treeview_kwargs["show"] = "headings"
        else:
            treeview_kwargs["show"] = ""

        if select_mode is not None:
            treeview_kwargs["selectmode"] = select_mode

        self.interior = Treeview(master, columns=columns, **treeview_kwargs)

        if command is not None:
            self._command = command
            self.interior.bind("<<TreeviewSelect>>", self._on_select)

        for i in range(0, self._number_of_columns):

            if sort:
                self.interior.heading(
                    i,
                    text=columns[i],
                    anchor=heading_anchor,
                    command=lambda col=i: self.sort_by(col, descending=False))
            else:
                self.interior.heading(i,
                                      text=columns[i],
                                      anchor=heading_anchor)

            if adjust_heading_to_content:
                self.interior.column(i, width=Font().measure(columns[i]))

            self.interior.column(i, anchor=cell_anchor)

        if data is not None:
            for row in data:
                self.insert_row(row)
示例#58
0
    def initUI(self):
      if not test_mode:
        run_pupil()

      #  Defining a method for absolute positioning of an image
      def place_img(self, filename, x, y):
        img = Image.open(filename)
        img = ImageTk.PhotoImage(img)
        lbl1 = Label(self, image=img)
        lbl1.image = img
        lbl1.place(x=x, y=y)

      def clear_frame(frame):
        for child in frame.winfo_children():
          child.destroy()

      def clear_panel(panel):
        for match_label in panel['match_labels']:
          match_label['text'] = ''
        for pic_frame in panel['match_pics']:
          clear_frame(pic_frame)
        clear_frame( panel['left_pic'] )
        panel['left_pic_label']['text'] = ''

      #  Defining a method for framewise positioning of an image
      # @params
      #   frame   the frame to attach filename to
      def insert_img(self, filename, frame, pic_path, label):
        clear_frame(frame)
        sizeY = frame.winfo_height()
        sizeX = frame.winfo_width()
        img = Image.open(filename)
        img = img.resize((sizeY, sizeX), Image.ANTIALIAS)
        # Subtract 8 for various borders in the frame.
        img = img.resize((sizeX-8, sizeY-8), Image.ANTIALIAS)
        img = ImageTk.PhotoImage(img)
        # The image is wrapped with a label to make it easier to place.
        lbl1 = Label(frame, image=img)

        #  Closure function for callback. This function will save the captured
        #   image of this specific panel, adding it to the model of the 
        #   person associated with the face being clicked on
        def save_image(event):
          global comparison_directory
          folder = "../face_comparison/%s/%s" %(comparison_directory,label)
          os.system("ls " + folder + " | wc -l > output.txt")
          f = open("output.txt", 'r')
          file_number = str(int(f.readline().rstrip().lstrip()) + 1)
          command = "cp " + pic_path + " " + folder + "/" +  file_number + ".jpg"
          add_face(pic_path, label)
          info_box['text'] = "Saved %s to %s" % (pic_path, folder)
          print command
          os.system(command)

        lbl1.image = img
        lbl1.bind('<Button-1>', save_image)
        lbl1.place(x=frame.winfo_x(), y=frame.winfo_y())

      self.parent.title("Eyedentify")

      menubar = Menu(self.parent)
      self.parent.config(menu=menubar)
  
      fileMenu = Menu(menubar)

      submenu = Menu(fileMenu)
      classes = get_dir_names()
      for cls in classes:
        #  This nesting is sort of weird, but is necessary due to
        #    how closures work in a loop.
        def make_fn(x):
          def fn():
            global comparison_directory
            comparison_directory = x
            update_group(comparison_directory, comparison_directory)
          return fn
        submenu.add_command(label=cls, command = make_fn(cls))
          
      ##  File menu commands
      fileMenu.add_cascade(label='Choose Class', menu=submenu, underline=0)
      fileMenu.add_separator()
      fileMenu.add_command(label="Exit", command=self.onExit)
      menubar.add_cascade(label="File", menu=fileMenu)

      style = Style()  #default style
      style.configure("TButton", padding=(0, 5, 0, 5), 
                      font='serif 10')
      style.configure("TFrame", background="#333")        
      style.configure("TLabel", background="#333")        

      #  Effectively causes our window size to be 650 by 500
      self.columnconfigure(0,pad=10, minsize=650, weight=1)
      self.columnconfigure(1,pad=10)
      self.rowconfigure(0,pad=10, minsize=500, weight=1)
      self.rowconfigure(1,pad=10, weight=1)

      self.pack()

      # Top box
      upper_frame = Frame(self, relief=RAISED )
      upper_frame.grid(row = 0, column = 0, columnspan=2, sticky=N+E+S+W)

      # Creates a panel in the frame passed in, and returns a list of frame objects
      #  that need to be accessed in the panel
      def save_image(event):
        print event.widget
        
        folder = "../face_comparison/" + comparison_directory + "/" + \
              event.widget.getvar('label')
        os.system("ls " + folder + " | wc -l > output.txt")
        f = open("output.txt", 'r')
        file_number = str(int(f.readline().rstrip().lstrip()) + 1)
        command = "cp " + event.widget.getvar('pic') + " " + folder + "/" +  file_number + ".jpg"
        print command
        os.system(command)

      def make_panel(panel_frame):
        ### p1 is the panel being made by this function.
        p1 = Frame(upper_frame, relief=RAISED, borderwidth =1)
        p1.pack(side = TOP, fill = BOTH, expand=1)

        pic_frame1 = Frame(p1, relief=RAISED, borderwidth =1)
        pic_frame1.pack(side = LEFT, fill = BOTH, expand=1,padx=15, pady=4)
        pic1 = Frame(pic_frame1, relief=RAISED, borderwidth =1)
        pic1.pack(side = TOP, fill = BOTH, expand=1)
        label1 = Label(pic_frame1, relief=RAISED, borderwidth =1, 
            text ="Captured face", width = 15)
        label1.pack(side = BOTTOM, fill = BOTH)

        info_panel = Frame(p1, relief=RAISED, borderwidth =1)
        info_panel.pack(side = LEFT, fill = BOTH, expand=1)
        bt = Label(info_panel, text="Best\nMatches:", background="#ececec")
        bt.pack(pady=20)

        match_pictures = []
        match_labels = []
        #  These are the three matches in the right side of the panel
        for i in range(3):
          pic_frame = Frame(p1, relief=RAISED, borderwidth =1)
          pic_frame.pack(side = LEFT, fill = BOTH, expand=1,padx=15, pady=4)
          pic = Frame(pic_frame, relief=RAISED, borderwidth =1)
          pic.pack(side = TOP, fill = BOTH, expand=1)
          match_pictures.append(pic)
          label = Label(pic_frame, relief=RAISED, borderwidth =1, 
              text = "Match %d"%(i+1), width=15)
          label.pack(side = BOTTOM, fill = BOTH)
          match_labels.append(label)


        return {"left_pic":pic1, "left_pic_label":label1,  "match_pics":match_pictures, 
                                "match_labels":match_labels}

      #  make 3 panels
      panel_data = []
      panel_data.append( make_panel(upper_frame) )
      panel_data.append( make_panel(upper_frame) )
      panel_data.append( make_panel(upper_frame) )

      def capture():
        coord = []
        if not test_mode:
          pic_file, coord = take_snapshot()
          pic_file = os.path.abspath(pic_file)
        else:
          pic_file = sys.argv[1]
          if len(sys.argv) >= 4:
            coord = [float(sys.argv[2]), float(sys.argv[3])]
          else:
            coord = [0.5,0.5]

        if len(coord) == 0:
          tkMessageBox.showwarning("Error",
                "Pupil device failed to capture gaze.")

        else:
          im=Image.open(pic_file)
          im.size # (width,height) tuple
          coord[0] = int(float(coord[0]) * im.size[0])
          coord[1] = int(float(coord[1]) * im.size[1])
          faces = facial_detection(pic_file, coord[0], coord[1])
          associated_matches = {}
          if len(faces) == 0:
            tkMessageBox.showwarning("Error",
                "No faces were found.")

          for face in faces:
            print "comparison directory"
            print comparison_directory
            #get the top three matches for each face
            associated_matches[face['path']] = compare( face, 
                   comparison_directory)

          index = -1
          for index, face in enumerate(faces):
            #get the top three matches for each face
            face_matches = associated_matches[face['path']]
            panel = panel_data[index]
            #place the captured face in the panel
            insert_img(self, face['path'], panel['left_pic'], face['path'], "")
            panel['left_pic_label']['text'] = "Captured face"
            j = -1
            for j, match in enumerate(face_matches):
              #place the matches in the panel
              panel['match_labels'][j]['text'] = match['id'].replace('_',' ')
              insert_img(self, match['match_path'], panel['match_pics'][j], face['path'], match['id'])
            # Clear the non-match frames
            for k in range(j+1, len(panel['match_pics'])):
              clear_frame( panel['match_pics'][k]  )
              panel['match_labels'][k]['text'] = "No more matches"
          # Clear the non-match panels
          for k in range(index+1, len(panel_data)):
            clear_panel(panel_data[k])
          if index == -1:
            panel_data[0]['left_pic_label']['text'] = "No faces detected"


      #def key(event):
        ## 'Enter' key triggers capture.
        #if event.char == '\r':
          #capture()
#
      # Bind to parent, so that the focus never leaves it. 
      self.parent.focus_set()
      self.parent.bind('<Return>', lambda event: capture())

      global info_box
      info_box = Label(self, text="Press Enter to capture gaze. Click on a matching face to add the captured face to the daset of the match.", background="#ececec")
      info_box.grid(row=1,column=0)

      # Some weird hack to bring this window to the front as it is launched. 
      #  Won't work on windows.
      if os.name == "posix":
        os.system('''/usr/bin/osascript -e 'tell app "Finder" to set frontmost of process "Python" to true' ''')