コード例 #1
0
def event_select(event=None):
    """Displays the event details in a popup window"""

    value = event_tree.item(event_tree.selection()[0], 'value')
    popup = tk.Toplevel(root)
    popup.title(eval(value[-1])[0])
    popup.minsize(150, 100)
    tk.Label(popup,
             text=eval(value[-1])[0] + ' (' + str(date_selected) + ')',
             font=('Courier', 14, 'bold')).pack(side='top', fill='x')
    desc = ScrolledText(popup,
                        bg='gray10',
                        fg='white',
                        font=('Courier New', '12'),
                        wrap='word',
                        height=10,
                        width=30)
    desc.insert('insert', eval(value[-1])[-1])
    desc.config(state='disabled')
    desc.pack(expand=True, fill='both')
    tk.Label(popup, text='tags: ' + eval(value[-1])[1],
             font=('Courier', 12)).pack()
    tk.Button(popup,
              text='Delete Event',
              bg='#F21',
              fg='#FFF',
              font=('Courier', 12),
              command=lambda: delete_event(eval(value[0]), eval(value[1]),
                                           popup)).pack(side='bottom')
    popup.mainloop()
コード例 #2
0
ファイル: poetry.py プロジェクト: Xreflextion/Poetry
    def update_box(self, box: scrolledtext.ScrolledText, message: str) -> None:
        """Clear the output box in the app and put message inside it."""

        box.config(state=tk.NORMAL)
        box.delete('1.0', tk.END)
        box.insert('1.0', message)
        box.config(state=tk.DISABLED)
コード例 #3
0
ファイル: gi.py プロジェクト: 0secmy/information_collection
def level(url):
    win1 = tk.Tk()
    win1.title('level-2')
    sw = win1.winfo_screenwidth()
    sh = win1.winfo_screenheight()
    ww = 800
    wh = 510
    x = (sw - ww) / 2
    y = (sh - wh) / 2
    win1.geometry("%dx%d+%d+%d" % (ww, wh, x - 100, y))
    t11 = ScrolledText(win1, height=32, width=97, font=20)
    t11.place(x=0, y=0)
    t11.config(state=NORMAL)

    def start(url):
        t11.config(state=NORMAL)
        t11.insert('end', 'scanning......')
        t11.config(state=DISABLED)
        value, missage = level2.dump_data(url)
        t11.config(state=NORMAL)
        t11.delete(1.0, END)
        t11.config(state=DISABLED)
        t11.config(state=NORMAL)
        for k in value.keys():
            t11.insert('end', k + ' : ' + value[k][0] + '\n\r\n\r')
        for i in missage.keys():
            for k in missage[i].keys():
                t11.insert('end', '\n\r' + k + ' :\n\r\t')
                for data in missage[i][k]:
                    t11.insert('end', data + '\n\r\t')
        t11.config(state=DISABLED)

    T = threading.Thread(target=start, args=(url, ))
    T.start()
    win1.mainloop()
コード例 #4
0
ファイル: gui.py プロジェクト: hamptus/mftpy
    def update(self, event):
        self.selected = self.listbox.curselection()
        self.removeTabs()
        try:
            e = self.listitems[int(self.selected[0])]

            self.entryTab = ScrolledText(self.notebook, relief=SUNKEN, padx=10, pady=5)

            self.entryTab.insert(END, "Signature: %s\n" % e.signature)
            self.entryTab.insert(END, "Fixup array offset: %s\n" % e.fixup_array_offset)
            self.entryTab.insert(END, "Fixup array entries: %s\n" % e.fixup_array_entries)
            self.entryTab.insert(END, "$LogFile sequence number: %s\n" % e.lsn)
            self.entryTab.insert(END, "Sequence: %s\n" % e.sequence)
            self.entryTab.insert(END, "Link count: %s\n" % e.link_count)
            self.entryTab.insert(END, "Attribute offset: %s\n" % e.attribute_offset)
            self.entryTab.insert(END, "Flags: %s\n" % e.flags)
            self.entryTab.insert(END, "Used size: %s\n" % e.used_size)
            self.entryTab.insert(END, "Allocated size: %s\n" % e.allocated_size)
            self.entryTab.insert(END, "File reference: %s\n" % e.file_ref)
            self.entryTab.insert(END, "Next attribute ID: %s\n" % e.next_attr_id)

            self.entryTab.config(state=DISABLED)
            self.notebook.add(self.entryTab, text=e.filename)

            for attribute in e.attributes:
                tab = ScrolledText(self.notebook, relief=SUNKEN, padx=10, pady=5)
                for i in attribute.export():
                    tab.insert(END, i + "\n")
                tab.config(state=DISABLED)
                self.notebook.add(tab, text=attribute.attr_type.value)

        except IndexError:
            pass
コード例 #5
0
class MessageReceiver(tk.Frame):
    """
    Component responsible for get a message from an input, encrypt it and send it
    """
    def __init__(self, *args, **kwargs):
        super(MessageReceiver, self).__init__(*args, **kwargs)
        self._label = tk.Label(self, text='Received message:')
        self._text_input = ScrolledText(self, height=3, state=tk.DISABLED)
        self._pack_widgets()

    def _pack_widgets(self):
        self._label.pack(side=tk.TOP)
        self._text_input.pack(padx=10)

    def set_message(self, message_file, encrypted_mode):
        """
        Set encrypted message
        """
        file = File(message_file, encrypted_mode=encrypted_mode)
        file.decrypt(self._key, self._iv, mode=encrypted_mode)
        self._text_input.config(state=tk.NORMAL)
        self._text_input.delete("1.0", tk.END)
        self._text_input.insert('1.0', file.data)
        self._text_input.config(state=tk.DISABLED)

    def set_keys(self, key, iv):
        self._key = key
        self._iv = iv
コード例 #6
0
 def receivePrivateChat(self, connectingUser):
     global conversationBoxList
     print("CHAT PRIVATA in arrivo con "+connectingUser)
         
     newWindow = Toplevel(self.parent)
     newWindow.title("Python Chat requested by "+connectingUser)
     newWindow.minsize(400, 475)
     newWindow.focus()
     
     def disconnectPM():
         del conversationBoxList[connectingUser]
         newWindow.destroy()
     newWindow.protocol('WM_DELETE_WINDOW', disconnectPM)
     
     #label = Label(newWindow, text="PROVA PROVA")
     #label.pack(side="top", fill="both", padx=10, pady=10)
     frame = Frame(newWindow)
     frame.pack(fill=BOTH, expand=1, side=LEFT)
     
     box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
     box.config(state=DISABLED)
     box.pack(expand="yes", fill=BOTH, side=TOP)
     
     textarea = Text(frame, width=30, height=5)
     textarea.bind("<KeyRelease-Return>", lambda event : self.getprivatetext(event, textarea, connectingUser)) 
     textarea.pack(expand="yes", fill=BOTH, side=TOP)
     
     #aggiungo alla mappa globale il box di conversazione
     conversationBoxList[connectingUser] = box
コード例 #7
0
def show_text(textstring, titlestring=" "):
    """
    Bring up a window within which the input text is displayed.

    Parameters
    ----------

    textstring:  a string variable that is displayed in the window

    titlestring:  an optional string variable that is used as the title 
                  of the window

    Returns
    -------

    None

    """
    message_window = Tk.Toplevel()
    message_window.title(titlestring)
    frame1 = Tk.Frame(message_window)
    frame1.pack(side=Tk.TOP)
    message_text = ScrolledText(frame1,
                                height=40,
                                width=80,
                                bd=1,
                                relief=Tk.RIDGE,
                                wrap=Tk.NONE)
    message_text.config(font=('courier', 16, 'bold'))
    message_text.pack()
    message_text.insert('0.0', textstring)
    frame2 = Tk.Frame(message_window)
    frame2.pack()
    button1 = Tk.Button(frame2, text='Close', command=message_window.destroy)
    button1.pack()
コード例 #8
0
ファイル: result.py プロジェクト: ycwan9/py-judge-homework
class ResultView(Dialog):
    """configure test cases"""

    def __init__(self, test_result):
        self.test_result = test_result
        super().__init__(tk._default_root, "评测结果")

    def body(self, master):
        master.pack(fill=tk.BOTH)
        self.resultlist = tk.Listbox(master)
        self.resultlist.pack(fill=tk.BOTH)
        self.resultlist.bind("<<ListboxSelect>>", self.cb_list)
        self.resultdetail = ScrolledText(master, state=tk.DISABLED)
        self.resultdetail.pack(fill=tk.BOTH)
        for case_name, ret, time_len, err_msg in self.test_result:
            item_color = "blue" if ret == "AC" else "red"
            self.resultlist.insert(
                tk.END, f"{ret} {time_len:0.3f}s {case_name}")
            self.resultlist.itemconfigure(tk.END, fg=item_color)

    def cb_list(self, event):
        selection = event.widget.curselection()
        if not selection:
            return
        pos = selection[0]
        case_name, ret, time_len, err_msg = self.test_result[pos]
        detail = f"""\
结果:\t{RESULTS[ret]}
时间:\t{time_len} s
测试点:\t{case_name}
{err_msg}"""
        self.resultdetail.config(state=tk.NORMAL)
        self.resultdetail.delete("1.0", tk.END)
        self.resultdetail.insert("1.0", detail)
        self.resultdetail.config(state=tk.DISABLED)
コード例 #9
0
    def __init__(self, parent, controller):
        codeforceObj = Codeforce()
        codeforceEvents = codeforceObj.codeforceEvents
        tk.Frame.__init__(self,
                          parent,
                          highlightbackground="lightblue",
                          highlightcolor="lightblue",
                          highlightthickness=1,
                          width=720,
                          height=500,
                          bd=0)
        heading = tk.Label(self,
                           text="""
============================================================================================
	CODEFORCE EVENTS
============================================================================================""",
                           fg="#00e6e6",
                           bg="#0d0d0d",
                           font=LARGE_FONT)
        heading.pack(expand=False, fill="both")
        text = ScrolledText(self,
                            font=LARGE_FONT,
                            fg="#00ff00",
                            bg="#1a1a1a",
                            cursor="arrow")
        text.pack(expand=True, fill='both')
        text.insert(tk.INSERT, "\n root", 'red')
        text.insert(tk.INSERT, " @ ", 'white')
        text.insert(tk.INSERT, "Notifier")
        text.insert(tk.INSERT, " ># ", 'lightblue')
        text.insert(tk.INSERT, " get codeforceevents ")

        for event in codeforceEvents:
            text.insert(tk.INSERT, "\n\n [+]  ", 'orange')
            name = event['title']
            text.insert(tk.INSERT, name, 'lightblue')
            startTime = event['start']
            startTime = "\n\t>  " + "Starts: " + startTime
            text.insert(tk.INSERT, startTime)
            duration = "\n\t>  Duration: " + event['duration']
            text.insert(tk.INSERT, duration)
            beforeStartTime = "\n\t>  Before start: " + event['beforeStart']
            text.insert(tk.INSERT, beforeStartTime)
            beforeRegTime = "\n\t>  Before registration: " + event['beforeReg']
            text.insert(tk.INSERT, beforeRegTime)

            codeforceUrl = event['url']
            text.insert(tk.INSERT, "\n\t>  Event url: ")
            text.insert(tk.INSERT, codeforceUrl, ('link', codeforceUrl))
            text.insert(tk.INSERT, "\n")

        text.tag_config('link', foreground="#3385ff")
        text.tag_bind('link', '<Button-1>', self.openLink)
        text.tag_config('lightblue', foreground="#00e6e6")
        text.tag_config('red', foreground="red")
        text.tag_config('white', foreground="white")
        text.tag_config('orange', foreground="#ff6600")

        text.config(state=tk.DISABLED)
コード例 #10
0
class ReadMailWindow:
    def __init__(self, receiver='*****@*****.**', sender='*****@*****.**', topic='DefaultTopic', text='Dear:\n\nDefaultLine\nDefaultLine2\nDefaultLine3\n\nSincerely,\nDefaultUser'):
        '''
        create the ReadMailWindow.
        '''
        self.root = tk.Tk()
        self.root.title('Mail from '+sender)
        self.root.geometry('300x200')
        
        self.receiver=receiver
        self.sender=sender
        self.topic=topic
        self.text=text
        
        self.pane_for_sender = tk.PanedWindow(self.root,orient=tk.HORIZONTAL, borderwidth=5)
        self.pane_for_sender.pack(fill=tk.BOTH)
        self.lable_for_sender = tk.Label(self.pane_for_sender, text='From:', width=5, justify=tk.LEFT, anchor=tk.W)
        self.entry_for_sender = tk.Entry(self.pane_for_sender, width=10)
        self.entry_for_sender.insert(0, self.sender)
        self.entry_for_sender.config(state=tk.DISABLED)
        self.pane_for_sender.add(self.lable_for_sender)
        self.pane_for_sender.add(self.entry_for_sender)
        
        self.pane_for_topic = tk.PanedWindow(self.root, orient=tk.HORIZONTAL, borderwidth=5)
        self.pane_for_topic.pack(fill=tk.BOTH)
        self.lable_for_topic = tk.Label(self.pane_for_topic, text='Topic:', width=5, justify=tk.LEFT, anchor=tk.W)
        self.entry_for_topic = tk.Entry(self.pane_for_topic, width=10)
        self.entry_for_topic.insert(0, self.topic)
        self.entry_for_topic.config(state=tk.DISABLED)
        self.pane_for_topic.add(self.lable_for_topic)
        self.pane_for_topic.add(self.entry_for_topic)
        
        self.pane_for_content = tk.PanedWindow(self.root, orient=HORIZONTAL, borderwidth=7)
        self.pane_for_content.pack(fill=tk.BOTH, expand=1)
        self.lable_for_content = tk.Label(self.pane_for_content, text='Text:', justify=tk.LEFT, anchor=tk.W)
        self.text_for_content = ScrolledText(self.pane_for_content, width=10, height=4)
        self.text_for_content.insert(1.0, self.text)
        self.text_for_content.config(state=tk.DISABLED)
        self.pane_for_content.add(self.lable_for_content)
        self.pane_for_content.add(self.text_for_content)
        
        self.pane_for_button = tk.PanedWindow(self.root, orient=tk.HORIZONTAL)
        self.pane_for_button.pack(fill=tk.BOTH)
        self.button_for_reply = tk.Button(self.pane_for_button, text="Reply", command=self.Reply)
        self.button_for_close = tk.Button(self.pane_for_button, text="Exit", command=self.Destroy, width=5)
        self.pane_for_button.add(self.button_for_close) 
        self.pane_for_button.add(self.button_for_reply)
        

    def Reply(self):
        with open('acpwd.txt') as file:
            for line in file:
                acpwd = line.split(':')
                self.SMW = smw.SendMailWindow(self.receiver, self.sender, acpwd[1])
        self.SMW.text_for_content.insert(1.0, '\n\n---------------\n'+self.text)
        #self.root.destroy()
    
    def Destroy(self):
        self.root.destroy() 
コード例 #11
0
def edit_lines(plotgui):
    """
    Make window for editing the line values.

    This routine produces a text box in a window, within which one can
    edit the line values.  If no lines are defined the routine just
    exits with no action.

    Line values are presented one per text line, with the start x
    position, the start y position, the end x position, the end y
    position, the plot number, the line type, the line colour, and the
    line thickness separated by tab symbols.  One can edit the values
    within the text window and then these are applied when one clicks
    on the "Close Window" button.

    Parameters
    ----------

        plotgui : the matplotlib_user_interface object holding the plot

    Returns
    -------

        None

    """
    if plotgui.number_of_lines == 0:
        return
    str1 = 'Edit values below: fields are separated by tab characters.\n'\
           + '     start x       start y       end x         end y   ' \
           + 'plot        colour   line type  thickness\n------------' \
           + '-------------------------------------------------------' \
           + '-----------------------------\n'
    for loop in range(plotgui.number_of_lines):
        str1 = str1 + '%12.6g\t%12.6g\t%12.6g\t%12.6g\t%6d\t' % (
            plotgui.plot_lines[loop]['xstart'], plotgui.plot_lines[loop]
            ['ystart'], plotgui.plot_lines[loop]['xend'],
            plotgui.plot_lines[loop]['yend'], plotgui.plot_lines[loop]['plot'])
        str1 = str1 + '%15s\t%8s\t%7.3f\n' % (
            plotgui.plot_lines[loop]['line_colour'], plotgui.plot_lines[loop]
            ['line_type'], plotgui.plot_lines[loop]['line_thickness'])
    line_window = Tk.Toplevel()
    line_window.title('Lines:')
    holder = Tk.Frame(line_window)
    holder.pack(side=Tk.TOP)
    line_message_text = ScrolledText(holder,
                                     height=40,
                                     width=100,
                                     wrap=Tk.NONE)
    line_message_text.config(font=('courier', 16, 'bold'))
    line_message_text.pack(side=Tk.TOP)
    line_message_text.insert(0.0, str1)
    bholder = Tk.Frame(line_window)
    bholder.pack(side=Tk.TOP)
    close_button = Tk.Button(
        bholder,
        text='Close Window',
        command=lambda: read_lines(plotgui, line_message_text, line_window))
    close_button.pack()
コード例 #12
0
ファイル: mixins.py プロジェクト: josephchandlerjr/pythonlib
 def browser(self, filename):                         # if tkinter.scrolledtext
     new  = Toplevel()                                # included for reference
     text = ScrolledText(new, height=30, width=85)    
     text.config(font=('courier', 10, 'normal'))      
     text.pack(expand=YES, fill=BOTH)
     new.title("Text Viewer")                         
     new.iconname("browser")
     text.insert('0.0', open(filename, 'r').read() )  
コード例 #13
0
 def howToUse(self):
     with open('Data/How_to_use.txt', 'r') as txt_file:
         use_doc = txt_file.read()
     use_window = Toplevel(self.master)
     use_window.geometry('800x600+75+40')
     use_window.title('How to Use')
     use_text = ScrolledText(use_window, width=135, height=50, wrap='word')
     use_text.insert(1.0, use_doc)
     use_text.pack()
     use_text.config(state='disabled')
コード例 #14
0
 def info(self):
     mw = tkinter.Tk()
     mw.title('HELP') 
     txt = ScrolledText(mw, width=90, height=35)
     txt.pack()
     with open(HELP) as f:
         txt.insert(END, '\n    DXconvert-{} ({})\n'.format(PROGRAMVERSION, PROGRAMDATE))
         for line in f:
             txt.insert(END, line)
     txt.config(state=DISABLED)
     return
コード例 #15
0
    def __init__(self, parent, controller):
        leetcodeObj = Leetcode()
        leetcodeEvents = leetcodeObj.leetcodeEvents
        tk.Frame.__init__(self,
                          parent,
                          highlightbackground="lightblue",
                          highlightcolor="lightblue",
                          highlightthickness=1,
                          width=720,
                          height=500,
                          bd=0)
        heading = tk.Label(self,
                           text="""
============================================================================================
	LEETCODE EVENTS
============================================================================================""",
                           fg="#00e6e6",
                           bg="#0d0d0d",
                           font=LARGE_FONT)
        heading.pack(expand=False, fill="both")
        text = ScrolledText(self,
                            font=LARGE_FONT,
                            fg="#00ff00",
                            bg="#1a1a1a",
                            cursor="arrow")
        text.pack(expand=True, fill='both')
        text.insert(tk.INSERT, "\n root", 'red')
        text.insert(tk.INSERT, " @ ", 'white')
        text.insert(tk.INSERT, "Notifier")
        text.insert(tk.INSERT, " ># ", 'lightblue')
        text.insert(tk.INSERT, " get leetcodeEvents ")

        for event in leetcodeEvents:
            text.insert(tk.INSERT, "\n\n [+]  ", 'orange')
            name = event['title']
            text.insert(tk.INSERT, name, 'lightblue')
            startTime = event['start']
            startTime = "\n\t>  " + "Starts: " + startTime
            endTime = "\n\t>  " + "Finish: " + event['finish']
            description = startTime + endTime + "\n\t>  "
            text.insert(tk.INSERT, description)
            leetcodeUrl = event['url']
            text.insert(tk.INSERT, "\n\t>  Event url: ")
            text.insert(tk.INSERT, leetcodeUrl, ('link', leetcodeUrl))
            text.insert(tk.INSERT, "\n")

        text.tag_config('link', foreground="#3385ff")
        text.tag_bind('link', '<Button-1>', self.openLink)
        text.tag_config('lightblue', foreground="#00e6e6")
        text.tag_config('red', foreground="red")
        text.tag_config('white', foreground="white")
        text.tag_config('orange', foreground="#ff6600")

        text.config(state=tk.DISABLED)
コード例 #16
0
def descripText(destroy = False):
    'Laat de puntentelling zien op het spelscherm'
    T.pack_forget()
    global hint, root, destxt
    destxt = ScrolledText(root, height=8, width=50, padx=170, pady=50)
    destxt.pack()
    destxt.insert(END, hint)
    destxt.config(state=DISABLED)
    destxt.tag_configure("center", justify='center')
    destxt.tag_add("center", 1.0, "end")
    destxt.place(relx=1, x=-2, y=2, anchor=NE)
コード例 #17
0
ファイル: gui.py プロジェクト: wearyoung/daovision
	def _conButtonCmd(self):
		popwin = PopupWindow("Container Log")
		popwin.grab_set()
		popwin.focus()
		details = self.checkresult.getContainerLogs()
		stext = ScrolledText(popwin)
		stext.config(font = ("courier", 15, "normal"))
		stext.pack()
		for d in details:
			stext.insert("end",d)
		stext.see("end")
コード例 #18
0
def drawpagetable(pagelist):
    '''在控制面板绘制生成的页表
    '''
    show = ScrolledText(table, bg='#F0F0F0', width=15, height=30)
    show.place(x=50, y=10)
    show.insert('insert', '页号\t帧号\n')

    for item in pagelist:
        show.insert('insert', str(item[0]) + '\t')
        show.insert('insert', str(item[1]) + '\n')
    show.config(state=DISABLED)
コード例 #19
0
def logmain():
    '''Main window. The logs will be displayed here.'''
    loggui = Tk()
    loggui.title('Logfile Reader')
    loggui.config(bg='Gray')

    label_message = ScrolledText(loggui, width=100, height=20, bg='#e6e6e6')
    label_message.insert(INSERT, loglist())
    label_message.grid(row=2, column=3, columnspan=5, sticky='ew')
    label_message.config(state="disabled", font=('times', 18))

    loggui.mainloop()
コード例 #20
0
    def browser(self, filename):
        """
        生成一个简易文本编辑器
        """

        new = Toplevel()
        text = ScrolledText(new, height=30, width=85)
        text.config(font=('courier', 10, 'normal'))
        text.pack(expand=YES, fill=BOTH)
        new.title("Text Viewer")
        new.iconname("browser")
        text.insert('0.0', open(filename, 'r').read())
コード例 #21
0
 def procedureWindow(self):
     with open('Data/Procedures.txt', 'r') as txt_file:
         help_doc = txt_file.read()
     help_window = Toplevel(self.master)
     help_window.geometry('800x600+75+40')
     help_window.title('RCV Procedures')
     help_text = ScrolledText(help_window,
                              width=135,
                              height=50,
                              wrap='word')
     help_text.insert(1.0, help_doc)
     help_text.pack()
     help_text.config(state='disabled')
コード例 #22
0
ファイル: gui.py プロジェクト: wearyoung/daovision
	def _buttonCmd(self):
		popwin = PopupWindow("Details")
		popwin.grab_set()
		popwin.focus()
		details = self.checkresult.getDetails()
#		with os.popen("kubectl describe nodes/115.154.138.241") as re:
#			details = re.readlines()
		stext = ScrolledText(popwin)
		stext.config(font = ("courier", 15, "normal"))
		stext.pack()
		for d in details:
			stext.insert("end",d)
		stext.see("end")
コード例 #23
0
    def __init__(self,root):
        self.root = root

        # create a Frame for the Text and Scrollbar
        txt_frm = tki.Frame(self.root, width=800, height=600)
        txt_frm.pack(fill="both", expand=True)

        # Set to fullscreen if True
        if setToFullscreen:
            self.root.attributes('-fullscreen', True)

        # ensure a consistent GUI size
        txt_frm.grid_propagate(False)

        # function when enter is pressed
        self.root.bind('<Return>', GUI.func)

        #Create invitation label
        label1 = Label(self.root, text="Chatte mit mir", width=50, height=1, bg="white")
        label1.place(relx=0.5, rely=0.05, anchor=CENTER)
        label1.config(font=("Courier", 44))

        photo = PhotoImage(file="background.png")
        label2 = Label(txt_frm, image=photo)
        label2.image = photo  # keep a reference!
        label2.place(relx=0.5, rely=0.5, anchor=CENTER)


        global txt0 # textbox display thinking process
        txt0 = Entry(txt_frm, width=20, justify='center')
        txt0.place(relx=0.5, rely=0.19, anchor=CENTER)

        # Hide progress bar if no speech is not used
        if not useSpeechRecognition:
            txt0.place_forget()

        self.lbl1 = tki.Label(txt_frm, text="Chatbot - Halten sie den Knopf beim sprechen gedrückt \n oder nutzen sie die Tastatur um mit mir zu kommunizieren")
        self.lbl1.place(relx=0.5, rely=0.29, anchor=CENTER)

        global txt1 # chatbox
        txt1 = ScrolledText(txt_frm, borderwidth=3, relief="sunken", height=25,width=60)
        txt1.config(font=("consolas", 12), undo=True, wrap='word')
        txt1.place(relx=0.5, rely=0.48, anchor=CENTER)
        txt1.tag_config('green', foreground='green')
        txt1.tag_config('red', foreground='red')

        global inp1 # Inputbox for Keyboard inputs
        inp1 = Entry(txt_frm, width=77)
        inp1.place(relx=0.5, rely=0.768, anchor=CENTER)
        inp1.focus_set()
コード例 #24
0
class GuiOutput():
    font = ('courier', 16, 'normal')

    def __init__(self, parent=None):
        self.text = ScrolledText(parent)
        self.text.config(font=self.font)
        self.text.pack(side=BOTTOM, fill=BOTH, expand=YES)

    def write(self, text):
        self.text.insert(END, str(text))
        self.text.see(END)
        self.text.update()  # update gui after each line

    def writelines(self, lines):
        for line in lines:
            self.write(line)
コード例 #25
0
ファイル: graphic.py プロジェクト: JarryShaw/TreeViewer
 def intr_cmd(self):
     toplevel = Toplevel(self.master)
     toplevel.title('About PCAP Tree Viewer')
     scrolledtext = ScrolledText(
             toplevel, font=('Courier New', 12),
             width=50, height=20
     )
     scrolledtext.pack()
     try:
         with open('assets/about', 'r') as file_:
             for line in file_:
                 scrolledtext.insert(END, line)
                 scrolledtext.update()
         scrolledtext.config(state=DISABLED)
         toplevel.resizable(width=False, height=False)
     except FileNotFoundError:
         showerror("Something's missing.", 'Unable to fine ABOUT.')
コード例 #26
0
def nayta_tilastot():
    """
    Saa tiedot lataa_tiedosto-funktion kautta ja jos kyseinen funktio palauttaa tietoja, koostaa niistä graafisen esityksen uuteen ikkunaan.
    """
    tiedot = lataa_tiedosto(TIEDOSTO)
    # Tarkistus estää ikkunan näyttämisen, jos tiedostoa ei ole olemassa (eli lataa_tiedosto-funktio ei palauta mitään)
    if tiedot:
        tilastoikkuna = tkinter.Toplevel()
        tilastoikkuna.title("Tilastot")
        tilastoikkuna.geometry("980x250")
        tilastoikkuna.grab_set()

        tekstilaatikko = ScrolledText(tilastoikkuna,
                                      width=130,
                                      height=10,
                                      font=("sans-serif", 10))
        try:
            for pvm, peliminuutit, vuorot, kentankoko, miinat, lopputulos in tiedot:
                minuuttiraja = peliminuutit.index(".")
                kokominuutit = int(peliminuutit[:minuuttiraja])
                peliminuutit = float(peliminuutit)
                sekunnit = round((peliminuutit - kokominuutit) * 60)
                tilastorivi = "{} aloitit pelin, joka kesti {} minuuttia ja {} sekuntia. Kentän koko oli {}, miinoja {}, teit {} siirtoa ennen loppua. Lopputulos: {}\n".format(
                    pvm, kokominuutit, sekunnit, kentankoko, miinat, vuorot,
                    lopputulos)
                tekstilaatikko.insert(tkinter.INSERT, tilastorivi)
        except ValueError:
            tkinter.messagebox.showerror(
                "Virhe",
                "Tiedostosi on vahingoittunut, tilastoja ei voida näyttää.")
        else:
            yhteenveto = tkinter.Label(tilastoikkuna,
                                       text="",
                                       font=("sans-serif", 10),
                                       pady=20)
            pelienmaara = len(tiedot)
            voittoja = laske_voitot(tiedot)
            yhteenveto.config(
                text=
                "Pelattuja pelejä: {}   Voitettuja pelejä: {}   Voittoprosentti: {:.1f}%"
                .format(pelienmaara, voittoja, voittoja / pelienmaara * 100))
            tekstilaatikko.config(state=tkinter.DISABLED)
            yhteenveto.pack()
            tekstilaatikko.pack()
            tilastoikkuna.mainloop()
コード例 #27
0
ファイル: graphic.py プロジェクト: JarryShaw/TreeViewer
 def help_cmd(self):
     toplevel = Toplevel(self.master)
     toplevel.title('PCAP Tree Viewer Help')
     scrolledtext = ScrolledText(
             toplevel, font=('Courier New', 12),
             width=57, height=20
     )
     scrolledtext.pack()
     try:
         with open('assets/manual', 'r') as file_:
             for line in file_:
                 scrolledtext.insert(END, line)
                 scrolledtext.update()
     except FileNotFoundError:
         showerror("Something's missing!", 'Unable to find MANUAL.')
         return
     scrolledtext.config(state=DISABLED)
     toplevel.resizable(width=False, height=False)
コード例 #28
0
ファイル: popup.py プロジェクト: ulaval-rs/spectrominer
    def __init__(self, message: str):
        super(PopUp, self).__init__()
        self.geometry('800x600')

        self.wm_title('Message')

        btn = ttk.Button(self, text='Ok', command=self.destroy)
        btn.pack(anchor='e', side=tkinter.BOTTOM, padx=10, pady=10)

        text_box = ScrolledText(
            self,
            width=360,
            height=230,
            wrap=tkinter.WORD
        )
        text_box.pack(padx=10, pady=10, fill=tkinter.BOTH, expand=True)
        text_box.insert(tkinter.INSERT, message)
        text_box.config(state='disabled')
コード例 #29
0
        class SourceView(ttk.Frame):
            def __init__(self, env, *args, **kwargs):
                super().__init__(*args, **kwargs)
                self._env = env

                self._text = ScrolledText(self, height=10, width=70)
                self._text.config(font=MONOSPACE_FONT, undo=True, wrap="word")
                self._text.grid(row=0, column=0, columnspan=6, sticky="nsew")

                self._run_button = ttk.Button(self,
                                              text="Run",
                                              command=event_wrapper(self.run))
                self._run_button.grid(column=0,
                                      row=1,
                                      columnspan=3,
                                      sticky="ew")
                self._reset_button = ttk.Button(self,
                                                text="Reset",
                                                command=event_wrapper(
                                                    self.reset))
                self._reset_button.grid(column=3,
                                        row=1,
                                        columnspan=3,
                                        sticky="ew")

            @property
            def text(self):
                return self._text.get("1.0", "end-1c")

            def run(self):
                try:
                    self._env.exec(self.text)
                except Exception as e:
                    messagebox.showwarning(type(e).__name__, e.args[0])
                self.event_generate("<<SOURCE.DONE>>")

            def reset(self):
                self._text.delete("1.0", tk.END)
                self._env.reset()
                self.event_generate("<<SOURCE.RESET>>")

            def populate(self, src):
                self._text.insert(tk.END, src)
                self.run()
コード例 #30
0
ファイル: transbox.py プロジェクト: MemoryD/MemoryTools
class TransBox(BaseBox):
    def __init__(self, title="翻译结果", copy_trans=None):
        buttons = [('重新翻译', self.retrans), ('复制', self.copy)]
        super(TransBox, self).__init__(buttons, title)
        self.copy_trans = copy_trans

    def set_text(self, textbox, text):
        textbox.delete("1.0", END)
        textbox.insert(END, text)

    def retrans(self):
        """
        根据用户的更改重新进行翻译
        """
        sentence = self.src_text.get("1.0", END)
        sentence = self.copy_trans.remove_newline(sentence)

        self.set_text(self.src_text, sentence)
        self.set_text(self.textbox, "翻译中,请稍候...")

        text = self.copy_trans.trans_text(sentence)
        self.set_text(self.textbox, text)

    def show(self, src: str, dest: str):
        h1 = min(10, max(5, get_text_line(src) + 1))
        h2 = min(10, max(5, get_text_line(dest) + 1))

        self.src_text = ScrolledText(self,
                                     height=h1,
                                     background='#ffffff',
                                     font=("微软雅黑", 11))
        self.textbox = ScrolledText(self,
                                    height=h2,
                                    background='#ffffff',
                                    font=("微软雅黑", 11))

        self.src_text.insert(END, str(src))
        self.src_text.config()
        self.textbox.insert(END, str(dest))

        self.src_text.pack(side='top', padx=10, pady=10)
        self.textbox.pack(side='top', padx=10, pady=10)

        self.start()
コード例 #31
0
    def editContextGui(self):
        def cancel():
            self.c.execute("SELECT context FROM contexts WHERE id=?",
                           (self.context_id, ))
            r = self.c.fetchone()
            if len(r) > 0 or r[0] is None:
                self.c.execute("DELETE FROM contexts WHERE id=?",
                               (self.word_id, ))
                self.c.execute(
                    "SELECT * FROM contexts WHERE word_id=? ORDER BY id LIMIT 1",
                    (self.word_id, ))
                r = self.c.fetchone()
                if r is not None:
                    self.changeText(self.wvar["ViewContext"], r[2])
                    self.context_id = r[0]
                    self.c.execute(
                        "SELECT count(*) FROM contexts WHERE word_id=?",
                        (self.word_id, ))
                    pageVar.set("1 / " + str(self.c.fetchone()[0]))
                else:
                    self.changeText(self.wvar["ViewContext"], "")
                    self.context_id = ()
                    pageVar.set("1 / 0")
            self.switchLayout(self.layouts, "ViewWord")

        layout = tk.Frame(self.root)
        self.layouts["EditContext"] = layout
        tk.Button(layout, text="Submit",
                  command=self.editContext).grid(row=0, column=0)
        tk.Button(layout, text="Cancel", command=cancel).grid(row=0, column=1)
        tk.Label(layout, textvariable=self.wvar["ViewWord"]).grid(row=1,
                                                                  column=0)
        tk.Label(layout, textvariable=self.wvar["ViewSpeech"]).grid(row=1,
                                                                    column=1)
        translationText = ScrolledText(layout, height=5, width=80)
        translationText.grid(row=2, column=0, columnspan=2)
        translationText.config(state=tk.DISABLED)
        self.wvar["EditContextTranslationText"] = translationText
        self.wvar["EditContext"] = ScrolledText(layout, height=5, width=80)
        self.wvar["EditContext"].grid(row=2, column=0, columnspan=2)
        self.wvar["EditSource"] = ScrolledText(layout, height=5, width=80)
        self.wvar["EditSource"].grid(row=3, column=0, columnspan=2)
コード例 #32
0
class GuiOutput:
    font = ('courier', 9, 'normal')              # in class for all, self for one
    def __init__(self, parent=None):
        self.text = None
        if parent: self.popupnow(parent)         # pop up now or on first write

    def popupnow(self, parent=None):             # in parent now, Toplevel later
        if self.text: return
        self.text = ScrolledText(parent or Toplevel())
        self.text.config(font=self.font)
        self.text.pack()

    def write(self, text):
        self.popupnow()
        self.text.insert(END, str(text))
        self.text.see(END)
        self.text.update()                       # update gui after each line

    def writelines(self, lines):                 # lines already have '\n'
        for line in lines: self.write(line)      # or map(self.write, lines)
コード例 #33
0
def createControlPanel():
	global winButton
	global loseButton
	global selectedLabel
	global editArea
	
	top = Toplevel()
	top.title("Control Panel")
	top.wm_attributes("-topmost", 1)
	#Main name settings
	selectedLabel = Label(top, textvariable=textDisplay, width=20, font=("Arial", 30)).pack()
	#Reset buttons settings
	hardResetButton = Button(top, text="Reset All", width=20, height=5, padx=20, pady=20, command=hardReset)
	hardResetButton.pack(side=LEFT)
	softResetButton = Button(top, text="Reset Partial", width=20, height=5, padx=20, pady=20, command=softReset)
	softResetButton.pack(side=LEFT)
	#Win button settings
	winButton = Button(top, text="Win", width=20, height=5, padx=20, pady=20, command=winFunc)
	winButton.pack(side=LEFT)
	#Lose button settings
	loseButton = Button(top, text="Lose", width=20, height=5, padx=20, pady=20, command=loseFunc)
	loseButton.pack(side=LEFT)
	#Toggle Display Border
	#Lose button settings
	borderButton = Button(top, text="Toggle Border", width=20, height=5, padx=20, pady=20, command=toggleBorder)
	borderButton.pack(side=LEFT)
	#Quit button settings
	quitButton = Button(top, text="Quit", width=20, height=5, padx=20, pady=20, command=quit)
	quitButton.pack(side=LEFT)
	#Scrollable Text Field
	editArea = ScrolledText(
		master = top,
		wrap = WORD,
		width = 10,
		height = 5
	)
	editArea.config(state='disabled')
	#editArea.configure(state=DISABLED)
	editArea.pack(padx=10,pady=10,fill=BOTH,expand=False,side=RIGHT)
	#Reset win/lose buttons to 'disable'
	resetButtons()
コード例 #34
0
    def __init__(self):
        top = tk.Tk()
        top.title = 'Format Orbitrap parameters'

        a = ScrolledText(top)
        a.config(width=50, height=20, undo=10, wrap='none')
        a.pack(pady=10)

        b = tk.Button(
            top,
            text='Click to format Orbitrap parameters',
            command=lambda: self.button_extract(a.get("1.0", tk.END)),
        )
        b.pack(pady=10)

        c = ScrolledText(top)
        c.config(width=50, height=10, undo=10, wrap='none')
        c.insert("1.0", 'Result:\n')
        c.pack(pady=10)

        top.mainloop()
コード例 #35
0
class MessageTester:
    def __init__(self, root):
        root.title("Message tester")
        Label(root, text="Enter message event below", bg="light green").pack()
        self.event_field = ScrolledText(root, width=180, height=10)
        self.event_field.pack()

        Label(root, text="Enter test case below", bg="light green").pack()
        self.test_case_field = ScrolledText(root, width=180, height=20)
        self.test_case_field.pack()

        Label(root, text="Test result:", bg="light green").pack()

        self.result_field = ScrolledText(root, width=180, height=10)
        self.result_field.pack()
        self.result_field.config(state=DISABLED)
        self.button = Button(root, text="Evaluate", fg="red",
                             command=self._clicked)
        self.button.pack()

        self.event_field.delete('1.0', END)
        self.event_field.insert('insert', EXAMPLE_EVENT)
        self.test_case_field.delete('1.0', END)
        self.test_case_field.insert('insert', EXAMPLE_TEST_CASE)

    def _clicked(self):
        event = self.event_field.get('1.0', END)
        test_case = self.test_case_field.get('1.0', END)

        evaluation = skill_tester.EvaluationRule(ast.literal_eval(test_case))
        evaluation.evaluate(ast.literal_eval(event))
        self.result_field.config(state=NORMAL)
        self.result_field.delete('1.0', END)
        self.result_field.insert('insert', evaluation.rule)
        self.result_field.config(state=DISABLED)
コード例 #36
0
ファイル: guiStreams.py プロジェクト: death-finger/Scripts
class GuiOutput:
    font = ('courier', 12, 'normal')
    def __init__(self, parent=None):
        self.text = None
        if parent:
            self.popupnow(parent)

    def popupnow(self, parent=None):
        if self.text: return
        self.text = ScrolledText(parent or Toplevel())
        self.text.config(font=self.font)
        self.text.pack()

    def write(self, text):
        self.popupnow()
        self.text.insert(END, str(text))
        self.text.see(END)
        self.text.update()

    def writelines(self, lines):
        for line in lines:
            self.write(line)
コード例 #37
0
 def __init__(self, appname, helptext, iconfile=None, showsource=lambda:0):
     PopupWindow.__init__(self, appname, 'Help', iconfile)
     from tkinter.scrolledtext import ScrolledText    # a nonmodal dialog
     bar  = Frame(self)                               # pack first=clip last
     bar.pack(side=BOTTOM, fill=X)
     code = Button(bar, bg='beige', text="Source", command=showsource)
     quit = Button(bar, bg='beige', text="Cancel", command=self.destroy)
     code.pack(pady=1, side=LEFT)
     quit.pack(pady=1, side=LEFT)
     text = ScrolledText(self)                   # add Text + scrollbar
     text.config(font=self.myfont)
     text.config(width=self.mywidth)             # too big for showinfo
     text.config(bg='steelblue', fg='white')     # erase on btn or return
     text.insert('0.0', helptext)
     text.pack(expand=YES, fill=BOTH)
     self.bind("<Return>", (lambda event: self.destroy()))
コード例 #38
0
ファイル: popuputil.py プロジェクト: minghu6/PyMail
    def __init__(self,appname,helptext,iconfile=None,
                 showsource=lambda:0):

        PopupWindow.__init__(self,appname,'Help',iconfile)
        from tkinter.scrolledtext import ScrolledText
        bar=Frame(self)
        bar.pack(side=BOTTOM,fill=X)
        code=Button(bar,bg='beige',text='Source',command=showsource)
        quit=Button(bar,bg='beige',text='Cancel',command=self.destroy)
        code.pack(pady=1,side=LEFT)
        quit.pack(pady=1,side=LEFT)

        text=ScrolledText(self)
        text.config(font=self.myfont)
        text.config(width=self.mywidth)
        text.config(bg='steelblue',fg='white')
        text.insert('0.0',helptext)
        text.pack(expand=YES,fill=BOTH)
        self.bind('<Return>',(lambda event:self.destroy()))
コード例 #39
0
ファイル: client.py プロジェクト: Scratso/XeIRC
    wrap   = 'word',  # wrap text at full words only
    width  = 25,      # characters
    height = 10,      # text lines
    bg = 'black',        # background color of edit area
    fg = '#0B62ED',
    insertbackground = "#E80860",
    highlightbackground="#888478",
    selectbackground="#E80860",
    selectforeground="#0B62ED"
)
# the padx/pady space will form a frame
chatLog.pack(fill='both', expand="yes")
chat = tk.Text(frame, padx=4, height=1, bg="black", fg="#E80860", insertbackground="#0B62ED",
               selectbackground="#0B62ED", selectforeground="#E80860", highlightthickness=0)
chat.pack(fill='x', side="bottom")
chatLog.config(state="disabled")
def addchat(text):
    chatLog.config(state="normal")
    chatLog.insert("insert", text + "\n")
    chatLog.see(tk.END)
    chatLog.config(state="disabled")
def enterPressed(event):
    #addchat(chat.get("1.0",'end-1c'))
    sendt = chat.get("1.0",'end-2c')
    try:
        pars = sendt.split(" ")
    except:
        pars = [sendt]
    try:
        channel = str(channels.get(channels.curselection()[0]))
    except:
コード例 #40
0
class Application:


    def __init__(self, parent):
        self.parent = parent
        self.frames()
        self.f_saved = True       #Sampled data saved
        root.protocol("WM_DELETE_WINDOW", self.on_closing)


    def on_closing(self):
        if (self.f_saved==False):
            if messagebox.askokcancel("Quit", "Sampled data not saved. Do you wanto to quit?"):
                root.destroy()
        else:
            root.destroy()


    def frames(self):
        frame1 = Tk.Frame(root, bd=5, relief='raised', borderwidth=1)
        frame2 = Tk.Frame(root, bd=5, relief='raised')

        note = ttk.Notebook(frame2)
        self.tab1 = ttk.Frame(note)
        self.tab2 = ttk.Frame(note)

        note.add(self.tab1, text = "Frquency")
        note.add(self.tab2, text = "Time")

        # Positioning
        frame1.pack(side='left', fill='both', padx=5, pady=5)
        frame2.pack(side='right', fill='both', expand='true')

        boton_open = Tk.Button(frame1, text ="Open file", command=self.open_file)
        boton_save = Tk.Button(frame1, text ="Save to file", command=self.save_file)
        boton_scan = Tk.Button(frame1, text="Scan serial ports", command=self.scan_ports)
        boton_read = Tk.Button(frame1, text="Read serial data", command=self.read_serial)

        label1 = Tk.Label(frame1, text="Select Serial Port:")
        self.sel_puerto = ttk.Combobox(frame1, textvariable='', state="readonly")
        portnames = scan_serial()
        self.sel_puerto['values'] = portnames        
        if (portnames != []):
            self.sel_puerto.current(0)

        self.text_message = ScrolledText(frame1, height=10, width=20)

        self.window_var = Tk.IntVar()
        self.window_var.set(1)        #Option rectangular window 
        radio_button1 = Tk.Radiobutton(frame1, text="Rectangular Window",
                                       variable=self.window_var, value=1, command=self.win_sel)
        radio_button2 = Tk.Radiobutton(frame1, text="Hann Window",
                                       variable=self.window_var, value=2, command=self.win_sel)
        radio_button3 = Tk.Radiobutton(frame1, text="Flattop Window",
                                       variable=self.window_var, value=3, command=self.win_sel)
        # Grid
        boton_open.grid(row=1, column=0, padx=5, pady=5)
        boton_save.grid(row=2, column=0, padx=5, pady=5)
        boton_scan.grid(row=3, column=0, padx=5, pady=5)
        label1.grid(row=4, column=0, padx=5, pady=5)
        self.sel_puerto.grid(row=5, column=0, padx=5, pady=5)
        boton_read.grid(row=6, column=0, padx=5, pady=5)
        self.text_message.grid(row=7, column=0, padx=5, pady=5)
        radio_button1.grid(row=8, column=0, sticky="W")
        radio_button2.grid(row=9, column=0, sticky="W")
        radio_button3.grid(row=10, column=0, sticky="W")

        #note.grid(row = 0, column=0)
        note.pack(side='top', fill='both', padx=5, pady=5)

        #Figure 1
        fig1 = Figure(figsize=(10,9))
        fig1.suptitle('Sampled signal - Acceleration')
        ax_11 = fig1.add_subplot(3,1,1)
        #ax_11.hold(False)
        ax_11.set_title("Channel X")
        ax_11.set_ylabel('g')
        ax_11.grid()                       #Shows grid.

        ax_12 = fig1.add_subplot(3,1,2)
        #ax_12.hold(False)
        ax_12.set_title("Channel Y")
        #ax_12.set_xlabel('ms')
        ax_12.set_ylabel('g')
        ax_12.grid()                       #Shows grid.

        ax_12 = fig1.add_subplot(3,1,3)
        #ax_12.hold(False)
        ax_12.set_title("Channel Z")
        ax_12.set_xlabel('ms')
        ax_12.set_ylabel('g')
        ax_12.grid()                       #Shows grid.

        #Figure 2
        fig2 = Figure(figsize=(10,9))
        fig2.suptitle('FFT spectrum')

        ax_21 = fig2.add_subplot(3,1,1)
        #ax_21.hold(False)
        ax_21.set_title("Channel X")
        ax_21.set_ylabel('g')
        ax_21.set_xlim(xmax=max_freq)
        ax_21.grid()            

        ax_22 = fig2.add_subplot(3,1,2)
        #ax_22.hold(False)
        ax_22.set_title("Channel Y")
        #ax_22.set_xlabel('Hz')
        ax_22.set_xlim(xmax=max_freq)
        ax_22.set_ylabel('g')
        ax_22.grid()

        ax_23 = fig2.add_subplot(3,1,3)
        #ax_23.hold(False)
        ax_23.set_title("Channel Z")
        ax_23.set_xlabel('Hz')
        #ax_23.set_xlim(xmax=max_freq)
        ax_23.set_xlim(xmax=max_freq_z)
        ax_23.set_ylabel('g')
        ax_23.grid()            

        # Canvas
        self.canvas2 = FigureCanvasTkAgg(fig1, master=self.tab2)
        self.canvas2.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        self.toolbar2 = NavigationToolbar2TkAgg(self.canvas2, self.tab2)
        self.toolbar2.update()
        self.canvas2._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        self.canvas1 = FigureCanvasTkAgg(fig2, master=self.tab1)
        self.canvas1.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

        self.toolbar1 = NavigationToolbar2TkAgg(self.canvas1, self.tab1)
        self.toolbar1.update()
        self.canvas1._tkcanvas.pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)


    def read_serial(self):
        puerto = self.sel_puerto.get()
        print(puerto)
        message_string = "Port: {0} \n".format(puerto)
        self.show_message(self.text_message, message_string)

        estado_serial = False
        try:
            serial_avr = serial.Serial(port=puerto, baudrate=500000,
                           bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE,
                           stopbits=serial.STOPBITS_ONE, timeout=0)

            time.sleep(2)            # waiting the initialization...
            print("Initializing")
            message_string = "Initializing... \n"
            self.show_message(self.text_message, message_string)
    
            if (serial_avr.isOpen() == True):
                estado_serial = True
            else:
                estado_serial = False
        except (serial.SerialException, ValueError) as ex:
            #print "Can´t open serial port: " + str(ex)
            messagebox.showerror( "Result", "Can't open serial port: " + str(ex))

        if (estado_serial == True):
            global g_canal_1, g_canal_2, g_canal_3, datos_a_leer
            canal_1 = []
            canal_2 = []
            canal_3 = []
            buffer = []
            paquete = []
            valores = []
            serial_avr.flushInput()
            serial_avr.flushOutput()

            valores_decod = []

            conta_datos_rx = 0;         #Received samples counter.

            print("Sending INI")
            message_string = "Sending INI \n"
            self.show_message(self.text_message, message_string)
            
            serial_avr.write(b'INI')         #Start data sampling command.
            #serial_avr.write(chr(0x22))    #CRC 'INI'. Not used.
            serial_avr.write(b"\x7E")     #End of packet.

            global t_timeout
            timeout_state = False
            t0 = time.time()       #Start loop time stamp.
            while ((conta_datos_rx < datos_a_leer) and (timeout_state == False)):
                if serial_avr.inWaiting():
                    lectura = serial_avr.read(serial_avr.inWaiting())
                    buffer += lectura
                    valores = []
                if len(buffer) > 15:
                    try:
                        i = buffer.index(0x7E)
                    except (ValueError):
                        i = -1
                    #print("Buffer: {0}".format(buffer))
                    if i >= 0:
                        paquete = buffer[:i]
                        buffer =  buffer[i+1:]
                        #print("Paquete: {0}".format(paquete))
                        valores=[i for i in paquete]
                        paquete = ''

                        x = 0
                        while x < len(valores):
                            if valores[x] == 0x7D:
                                valores_decod.append(valores[x+1] ^ 0x20)
                                x = x + 1
                            else:    
                                valores_decod.append(valores[x])
                            x = x + 1

                        canal1 = (valores_decod[0] * 256) + valores_decod[1]
                        canal2 = (valores_decod[2] * 256) + valores_decod[3]
                        canal3 = (valores_decod[4] * 256) + valores_decod[5]

                        canal_1.append(canal1)
                        canal_2.append(canal2)
                        canal_3.append(canal3)

                        #print("Canal 1: %s    Canal2: %s  " % (canal1, canal2))

                        valores = []
                        valores_decod = []

                        conta_datos_rx += 1 ;
                        #print("conta_datos_rx =  %s" %conta_datos_rx)

                #Check if t_timeout seconds have elapsed since time stamp t0
                if ((time.time() - t0) > t_timeout):
                    timeout_state = True
                    #print("Serial port timeout")

            if (timeout_state == False):
                print("Sending PAR")
                self.text_message.config(state=Tk.NORMAL)        #Enable to modify
                self.text_message.insert(Tk.END, "Sending PAR \n")
                self.text_message.config(state=Tk.DISABLED)      #Disable - Read only
                root.update_idletasks()        #Needed to make message visible
            
                serial_avr.write(b'PAR')          #Stop data sampling.
                serial_avr.write(b"\x7E")         #End of packet.

                serial_avr.close()                #Close serial port.

                print("Amount of samples channel 1: %s" %len(canal_1))
                print("Amount of samples channel 2: %s" %len(canal_2))
                print("Amount of samples channel 3: %s" %len(canal_3))
                message_string = "Amount of samples channel 1: {0} \n".format(len(canal_1))
                message_string += "Amount of samples channel 2: {0} \n".format(len(canal_2))
                message_string += "Amount of samples channel 3: {0} \n".format(len(canal_3))
                self.show_message(self.text_message, message_string)
            
                #Keep a copy of the original values
                g_canal_1 = canal_1[:]            #Copy list by value not by reference
                g_canal_2 = canal_2[:]
                g_canal_3 = canal_3[:]

                self.f_saved = False                #Sampled data not saved

                self.window_var.set(1)        #Option rectangular window
                self.plot(self.tab1, self.tab2, canal_1, canal_2, canal_3, win_var=1)
            else:
                serial_avr.write(b'PAR')          #Stop data sampling.
                serial_avr.write(b"\x7E")         #End of packet.
                serial_avr.close()                #Close serial port.
                print("Serial port timeout")
                message_string = ("Serial port timeout \n")
                self.show_message(self.text_message, message_string)


    def show_message(self, text_message, message_string):
        """Shows messages on a scrollable textbox"""
        text_message.config(state=Tk.NORMAL)        #Enable to modify
        text_message.insert(Tk.END, message_string)
        text_message.config(state=Tk.DISABLED)      #Disable - Read only
        text_message.see("end")        #Show the "end" of text
        root.update_idletasks()        #Needed to make message visible
        

    def scan_ports(self):
        portnames = []
        portnames = scan_serial()
        self.sel_puerto['values'] = portnames
        if (portnames != []):
            self.sel_puerto.current(0)


    def plot(self, tab1, tab2, canal_1, canal_2, canal_3, win_var=1):
        num_datos = len(canal_1)
        X = range(0, num_datos, 1)

        # Scale the signal in g's
        for indice in X:
            canal_1[indice] *= g_scale
            canal_2[indice] *= g_scale
            canal_3[indice] *= g_scale

        # Calculates medium value for each channel.
        vdc_canal_1 = 0
        vdc_canal_2 = 0
        vdc_canal_3 = 0
        for indice in X:
            vdc_canal_1 += canal_1[indice]
            vdc_canal_2 += canal_2[indice]
            vdc_canal_3 += canal_3[indice]
        vdc_canal_1 = vdc_canal_1 / num_datos
        vdc_canal_2 = vdc_canal_2 / num_datos
        vdc_canal_3 = vdc_canal_3 / num_datos
        #print("Vdc Channel 1: {0}, Vdc Channel 2: {1}".format(vdc_canal_1, vdc_canal_2))

        # Substract DC offset
        for indice in X:
            canal_1[indice] -= vdc_canal_1
            canal_2[indice] -= vdc_canal_2
            canal_3[indice] -= vdc_canal_3

        #----------------- Plotting ----------
        X1 = np.linspace(0, num_datos/5, num=num_datos)     # X axis, 5000 sps, 1/5 ms.

        # Figure 1. Sampled signals.
        #Channel X
        ax_11, ax_12, ax_13 = self.canvas2.figure.get_axes()
        ax_11.clear()
        ax_11.plot(X1,canal_1)
        ax_11.set_title("Channel X")
        ax_11.set_ylabel('g')
        ax_11.grid()                       #Shows grid.
        
        #Channel Y
        ax_12.clear()
        ax_12.plot(X1,canal_2)
        ax_12.set_title("Channel Y")
        #ax_12.set_xlabel('ms')
        ax_12.set_ylabel('g')
        ax_12.grid()                       #Shows grid.

        #Channel Z
        ax_13.clear()
        ax_13.plot(X1,canal_3)
        ax_13.set_title("Channel Z")
        ax_13.set_xlabel('ms')
        ax_13.set_ylabel('g')
        ax_13.grid()                       #Shows grid.

        # Figure 2. FFT from signals.
        #Channel X
        canal_fft = []
        canal_fft = canal_1

        N = len(canal_fft)         # length of the signal

        #Window function
        if(win_var == 2):
            w = signal.hann(N, sym=False)      #Hann (Hanning) window
        elif(win_var == 3):
            w = signal.flattop(N, sym=False)   #Flattop window
        else:
            w = 1                              #Rectangular window
        
        T = 1.0 / sample_rate
        y = canal_fft
        yf = fftpack.fft(y*w)*(2/N)
        yf = yf[:int(N/2)]
        xf = np.linspace(0.0, 1.0/(2.0*T), N/2)

        ax_21, ax_22, ax_23 = self.canvas1.figure.get_axes()
        ax_21.clear()
        #ax_21.plot(xf, 2.0/N * np.abs(yf[:N/2]))
        ax_21.plot(xf, np.abs(yf))
        ax_21.grid()
        ax_21.set_title("Channel X")
        ax_21.set_ylabel('g')
        ax_21.set_xlim(xmax=max_freq)

        #Channel Y
        canal_fft = []
        canal_fft = canal_2

        N = len(canal_fft)              # length of the signal
        T = 1.0 / sample_rate
        y = canal_fft
        yf = fftpack.fft(y*w)*(2/N)
        yf = yf[:int(N/2)]
        xf = np.linspace(0.0, 1.0/(2.0*T), N/2)

        ax_22.clear()
        #ax_22.plot(xf, 2.0/N * np.abs(yf[:N/2]))
        ax_22.plot(xf, np.abs(yf))
        ax_22.grid()
        ax_22.set_title("Channel Y")
        #ax_22.set_xlabel('Hz')
        ax_22.set_xlim(xmax=max_freq)
        ax_22.set_ylabel('g')

        #Channel Z
        canal_fft = []
        canal_fft = canal_3

        N = len(canal_fft)              # length of the signal
        T = 1.0 / sample_rate
        y = canal_fft
        yf = fftpack.fft(y*w)*(2/N)
        yf = yf[:int(N/2)]
        xf = np.linspace(0.0, 1.0/(2.0*T), N/2)

        ax_23.clear()
        #ax_23.plot(xf, 2.0/N * np.abs(yf[:N/2]))
        ax_23.plot(xf, np.abs(yf))
        ax_23.grid()
        ax_23.set_title("Channel Z")
        ax_23.set_xlabel('Hz')
        #ax_23.set_xlim(xmax=max_freq)
        ax_23.set_xlim(xmax=max_freq_z)
        ax_23.set_ylabel('g')

        self.canvas1.draw()
        self.canvas2.draw()


    def win_sel(self):
        """Window selection. Every time a window is selected,
        the FFT spectrum is calculated, applying the selected window function"""
        global g_canal_1, g_canal_2, g_canal_3
        canal_1 = g_canal_1[:]            #Copy list by value not by reference
        canal_2 = g_canal_2[:]
        canal_3 = g_canal_3[:]            
        win_var = self.window_var.get()
        if(len(canal_1) != 0):            #Apply only if data available
            self.plot(self.tab1, self.tab2, canal_1, canal_2, canal_3, win_var)


    def open_file(self):
        """Opens dialog to select a file, reads data from file and plots the data"""
        ftypes = [('Text files', '*.txt'), ('All files', '*')]
        dlg = filedialog.Open(root, filetypes = ftypes)
        fl = dlg.show()
        if fl != '':
            # Open file for reading
            arch = open(fl, "r")
            datos_arch = arch.read()
            # Searches for every channel, delimited by L1, L2 and L3 tags.
            canal_1 = extraer_int_tag(datos_arch, 'L1')
            canal_2 = extraer_int_tag(datos_arch, 'L2')
            canal_3 = extraer_int_tag(datos_arch, 'L3')

            print("Amount of samples in channel 1: %s" %len(canal_1))
            print("Amount of samples on channel 2: %s" %len(canal_2))
            print("Amount of samples on channel 3: %s" %len(canal_3))
            message_string = "Amount of samples channel 1: {0} \n".format(len(canal_1))
            message_string += "Amount of samples channel 2: {0} \n".format(len(canal_2))
            message_string += "Amount of samples channel 3: {0} \n".format(len(canal_3))
            self.show_message(self.text_message, message_string)

            global g_canal_1, g_canal_2, g_canal_3
            #Keep a copy of the original values
            g_canal_1 = canal_1[:]            #Copy list by value not by reference
            g_canal_2 = canal_2[:]
            g_canal_3 = canal_3[:]

            self.window_var.set(1)        #Option rectangular window
            self.plot(self.tab1, self.tab2, canal_1, canal_2, canal_3, win_var=1)


    def save_file(self):
        ftypes = [('Text files', '*.txt'), ('All files', '*')]
        dlg = filedialog.SaveAs(root, filetypes = ftypes)
        fl = dlg.show()
        if fl != '':
            global g_canal_1, g_canal_2, g_canal_3
            if (len(g_canal_1) > 0):
                grabar(g_canal_1, g_canal_2, g_canal_3, fl)
                self.f_saved = True               #Sampled data saved
            else:
                print("No samled data to save")
                message_string = "No samled data to save\n"
                self.show_message(self.text_message, message_string)
コード例 #41
0
class ChatGUI(Frame):
    
    def __init__(self, parent, conn, title):
        #Frame.__init__(self, parent, background="grey")   
         
        self.parent = parent
        self.conn = conn
        self.title = title
        
        self.centerWindow()
        self.initUI()
    
    def initUI(self):
      
        self.lineCounter = 0
      
        # create a custom font
        self.customFontHeader = font.Font(family="Calibri", slant = "italic") #family="Helvetica", weight="bold", slant="italic")
        self.customFontMessage = font.Font(family="Calibri")
        
        self.parent.title(self.title) 
        
        frame = Frame(self.parent)
        frame.pack(fill=BOTH, expand=1, side=LEFT)
        
        self.box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
        self.box.insert(END, 'Welcome to Python Chat!')
        self.box.config(state=DISABLED)
        self.box.pack(expand="yes", fill=BOTH, side=TOP)
        
        self.textarea = Text(frame, width=30, height=5)
        #self.textarea.insert(END, "")
        self.textarea.bind("<KeyRelease-Return>", self.gettext) #Se metto on press, rimane una newline in piu
        self.textarea.pack(expand="yes", fill=BOTH, side=TOP)

        
        okButton = Button(frame, text="Panic Button", activebackground="red", command=self.sendFile) 
        okButton.pack(expand="no", fill=BOTH, side=TOP)
        
        self.usersFrame = Frame(self.parent)
        self.usersFrame.pack(fill=BOTH, expand=1, side=RIGHT)
        
        self.userListbox = Listbox(self.usersFrame, width=3)
        self.userListbox.bind("<Double-Button-1>", self.privateChat)
        self.userListbox.pack(fill=BOTH, expand=1)
            
        self.updateUsersFrame()
        
    def centerWindow(self):
      
        w = 600
        h = 475

        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))
     
    def gettext(self, e): #e sta per event, questo e' un listener
        text = self.textarea.get("1.0", END + " - 2c") # 1.0: row:columa -  END-2c rimuove l'ultimo carattere, una newline \r\n
        self.textarea.delete("0.0", END) #NON VA: il problema e' che viene inviato il carattere di newline ma non incluso nell'area a causa della bind mi sa. Devo escluderlo io
        self.sendToServer(text)
        
    def printConversation(self, message):
        self.box.config(state=NORMAL)
        self.box.insert(END,"\n" + message)
        self.lineCounter = self.lineCounter + 2
        
        #m = re.match("\[.*\] From .*\n", self.box.get("0.0", END))
        m = re.search("\[.*\].*:", message, re.MULTILINE)
        
        
        if m is not None:
            #print("MATCH")
            #print(m.group(0))
            #print(str(m.start(0)) + "_" + str(m.end(0)))
            #print("COUNTER")
            #print(str(self.lineCounter) + "." + str(m.start(0)+1) + "___" + str(self.lineCounter) + "." + str(m.end(0)))
            self.box.tag_add("header", str(self.lineCounter) + "." + str(m.start(0)), str(self.lineCounter) + "." + str(m.end(0)))
            self.box.tag_config("header", font=self.customFontHeader, foreground = "blue")
        
        
        self.box.config(state=DISABLED)
        #self.box.yview_scroll(10000,"units")
        self.box.see(END)

    
    def sendToServer(self, messageToSend):
        self.conn.send(messageToSend.encode(encoding='utf_8', errors='strict'))
    
    def sendFile(self):
        #aprire una dialog di quelle predefinite (Sfoglia...)
        #capire come fare la send di un file sul socket...
        pass
    def updateUsersFrame(self):
        
        global connectedClients
    
        self.userListbox.delete(0, END)
                    
        self.userListbox.insert(END, "Connected users")
        for item in connectedClients:
            self.userListbox.insert(END, item)
        #self.userListbox.update()
        #self.usersFrame.update()
    def privateChat(self, e):
        global conversationBoxList
        userselected = self.userListbox.selection_get()
        if not userselected == "Connected users":
            print("EVVAI CHAT PRIVATA con "+userselected)
            
            newWindow = Toplevel(self.parent)
            newWindow.title("Python Chat with "+userselected)
            newWindow.minsize(400, 475)
            newWindow.focus()
            
            def disconnectPM():
                del conversationBoxList[userselected]
                newWindow.destroy()
            newWindow.protocol('WM_DELETE_WINDOW', disconnectPM)
            
            #label = Label(newWindow, text="PROVA PROVA")
            #label.pack(side="top", fill="both", padx=10, pady=10)
            frame = Frame(newWindow)
            frame.pack(fill=BOTH, expand=1, side=LEFT)
            
            box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
            box.config(state=DISABLED)
            box.pack(expand="yes", fill=BOTH, side=TOP)
            
            textarea = Text(frame, width=30, height=5)
            textarea.bind("<KeyRelease-Return>", lambda event : self.getprivatetext(event, textarea, userselected)) 
            textarea.pack(expand="yes", fill=BOTH, side=TOP)
            
            #aggiungo alla mappa globale il box di conversazione
            conversationBoxList[userselected] = box
            

    def receivePrivateChat(self, connectingUser):
        global conversationBoxList
        print("CHAT PRIVATA in arrivo con "+connectingUser)
            
        newWindow = Toplevel(self.parent)
        newWindow.title("Python Chat requested by "+connectingUser)
        newWindow.minsize(400, 475)
        newWindow.focus()
        
        def disconnectPM():
            del conversationBoxList[connectingUser]
            newWindow.destroy()
        newWindow.protocol('WM_DELETE_WINDOW', disconnectPM)
        
        #label = Label(newWindow, text="PROVA PROVA")
        #label.pack(side="top", fill="both", padx=10, pady=10)
        frame = Frame(newWindow)
        frame.pack(fill=BOTH, expand=1, side=LEFT)
        
        box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
        box.config(state=DISABLED)
        box.pack(expand="yes", fill=BOTH, side=TOP)
        
        textarea = Text(frame, width=30, height=5)
        textarea.bind("<KeyRelease-Return>", lambda event : self.getprivatetext(event, textarea, connectingUser)) 
        textarea.pack(expand="yes", fill=BOTH, side=TOP)
        
        #aggiungo alla mappa globale il box di conversazione
        conversationBoxList[connectingUser] = box

    def getprivatetext(self, e, textarea, nickname):
            text = textarea.get("1.0", END + " - 2c") 
            textarea.delete("0.0", END) 
            self.sendToServer("##" + nickname + "##" + text)
    
    def setprivatetext(self, nickname, message, isLocalMessage):
        
            #isLocalMessage identifica un messaggio che mando io e che devo ri-ricevere nella mia finestra
            if isLocalMessage:
                for i in conversationBoxList.keys():
                    box = conversationBoxList[i]
                    box.config(state=NORMAL)
                    box.insert(END,"\n" + message)
                    box.config(state=DISABLED)
                    box.see(END)            
            else:
                conversationbox = conversationBoxList[nickname]
                
                conversationbox.config(state=NORMAL)
                conversationbox.insert(END,"\n" + message)
                #self.lineCounter = self.lineCounter + 2
                
                #m = re.match("\[.*\] From .*\n", self.box.get("0.0", END))
                #m = re.search("\[.*\].*:", message, re.MULTILINE)
                
                '''
                if m is not None:
                    #print("MATCH")
                    #print(m.group(0))
                    #print(str(m.start(0)) + "_" + str(m.end(0)))
                    #print("COUNTER")
                    #print(str(self.lineCounter) + "." + str(m.start(0)+1) + "___" + str(self.lineCounter) + "." + str(m.end(0)))
                    self.box.tag_add("header", str(self.lineCounter) + "." + str(m.start(0)), str(self.lineCounter) + "." + str(m.end(0)))
                    self.box.tag_config("header", font=self.customFontHeader, foreground = "blue")
                '''
                
                conversationbox.config(state=DISABLED)
                #self.box.yview_scroll(10000,"units")
                conversationbox.see(END)       
コード例 #42
0
class ChatGUI(Frame):
    
    def __init__(self, parent, conn):
        #Frame.__init__(self, parent, background="grey")   
         
        self.parent = parent
        self.conn = conn
        
        self.centerWindow()
        self.initUI()
    
    def initUI(self):
      
        self.lineCounter = 0
      
        # create a custom font
        self.customFontHeader = font.Font(family="Calibri", slant = "italic") #family="Helvetica", weight="bold", slant="italic")
        self.customFontMessage = font.Font(family="Calibri")
        
        self.parent.title("Python Chat") 
        
        frame = Frame(self.parent)
        frame.pack(fill=BOTH, expand=1, side=LEFT)
        
        self.box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
        self.box.insert(END, 'Welcome to Python Chat!')
        self.box.config(state=DISABLED)
        self.box.pack(expand="yes", fill=BOTH, side=TOP)
        
        self.textarea = Text(frame, width=30, height=5)
        #self.textarea.insert(END, "")
        self.textarea.bind("<KeyRelease-Return>", self.gettext) #Se metto on press, rimane una newline in piu
        self.textarea.pack(expand="yes", fill=BOTH, side=TOP)

        
        okButton = Button(frame, text="Panic Button", activebackground="red", command=self.sendFile) 
        okButton.pack(expand="no", fill=BOTH, side=TOP)
        
        self.usersFrame = Frame(self.parent)
        self.usersFrame.pack(fill=BOTH, expand=1, side=RIGHT)
        
        self.userListbox = Listbox(self.usersFrame, width=3)
        self.userListbox.pack(fill=BOTH, expand=1)
            
        self.updateUsersFrame()
        
    def centerWindow(self):
      
        w = 600
        h = 475

        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))
     
    def gettext(self, e): #e sta per event, questo e' un listener
        text = self.textarea.get("1.0", END) # 1.0: row:columa -  END-2c rimuove l'ultimo carattere, una newline \r\n
        if "\n" in text:
            text = text.replace("\n", "")
        self.textarea.delete("0.0", END) #NON VA: il problema e' che viene inviato il carattere di newline ma non incluso nell'area a causa della bind mi sa. Devo escluderlo io
        self.sendToServer(text)
        
    def printConversation(self, message):
        self.box.config(state=NORMAL)
        self.box.insert(END,"\n" + message)
        self.lineCounter = self.lineCounter + 2
        
        #m = re.match("\[.*\] From .*\n", self.box.get("0.0", END))
        m = re.search("\[.*\].*:", message, re.MULTILINE)
        
        
        if m is not None:
            #print("MATCH")
            #print(m.group(0))
            #print(str(m.start(0)) + "_" + str(m.end(0)))
            #print("COUNTER")
            #print(str(self.lineCounter) + "." + str(m.start(0)+1) + "___" + str(self.lineCounter) + "." + str(m.end(0)))
            self.box.tag_add("header", str(self.lineCounter) + "." + str(m.start(0)), str(self.lineCounter) + "." + str(m.end(0)))
            self.box.tag_config("header", font=self.customFontHeader, foreground = "blue")
        
        
        self.box.config(state=DISABLED)
        #self.box.yview_scroll(10000,"units")
        self.box.see(END)

    
    def sendToServer(self, messageToSend):
        self.conn.send(messageToSend.encode(encoding='utf_8', errors='strict'))
    
    def sendFile(self):
        #aprire una dialog di quelle predefinite (Sfoglia...)
        #capire come fare la send di un file sul socket...
        pass
    def updateUsersFrame(self):
        
        global connectedClients
    
        self.userListbox.delete(0, END)
                    
        self.userListbox.insert(END, "Connected users")
        for item in connectedClients:
            self.userListbox.insert(END, item)
コード例 #43
0
ファイル: gui.py プロジェクト: hamptus/mftpy
class Application(Frame):
    """ The application GUI for the MFT Parser """

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master.title(settings.title)
        self.centerWindow()
        self.master.config(menu=self.buildMenu())

        top = self.winfo_toplevel()
        top.rowconfigure(0, weight=1000)
        top.columnconfigure(0, weight=1000)

        self.rowconfigure(0, weight=999)
        self.columnconfigure(2, weight=999)

        self.grid(sticky=N + E + S + W, padx=10, pady=5)

        self.createWidgets()

    def centerWindow(self):
        """ Center the application window """
        w = settings.width
        h = settings.height
        sw = self.master.winfo_screenwidth()
        sh = self.master.winfo_screenheight()

        x = (sw - w) / 2
        y = (sh - h) / 2
        self.master.geometry("%dx%d+%d+%d" % (w, h, x, y))

    def buildMenu(self):
        # Add a menu bar
        menubar = Menu(self)
        # Create the file menu
        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label="Open", command=self.open, underline=0)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.quit, underline=1)
        # Add the file menu to the menu bar
        menubar.add_cascade(label="File", menu=filemenu, underline=0)
        return menubar

    def createWidgets(self):
        self.buildListbox()
        self.buildNotebook()

    def buildListbox(self):
        scrollbar = Scrollbar(self, orient=VERTICAL)
        scrollbar.grid(row=0, column=1, sticky=N + S, pady=5)

        self.listbox = Listbox(self, selectmode=SINGLE, relief=SUNKEN, yscrollcommand=scrollbar.set)
        self.listbox.grid(row=0, column=0, sticky=N + S + W, padx=2, pady=5, ipadx=10)
        self.listbox.bind("<<ListboxSelect>>", self.update)
        self.listbox.rowconfigure(0, weight=1)
        self.listbox.columnconfigure(0, weight=10)
        self.listitems = []
        scrollbar.configure(command=self.listbox.yview)

        self.buttons = Frame(self)
        self.buttons.grid(row=1, column=0, sticky=N + E + S + W, padx=2, pady=2)

        self.clearButton = Button(self.buttons, text="Clear", command=self.clearListbox)
        self.clearButton.grid(row=0, column=0, padx=2, sticky=E + W)

        self.exportButton = Button(self.buttons, text="Export", command=self.exportEntry)
        self.exportButton.grid(row=0, column=1, padx=2, sticky=E + W)

    def clearListbox(self):
        self.listbox.delete(0, END)
        self.listitems = []
        self.removeTabs()

    def exportEntry(self):
        self.selected = self.listbox.curselection()
        if self.selected:
            e = self.listitems[int(self.selected[0])]
            if hasattr(e, "filename"):
                fn = asksaveasfilename(initialfile=e.filename + ".mft")
            else:
                fn = asksaveasfilename()
            with open(fn, "wb") as mftfile:
                mftfile.write(e.dump())

    def buildNotebook(self):
        self.notebook = Notebook(self)
        self.notebook.grid(row=0, column=2, sticky=N + S + W + E, pady=5, padx=5)
        self.notebook.rowconfigure(0, weight=2)
        self.notebook.columnconfigure(1, weight=2)

    def open(self):
        self.filename = askopenfilename()
        if self.filename:
            self.validate_entry(self.filename)

    def add_entry(self, entry):
        self.master.update_idletasks()
        self.listitems.append(entry)
        self.listbox.insert(END, os.path.basename(entry.filename))

    def validate_entry(self, filename):
        if os.path.getsize(filename) == 1024:
            self.filetype = "entry"
        else:
            self.filetype = "partition"

        if self.filetype == "partition":
            p = entry.Partition(filename)
            while True:
                try:
                    w = p.walk()
                    self.add_entry(w.__next__())
                except StopIteration:
                    break

        else:
            with open(filename, "rb") as data:
                d = data.read(1024)
                e = entry.Entry(d)
                try:
                    e.validate()
                except ValidationError:
                    showwarning(
                        "Invalid Mft entry",
                        "This file is not a valid MFT entry. Its signature value is %s" % e.signature.raw,
                    )
                else:
                    self.add_entry(e)

    def get_attribute(self, attributes, attribute_name):
        data = []
        for attr in attributes:
            if hasattr(attr, attribute_name):
                data.append(getattr(attr, attribute_name))
        if data:
            return data
        else:
            return None

    def removeTabs(self):
        tabs = self.notebook.tabs()
        for tab in tabs:
            self.notebook.forget(tab)

    def update(self, event):
        self.selected = self.listbox.curselection()
        self.removeTabs()
        try:
            e = self.listitems[int(self.selected[0])]

            self.entryTab = ScrolledText(self.notebook, relief=SUNKEN, padx=10, pady=5)

            self.entryTab.insert(END, "Signature: %s\n" % e.signature)
            self.entryTab.insert(END, "Fixup array offset: %s\n" % e.fixup_array_offset)
            self.entryTab.insert(END, "Fixup array entries: %s\n" % e.fixup_array_entries)
            self.entryTab.insert(END, "$LogFile sequence number: %s\n" % e.lsn)
            self.entryTab.insert(END, "Sequence: %s\n" % e.sequence)
            self.entryTab.insert(END, "Link count: %s\n" % e.link_count)
            self.entryTab.insert(END, "Attribute offset: %s\n" % e.attribute_offset)
            self.entryTab.insert(END, "Flags: %s\n" % e.flags)
            self.entryTab.insert(END, "Used size: %s\n" % e.used_size)
            self.entryTab.insert(END, "Allocated size: %s\n" % e.allocated_size)
            self.entryTab.insert(END, "File reference: %s\n" % e.file_ref)
            self.entryTab.insert(END, "Next attribute ID: %s\n" % e.next_attr_id)

            self.entryTab.config(state=DISABLED)
            self.notebook.add(self.entryTab, text=e.filename)

            for attribute in e.attributes:
                tab = ScrolledText(self.notebook, relief=SUNKEN, padx=10, pady=5)
                for i in attribute.export():
                    tab.insert(END, i + "\n")
                tab.config(state=DISABLED)
                self.notebook.add(tab, text=attribute.attr_type.value)

        except IndexError:
            pass
コード例 #44
0
ファイル: ChatGUIClient.py プロジェクト: skimdz86/Utilities
class ChatGUI(Frame):
  
    def __init__(self, parent, conn):
        #Frame.__init__(self, parent, background="grey")   
         
        self.parent = parent
        self.conn = conn
        
        self.centerWindow()
        self.initUI()
    
    def initUI(self):
      
        #mettere qui tutta l'inizializzazione dei frame anche
        #direi 2 frame, uno left e uno right
      
        self.parent.title("Python Chat") 
        
        frame = Frame(self.parent)
        frame.pack(fill=BOTH, expand=1, side=LEFT)
        
        self.box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=1, height=20)
        self.box.insert(END, 'Welcome to Python Chat!')
        self.box.config(state=DISABLED)
        self.box.pack(expand="yes", fill=BOTH, side=TOP)
        
        self.textarea = Text(frame, width=1, height=5)
        #self.textarea.insert(END, "")
        self.textarea.bind("<KeyRelease-Return>", self.gettext) #Se metto on press, rimane una newline in piu
        self.textarea.pack(expand="yes", fill=BOTH, side=TOP)

        
        okButton = Button(frame, text="Attach file", activebackground="green", command=self.sendFile) 
        okButton.pack(expand="no", fill=BOTH, side=TOP)
        
        
        #per gestire invio con la newline --> http://userpages.umbc.edu/~dhood2/courses/cmsc433/spring2010/?section=Notes&topic=Python&notes=93
        
        #usersFrame = Frame(self.parent)
        #usersFrame.pack(fill=BOTH, expand=1, side=RIGHT)
    
    def centerWindow(self):
      
        w = 600
        h = 450

        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))
     
    def gettext(self, e): #e sta per event, questo e' un listener
        text = self.textarea.get("1.0", END + " - 2c") # 1.0: row:columa -  END-2c rimuove l'ultimo carattere, una newline \r\n
        self.textarea.delete("0.0", END) #NON VA: il problema e' che viene inviato il carattere di newline ma non incluso nell'area a causa della bind mi sa. Devo escluderlo io
        self.sendToServer(text)
        
    def printConversation(self, message):
        self.box.config(state=NORMAL)
        self.box.insert(END,"\n" + message)
        
        #aggiungo colorazione parte di testo --> troppo complesso per ora
        ''''m = re.search("", message)
        lastIndex = len(m.group(0))
        self.box.tag_add("header", m.start(), m.stop())
        self.box.tag_config("header", foreground="green")
        '''
        self.box.config(state=DISABLED)
        #self.box.yview_scroll(10000,"units")
        self.box.see(END)

    
    def sendToServer(self, messageToSend):
        self.conn.send(messageToSend.encode(encoding='utf_8', errors='strict'))
    
    def sendFile(self):
        #aprire una dialog di quelle predefinite (Sfoglia...)
        #capire come fare la send di un file sul socket...
        pass
コード例 #45
0
ファイル: excel_gui.py プロジェクト: waywinkle/m3_excel
class App:

    def __init__(self, master):

        nb = ttk.Notebook(master)
        nb.pack()

        main_tab = ttk.Frame(nb, padding=(3,3,12,12))
        settings_tab = ttk.Frame(nb, padding=(3,3,12,12))
        main_tab.grid(column=0, row=0, sticky=(N, S, E, W))
        settings_tab.grid(column=0, row=0, sticky=(N, S, E, W))

        nb.add(main_tab, text='Main')
        nb.add(settings_tab, text='Settings')

        nb.pack(expand=1, fill="both")


        self.quit_button = Button(
            main_tab, text="Quit", command=nb.quit
            )
        self.quit_button.grid(column=1, row=5, columnspan=1, sticky=(N, S, E, W))
        self.process_button = Button(
            main_tab, text="Process", command=self.process
            )
        self.process_button.grid(column=1, row=0, columnspan=1, sticky=(N, S, E, W), padx=5)

        self.open_file_button = Button(
            main_tab, text="Open file", command=self.open_file
            )
        self.open_file_button.grid(column=0, row=0, columnspan=1, sticky=(N, S, E, W), padx=5)

        self.text =  ScrolledText(main_tab)
        self.text.grid(column=0, row=3, columnspan=2, rowspan=2, sticky=(N, S, E, W))
        self.text.config(state='disabled')

        self.user_label = Label(main_tab, text="Username")
        self.password_label = Label(main_tab, text="Password")

        self.username = Entry(main_tab)
        self.password = Entry(main_tab, show="*")

        self.user_label.grid(row=1, column=0, sticky=W)
        self.password_label.grid(row=2, column=0, sticky=W)
        self.username.grid(row=1, column=0, sticky=E)
        self.password.grid(row=2, column=0, sticky=E)

        main_tab.rowconfigure(3, weight=3)
        main_tab.columnconfigure(0, weight=1)
        main_tab.columnconfigure(1, weight=1)

    def open_file(self):

        ftypes = [('Excel', '*.xlsx'), ('All files', '*')]
        self.file_reference = filedialog.askopenfilename(filetypes = ftypes)

    def process(self):

        if hasattr(self, 'file_reference'):

            try:
                trans = excel_mi(self.file_reference, self.username.get(), self.password.get())
                trans.process_trans()

                for i in trans:
                    log = i['program'] + '.' + i['transaction'] + ': ' + i['result']
                    self.write_log(log)

            except:
                e = sys.exc_info()
                self.write_log(str(e))

        else:
            self.write_log('No file selected')

    def write_log(self, log_text):
        self.text.config(state='normal')
        self.text.insert(END, log_text + '\n')
        self.text.config(state='disable')
コード例 #46
0
ファイル: Express.py プロジェクト: liukangxu/ExpressManager
class ExpressQuery(Frame):
    def __init__(self, master):
        Frame.__init__(self, master)
        self.root = master
        self.root.bind_all('<F5>', self.update_all_posts)
        self.root.bind_all('<Escape>', self.clear_input)
        self.all_posts = {}  # 运单列表
        self.root.title('快递助手 v1.2')
        self.root.iconbitmap('logo.ico')
        self.root.resizable(width=False, height=False)

        self.auto_company_url = 'http://www.kuaidi100.com/autonumber/autoComNum?text='
        self.query_url = 'http://www.kuaidi100.com/query?'

        with open('company_codes.json', 'r', encoding='utf-8') as f:
            self.company_codes = json.loads(f.read())
            self.company_names = dict((v, k) for k, v in self.company_codes.items())
        with open('state.json', 'r', encoding='utf-8') as f:
            self.state = json.loads(f.read())

        parent_frame = Frame(self.root)
        parent_frame.grid(padx=10, pady=10, stick=E + W + N + S)

        add_post_group = Frame(parent_frame)
        post_id_label = Label(add_post_group, text='运单号:')
        self.post_id_var = tkinter.StringVar()  # 运单号
        self.post_id_field = Entry(add_post_group, width=20, textvariable=self.post_id_var)
        self.post_id_field.bind('<Return>', self.handle_add_post)
        post_note_label = Label(add_post_group, text='备注:')
        self.post_note_var = tkinter.StringVar()  # 运单注释
        post_note_field = Entry(add_post_group, width=20, textvariable=self.post_note_var)
        post_note_field.bind('<Return>', self.handle_add_post)
        post_company_label = Label(add_post_group, text='公司:')
        self.post_company_name_var = tkinter.StringVar()
        self.post_company_field = Combobox(add_post_group, textvariable=self.post_company_name_var,
                                           values=list(self.company_names.values()), width=12)
        post_add_button = Button(add_post_group, text='添加', width=10, command=self.handle_add_post)
        clear_input_button = Button(add_post_group, text='清空', width=10, command=self.clear_input)

        post_id_label.grid(row=0, column=0)
        self.post_id_field.grid(row=0, column=1)
        post_note_label.grid(row=0, column=2)
        post_note_field.grid(row=0, column=3)
        post_company_label.grid(row=0, column=4)
        self.post_company_field.grid(row=0, column=5)
        post_add_button.grid(row=0, column=6, padx=5)
        clear_input_button.grid(row=0, column=7, padx=5)
        self.post_id_field.focus_set()

        show_posts_group = Frame(parent_frame)
        self.posts = Treeview(show_posts_group, height=10, selectmode='browse',
                              columns=('note', 'company_name', 'state', 'last_update'))  # 运单列表框
        self.x_scrollbar = Scrollbar(show_posts_group, orient=tkinter.HORIZONTAL, command=self.posts.xview)
        self.y_scrollbar = Scrollbar(show_posts_group, orient=tkinter.VERTICAL, command=self.posts.yview)
        self.posts.config(xscroll=self.x_scrollbar.set, yscroll=self.y_scrollbar.set)
        self.posts.column('#0', width=130)
        self.posts.heading('#0', text='运单号')
        self.posts.column('note', width=130)
        self.posts.heading('note', text='备注')
        self.posts.column('company_name', width=80)
        self.posts.heading('company_name', text='公司名称')
        self.posts.column('state', width=180)
        self.posts.heading('state', text='运单状态')
        self.posts.column('last_update', width=150)
        self.posts.heading('last_update', text='最后更新')
        self.posts.bind('<<TreeviewSelect>>', self.show_post_detail)
        self.posts.bind('<Delete>', self.remove_post)
        self.post_detail = ScrolledText(show_posts_group, bg='white', width=92, height=16, state=tkinter.DISABLED)
        self.posts.grid(row=0, column=0, sticky=W + N + S)
        self.x_scrollbar.grid(row=1, column=0, sticky=E + W)
        self.y_scrollbar.grid(row=0, column=1, sticky=N + S)
        self.post_detail.grid(row=2, column=0, sticky=W + N + S, padx=(0, 10))
        status_label = Label(parent_frame, text='F5 更新全部运单动态')

        add_post_group.grid(row=0, column=0)
        show_posts_group.grid(row=1, column=0)
        status_label.grid(row=2, column=0)

        self.get_history()

    # 获取历史记录
    def get_history(self):
        try:
            with open('history.json', 'r', encoding='utf-8') as f:
                self.all_posts = json.loads(f.read())
            for post_id in self.all_posts:
                self.posts.insert('', 0, post_id,
                                  text=post_id,
                                  values=(self.all_posts[post_id]['note'],
                                          self.all_posts[post_id]['company_name'],
                                          self.state[self.all_posts[post_id]['state']],
                                          self.all_posts[post_id]['last_update']))
        except ValueError:
            with open('history.json', 'w', encoding='utf-8') as f:
                json.dump(self.all_posts, f)
            print('No history record found')

    # 保存运单记录
    def save_history(self):
        with open('history.json', 'w', encoding='utf-8') as f:
            json.dump(self.all_posts, f)

    # 新增运单
    def handle_add_post(self, event=None):
        if self.post_id_var.get() == '':
            return

        if self.post_company_name_var.get():
            company_code = self.company_codes[self.post_company_name_var.get()]
        else:
            try:
                with request.urlopen(self.auto_company_url + self.post_id_var.get()) as response:
                    company_code = json.loads(response.read().decode())['auto'][0]['comCode']
            except IndexError:
                return

        post = {
            'post_id': self.post_id_var.get(),
            'company_code': company_code,
            'company_name': self.company_names[company_code],
            'note': self.post_note_var.get()}

        self.all_posts[post['post_id']] = post

        try:
            self.posts.index(post['post_id'])
        except tkinter.TclError:
            self.posts.insert('', 0, self.post_id_var.get(), text='%s' % self.post_id_var.get())

        handle_add_post = threading.Thread(target=self.handle_add_post_thread, args=(post,))
        handle_add_post.start()

        self.clear_input()

    def handle_add_post_thread(self, post):
        self.update_post_detail_thread(post)
        self.posts.selection_set(post['post_id'])
        self.save_history()

    # 清空输入框
    def clear_input(self, event=None):
        self.post_id_var.set('')
        self.post_note_var.set('')
        self.post_company_name_var.set('')
        self.post_id_field.focus_set()

    # 移除运单
    def remove_post(self, event=None):
        self.all_posts.pop(self.posts.selection()[0])
        self.posts.delete(self.posts.selection()[0])
        self.post_detail.config(state=tkinter.NORMAL)
        self.post_detail.delete('1.0', tkinter.END)
        self.post_detail.config(state=tkinter.DISABLED)
        self.save_history()
        self.clear_input()

    # 更新全部运单动态
    def update_all_posts(self, event=None):
        update_all_posts = threading.Thread(target=self.update_all_posts_thread)
        update_all_posts.start()

    def update_all_posts_thread(self):
        pool = ThreadPool(4)
        posts = list(self.all_posts.values())
        pool.map(self.update_post_detail, posts)
        pool.close()
        pool.join()
        self.save_history()

    # 更新单个运单状态
    def update_post_detail(self, post=None):
        update_post_detail  = threading.Thread(target=self.update_post_detail_thread)
        update_post_detail.start()

    def update_post_detail_thread(self, post=None):
        if not post:
            post = self.all_posts[self.posts.selection()[0]]
        with request.urlopen(self.query_url + 'type=' + post['company_code'] + '&postid=' + post['post_id'])\
                as response:
            obj = json.loads(response.read().decode())
            self.all_posts[post['post_id']]['status'] = obj['status']
            if obj['status'] == '200':
                self.all_posts[post['post_id']]['data'] = obj['data']
                self.all_posts[post['post_id']]['state'] = obj['state']
                self.all_posts[post['post_id']]['last_update'] = obj['data'][0]['time']
            else:
                self.all_posts[post['post_id']]['data'] = [{'time': '快递公司参数异常',
                                                            'context': '单号不存在或者已经过期'}]
                self.all_posts[post['post_id']]['state'] = '-1'
                self.all_posts[post['post_id']]['last_update'] = ''
        self.posts.item(post['post_id'],
                        values=(post['note'], post['company_name'], self.state[post['state']], post['last_update']))

    # 显示运单详情
    def show_post_detail(self, event=None):
        selected_post = self.all_posts[self.posts.selection()[0]]
        self.post_id_var.set(selected_post['post_id'])
        self.post_note_var.set(selected_post['note'])
        self.post_company_name_var.set(selected_post['company_name'])

        self.post_detail.config(state=tkinter.NORMAL)  # 允许编辑消息记录文本框
        self.post_detail.delete('1.0', tkinter.END)
        for x in selected_post['data']:
            self.post_detail.insert('end', x['time'] + '\t' + x['context'] + '\n')
        self.post_detail.config(state=tkinter.DISABLED)  # 禁止编辑消息记录文本框
コード例 #47
0
ファイル: gui.py プロジェクト: wearyoung/daovision
class SshPanel(Frame):
	def __init__(self, parent):
		Frame.__init__(self, parent)
		self.scrolltext = ScrolledText(self, width = 120,
				font = ("", 14, "normal"), height = 30)
		self.scrolltext.config(state = "disable")

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

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

		with shelve.open("userconfigdb") as db:
			keys = tuple(db.keys())
		if not keys:
			configButtonCmd()
		with shelve.open("userconfigdb") as db:
			self.sshIP = db[tuple(db.keys())[0]].hostaddress
		self._configButtonCmd()

	def _deleteText(self):
		self.scrolltext.config(state = "normal")
		self.scrolltext.delete("1.0", END)
		self.scrolltext.config(state = "disable")
	
	def _fetch(self, root, vars):
		attrs  = []
		for var in vars:
			t = var.get()
			if not t:
				return
			attrs.append(t)
		self.username = attrs[0]
		self.passwd = attrs[1]
		root.destroy()

	def _configButtonCmd(self):
		popwin = PopupWindow("User Config")
		popwin.grab_set()
		popwin.focus()

		form = Frame(popwin)
		left = Frame(form)
		right = Frame(form)
		bottom = Frame(popwin)
		form.pack(fill = X)
		left.pack(side = LEFT)
		right.pack(side = RIGHT, expand = YES, fill = X)
	#	bottom.pack(side = LEFT)

		fields = ("username", "password")
		variables = []
		for field in fields:
			lab = Label(left, width = 10, text = field)
			ent = Entry(right)
			lab.pack(side = TOP)
			ent.pack(side = TOP, fill = X)
			var = StringVar()
			ent.config(textvariable = var)
			variables.append(var)
	
		Button(popwin, text = "Ok", font = ("", 15, "normal"),
			command = (lambda vars = variables, root = popwin: self._fetch(root, vars))).pack()
        

	def _runCommand(self):
		command = self.entry.get()
		self.entry.delete(0, END)
		self.scrolltext.config(state = "normal")

		if command != "":
			ssh = paramiko.SSHClient()
			try:
				ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#				print(self.username, self.passwd)
				ssh.connect(self.sshIP, 22, self.username, self.passwd, timeout = 10)
				stdin,stdout,stderr = ssh.exec_command(command)
				out = stdout.readlines()
				err = stderr.readlines()
				for r in out:
					self.scrolltext.insert(END, "  " + r)
				for r in err:
					self.scrolltext.insert(END, "  " + r)
			except:
				pass
			finally:
				ssh.close()
		self.scrolltext.insert(END, "---------------------------------\n")
		self.scrolltext.config(state = "disable")
		self.scrolltext.see("end")
コード例 #48
0
ファイル: recipe-578062.py プロジェクト: jacob-carrier/code
class MarkovDemo:

    def __init__(self, master):
        self.prompt_size = Label(master, anchor=W, text='Encode Word Size')
        self.prompt_size.pack(side=TOP, fill=X)

        self.size_entry = Entry(master)
        self.size_entry.insert(0, '8')
        self.size_entry.pack(fill=X)

        self.prompt_plain = Label(master, anchor=W, text='Plaintext Characters')
        self.prompt_plain.pack(side=TOP, fill=X)

        self.plain_entry = Entry(master)
        self.plain_entry.insert(0, '""')
        self.plain_entry.pack(fill=X)

        self.showframe = Frame(master)
        self.showframe.pack(fill=X, anchor=W)

        self.showvar = StringVar(master)
        self.showvar.set("encode")

        self.showfirstradio = Radiobutton(self.showframe,
                                          text="Encode Plaintext",
                                          variable=self.showvar,
                                          value="encode",
                                          command=self.reevaluate)
        self.showfirstradio.pack(side=LEFT)

        self.showallradio = Radiobutton(self.showframe,
                                        text="Decode Cyphertext",
                                        variable=self.showvar,
                                        value="decode",
                                        command=self.reevaluate)
        self.showallradio.pack(side=LEFT)
        
        self.inputbox = ScrolledText(master, width=60, height=10, wrap=WORD)
        self.inputbox.pack(fill=BOTH, expand=1)

        self.dynamic_var = IntVar()
        self.dynamic_box = Checkbutton(master, variable=self.dynamic_var,
                                       text='Dynamic Evaluation',
                                       offvalue=False, onvalue=True,
                                       command=self.reevaluate)
        self.dynamic_box.pack()
                                       
        self.output = Label(master, anchor=W, text="This is your output:")
        self.output.pack(fill=X)
        
        self.outbox = ScrolledText(master, width=60, height=10, wrap=WORD)
        self.outbox.pack(fill=BOTH, expand=1)

        self.inputbox.bind('<Key>', self.reevaluate)

        def select_all(event=None):
            event.widget.tag_add(SEL, 1.0, 'end-1c')
            event.widget.mark_set(INSERT, 1.0)
            event.widget.see(INSERT)
            return 'break'
        self.inputbox.bind('<Control-Key-a>', select_all)
        self.outbox.bind('<Control-Key-a>', select_all)
        self.inputbox.bind('<Control-Key-/>', lambda event: 'break')
        self.outbox.bind('<Control-Key-/>', lambda event: 'break')
        self.outbox.config(state=DISABLED)
        
    def reevaluate(self, event=None):
        if event is not None:
            if event.char == '':
                return
        if self.dynamic_var.get():
            text = self.inputbox.get(1.0, END)[:-1]
            if len(text) < 10:
                return
            text = text.replace('\n \n', '\n\n')
            mode = self.showvar.get()
            assert mode in ('decode', 'encode'), 'Bad mode!'
            if mode == 'encode':
                # Encode Plaintext
                try:
                    # Evaluate the plaintext characters
                    plain = self.plain_entry.get()
                    if plain:
                        PC = eval(self.plain_entry.get())
                    else:
                        PC = ''
                        self.plain_entry.delete(0, END)
                        self.plain_entry.insert(0, '""')
                    # Evaluate the word size
                    size = self.size_entry.get()
                    if size:
                        XD = int(size)
                        while grid_size(text, XD, PC) > 1 << 20:
                            XD -= 1
                    else:
                        XD = 0
                        grid = 0
                        while grid <= 1 << 20:
                            grid = grid_size(text, XD, PC)
                            XD += 1
                        XD -= 1
                    # Correct the size and encode
                    self.size_entry.delete(0, END)
                    self.size_entry.insert(0, str(XD))
                    cyphertext, key, prime = encrypt_str(text, XD, PC)
                except:
                    traceback.print_exc()
                else:
                    buffer = ''
                    for block in key:
                        buffer += repr(block)[2:-1] + '\n'
                    buffer += repr(prime)[2:-1] + '\n\n' + cyphertext
                    self.outbox.config(state=NORMAL)
                    self.outbox.delete(1.0, END)
                    self.outbox.insert(END, buffer)
                    self.outbox.config(state=DISABLED)
            else:
                # Decode Cyphertext
                try:
                    header, cypher = text.split('\n\n', 1)
                    lines = header.split('\n')
                    for index, item in enumerate(lines):
                        try:
                            lines[index] = eval('b"' + item + '"')
                        except:
                            lines[index] = eval("b'" + item + "'")
                    plain = decrypt_str(cypher, tuple(lines[:-1]), lines[-1])
                except:
                    traceback.print_exc()
                else:
                    self.outbox.config(state=NORMAL)
                    self.outbox.delete(1.0, END)
                    self.outbox.insert(END, plain)
                    self.outbox.config(state=DISABLED)
        else:
            text = self.inputbox.get(1.0, END)[:-1]
            text = text.replace('\n \n', '\n\n')
            mode = self.showvar.get()
            assert mode in ('decode', 'encode'), 'Bad mode!'
            if mode == 'encode':
                try:
                    XD = int(self.size_entry.get())
                    PC = eval(self.plain_entry.get())
                    size = grid_size(text, XD, PC)
                    assert size
                except:
                    pass
                else:
                    buffer = 'Grid size will be:\n' + convert(size)
                    self.outbox.config(state=NORMAL)
                    self.outbox.delete(1.0, END)
                    self.outbox.insert(END, buffer)
                    self.outbox.config(state=DISABLED)
コード例 #49
0
ファイル: GUI.py プロジェクト: samhowes/Downloader
class GUI(GUITools.MainWindow):
	ITEMS_PER_WAKE = 10
	WAKE_INTERVAL = 100
	def __init__(self, app_name):
		GUITools.MainWindow.__init__(self, app_name)
		self.displayStart()
		
	def displayStart(self):
		self.container = Frame(self)
		self.container.pack(expand=YES, fill=BOTH)
		msg = 'Downloader by Sam Howes\nPress Start to begin downloading!'
		Label(self.container, text=msg).pack(side=TOP, expand=YES, fill=BOTH)	
		Button(self.container, text='Start!', command=self.onStart).pack(side=TOP, expand=YES, anchor=S)
		
	def onStart(self): 
		self.stdout = GUITools.TSafeRedirect()						# Create a buffer to replace stdout
		self.systemStreams = (sys.stdin, sys.stdout, sys.stderr)	# Save the system streams to replace them later
		sys.stdout = self.stdout									# Redirect writes to stdout and stderr
		sys.stderr = self.stdout
		
		newFrame = Frame(self)										# Create a display for the stdout
		self.textDisplay = ScrolledText(newFrame)
		self.textDisplay.config(state=DISABLED)						# make it read only
	
		self.container.pack_forget()								# remove the old window contents
		del self.container											# explicitly delete to destroy the elements
		
		self.mainContainer = newFrame									# Replace the windows content	
		self.progressContainer = Frame(self)
		self.progressContainer.pack(side=BOTTOM, fill=X)
		self.mainContainer.pack(expand=YES, fill=BOTH)					# Pack now to display the frame
		self.textDisplay.pack(expand=YES, fill=BOTH)
		
		self.callbackQ = Queue()									# Kick off the main worker thread to start downloading
		self.mainWorker = DownloadMaster(self, self.callbackQ, name='DownloadMaster')		
		#self.mainWorker = DryRun(self, self.callbackQ, name='DryRun')		
		self.mainWorker.start()
		
		self.after(self.WAKE_INTERVAL, self.onWake)					# Set the timer to refresh the GUI
		
	def newProgressBox(self, title, totalBytes, progressFunc):
		self.progressBox = GUITools.ProgressBox(self.progressContainer, title, totalBytes, progressFunc)
		self.progressBox.pack(side=BOTTOM, fill=X)	
	
	def deleteProgressBox(self):
		self.progressBox.cancelUpdate()
		self.progressBox.pack_forget()
		del self.progressBox
			
	def onWake(self):
		if not self.stdout.isEmpty():
			self.textDisplay.config(state=NORMAL)
			self.textDisplay.insert(END, self.stdout.clear())
			self.textDisplay.see(END)		
			self.textDisplay.config(state=DISABLED)
			self.textDisplay.update()
		
		for ii in range(self.ITEMS_PER_WAKE):
			try:
				callback, args = self.callbackQ.get(block=False)
			except queue.Empty:
				break
			else:
				callback(*args)
						
		self.after(self.WAKE_INTERVAL, self.onWake)
コード例 #50
0
ファイル: EAAutoWindow.py プロジェクト: Maccalariat/EAAuto
class EAAutoWindow:
    eaDB = None
    fileName = None

    def __init__(self, master):

        self.master = master
        # declare instance variables
        self.log = None  # the logging widget
        self.eaDB = None
        self.spreadsheet = None
        self.application_inventory_map_excel = {}
        self.application_inventory_map_eap = {}
        self.ea_ecdm_element_map = {}
        self.ea_ecdm_relationship_map = {}
        self.erwin_package_map = {}
        self.erwin_class_map = {}
        self.erwin_relationship_map = {}
        self.erwin_generalization_map = {}
        self.log_widget = None
        self.ecdm_Sparx_to_ERWIN_GUID = {}
        self.ecdm_ERWIN_to_Sparx_GUID = {}
        # end instance variables

        self.initUI(master)
        self.log_message('open for business')
        self.log_message("Don't forget to open and close the database yourself!")

    def exit_action(self):
        self.master.destroy()

    def reconcile_applications(self):
        """
        compare the application inventory spreadsheet to the EA database
        for now, produce a report of differences
        :return:

        """
        if self.eaDB is None:
            self.log_message("you need to open a database")
            return
        self.eaDB.find_package('Application Inventory')
        self.application_inventory_map_eap = self.eaDB.build_application_map()

        ai_file_name = self.open_excel_ai()
        self.log_message("AI excel file = " + ai_file_name)
        if ai_file_name is None:
            self.log_message("no eap file selected")
            return

        self.log_message("AI File = " + ai_file_name)
        spreadsheet = ApplicationInventory.ApplicationInventory(
            ai_file_name, self.log_message)
        self.application_inventory_map_excel = spreadsheet.build_application_map()
        spreadsheet.close_spreadsheet()
        self.log_message("Closing AI Spreadsheet")
        del spreadsheet

        self.compare_ai_to_sparx()

    def update_AHC(self):
        """
        read a spreadsheet with input from Application Health Check and Cloud affinity
        push into tagged values for the applications
        :return:

        """
        # first open the database
        eap_file_name = self.open_eap()

        if eap_file_name is None:
            self.log_message("no eap file selected")
            return
        self.log_message("EAP Filename = " + eap_file_name)

        self.eaDB = EADatabase.EAdatabase(eap_file_name, self.log_message)
        self.eaDB.find_package('Application Inventory')

        ai_file_name = self.open_excel_ai()
        self.log_message("AI excel file = " + ai_file_name)
        if ai_file_name is None:
            self.log_message("no excel file selected")
            return

        self.log_message("AI File = " + ai_file_name)
        spreadsheet = ApplicationInventory.ApplicationInventory(
            ai_file_name, self.log_message)
        self.application_inventory_map_excel = spreadsheet.build_application_map()
        spreadsheet.close_spreadsheet()
        self.log_message("Closing AI Spreadsheet")
        del spreadsheet

        self.compare_ahc_to_sparx()

        self.eaDB.stop_db()

    def extract_ECDM_guids(self):
        """
        parse the ECDM canonical directory dumping all elements and relationships (between ERWIN elements)
        to get the baseline Sparx GUIDS.
        This is pushed out in an Excel file (as a convencience) with two tabs:
        tab 1 is the element list
        tab 2 is the Relationship list
        :return:
        """
        self.log_message("starting ECDM guid dump")

        # if self.eaDB is None:
        #    self.log_message("no eap file selected")
        #    return

        erwin_mapper = ErwinXMI.ErwinXMI(self.log_message)
        options = {'defaultextension': '.xml',
                   'filetypes': (('xml', '.xml'), ('xmi', 'xmi')),
                   'initialdir': 'C:\\HOME\\var\\projects\\python\\EAAUTO',
                   'initialfile': 'erwin_export.EAAuto_xml',
                   'parent': self.master,
                   'title': 'Open ERWIN xmi export'}
        filename = askopenfilename(**options)

        self.eaDB.find_package('ECDM Canonical')
        (self.ea_ecdm_element_map, self.ea_ecdm_relationship_map) =  self.eaDB.build_ecdm_maps()

        directory = askdirectory(parent = self.master,
                                 initialdir='C:\\HOME\\var\\projects\\python\\EAAUTO',
                                 title = 'Sparx pickle of ECDM')
        pickle.dump(self.ea_ecdm_element_map, open(directory + '/ea_ecdm_element_map.p', "wb"))
        pickle.dump(self.ea_ecdm_relationship_map, open(directory + '/ea_ecdm_relationship_map.p', "wb"))
        exporter = ECDMSpreadsheet.ECDMSpreadsheet("c:/HOME/var/projects/Python/EAAuto/ecdmmap.xls", self.log_message)
        exporter.write_ecdm_map(self.ea_ecdm_element_map, self.ea_ecdm_relationship_map, self.log_message)

        if filename:
            (self.erwin_package_map, self.erwin_class_map, self.erwin_relationship_map, self.erwin_generalization_map) =\
                erwin_mapper.build_erwin_map(filename)

        else:
            self.log_message("error getting the ERWIN xmi export")
            return
        guid_mapper = BiGUID.BiGUID()
        reverse_ea_ecdm_element_map = {v: k for k, v in self.ea_ecdm_element_map.items()}
        # erwin GUID is left-hand, Sparx GUID is right-hand
        """
        ea_ecdm_element_map is GUID: (name, type)
        erwin_class_map is name: GUID
        """
        for erwin_name, erwin_guid in self.erwin_class_map.items():
            if erwin_name in reverse_ea_ecdm_element_map:
                guid_mapper.add(self.erwin_class_map[erwin_name], reverse_ea_ecdm_element_map[erwin_name])
            else:
                self.log_message("missing erwin element in sparx" + erwin_name)


        exporter.close_spreadsheet()

    def reconcile_ecdm(self):
        """
        compare the ecdm from xmi and sparx(mapped in extract_ECDM_guids)
         to come up with a 'diff' report
        :return:
        """
        if not (len(self.ea_ecdm_element_map) and len(self.ea_ecdm_relationship_map) and len(self.erwin_generalization_map) and
            len(self.erwin_relationship_map) and len(self.erwin_class_map) and len(self.erwin_package_map)):
            self.log_message("don't have all the maps to do a reconciliation")
            return

        # the order of add/change/delete is important.
        # relationships must come after entities

    def open_eap(self):
        # define options for opening the EAP file
        filename = None
        options = {'defaultextension': '.eap',
                   'filetypes': (('eap', '.eap'),),
                   'initialdir': 'C:\\HOME\\var\\projects\\python\EAAuto',
                   'initialfile': 'myfile.eap',
                   'parent': self.master,
                   'title': 'Open Sparx database'}
        filename = askopenfilename(**options)
        if filename:
            self.eaDB = EADatabase.EAdatabase(filename, self.log_message)
        else:
            self.log_message("Problem with opening the Sparx Database")

    def close_eap(self):
        self.eaDB.stop_db()

    def open_excel_ai(self):
        filename = None
        options = {'defaultextension': '.xlsx',
                   'filetypes': (('xls', '.xls'), ('xlsx', '.xlsx')),
                   'initialdir': 'C:\\HOME\\var\\projects\\python',
                   'initialfile': 'myfile.xlsx',
                   'parent': self.master,
                   'title': 'Open excel Application Inventory file'}
        filename = askopenfilename(**options)
        return filename

    def log_message(self, log_message):
        numlines = self.log_widget.index('end - 1 line').split('.')[0]
        self.log_widget.config(state=NORMAL)
        if numlines == 24:
            self.log_widget.delete(1.0, 2.0)
        if self.log_widget.index('end-1c') != '1.0':
            self.log_widget.insert('end', '\n')
        self.log_widget.insert('end', log_message)
        self.log_widget.config(state=DISABLED)

    def initUI(self, master):
        frame = Frame(master, bd=2, relief=SUNKEN)
        # frame.pack(fill=BOTH, expand=1)

        self.log = Text(frame)
        self.log.config(state=DISABLED)

        self.master.title("EAP Automation tool")
        menubar = Menu(self.master)
        self.master.config(menu=menubar)

        fileMenu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="File", menu=fileMenu)
        fileMenu.add_command(label="Open EAP", command=self.open_eap)
        fileMenu.add_command(label="Close EAP", command=self.close_eap)
        fileMenu.add_command(label="Exit", command=sys.exit)

        processmenu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="Process", menu=processmenu)
        processmenu.add_command(label="reconcile Applications",
                                command=self.reconcile_applications)
        processmenu.add_command(label="reconcile ERWIN", command=self.reconcile_ecdm)
        processmenu.add_command(label="update AHC",
                                command=self.update_AHC)

        extract_menu = Menu(menubar, tearoff=0)
        menubar.add_cascade(label="Extract", menu=extract_menu)
        extract_menu.add_command(label="Sparx ECDM GUIDs",
                                 command=self.extract_ECDM_guids)

        # the log widget
        self.log_widget = ScrolledText(master, bg='light cyan')
        self.log_widget.config(state=DISABLED)
        self.log_widget.pack(padx=10, pady=10, fill=BOTH, expand=True)

    def compare_ahc_to_sparx(self):
        """
        with the provided EA Database and Spreadsheet run through the application inventory secion
        of the database and updtate the Application Healthcheck tag and cloud tags.
        If the tags do not exist, then create them
        """
        self.log_message("nothing happening here, moving along")
        return

    def compare_ai_to_sparx(self):
        """
        wth the provided EA database and Spreadsheet, run through the
        Application Inventory section of the EA Database and display a 'diff' report
        TODO: this diff is currently just a dump to the log window. Provide better formatting and also excel output
        :type self: object
        """

        self.log_message("processing AI against Sparx")

        if not self.application_inventory_map_excel:
            self.log_message("the excel table is empty - nothing to reconcile")
            return

        if not self.application_inventory_map_eap:
            self.log_message("the Sparx table is empty - nothing to reconcile")
            return

        self.set_excel = set(self.application_inventory_map_excel.keys())
        self.set_eap = set(self.application_inventory_map_eap.keys())
        self.set_intersect = self.set_excel.intersection(self.set_eap)

        self.log_message("comparing Excel to Sparx")
        self.log_message("========================")
        # now iterate through the excel file and compare to the Sparx database
        for excel_key in self.set_excel:
            if excel_key not in self.set_eap:
                excel_app_record = self.application_inventory_map_excel[
                    excel_key]
                if excel_app_record[2] == 'Production':
                    self.log_message("    ID= " + excel_key + " not in EA")

        self.log_message("comparing Sparx to Excel")
        self.log_message("========================")
        # now iterate through the excel file and compare to the Sparx database
        for sparx_key in self.set_eap:
            if sparx_key not in self.set_excel:
                self.log_message("   ID= " + sparx_key + " not in AI")

        self.log_message("completed processing")
        self.log_message("====================")
コード例 #51
0
ファイル: endnotegui.py プロジェクト: siriusdemon/pyendnote
    map_F = 1
    docs = []
    ## 以下三个参数为网络分析参数
    degree = 6
    label_size = 6
    label_alpha = 1.0
    edge_width=2
    node_size=70
    df_old = 0
    edgelist = 0
    root = Tk()
    root.title('文献助手 0w0')
    menu = makemenu(root)
    var = makeFormRow(root,'文件路径')
    text = ScrolledText(root)
    text.config(width=100)
    text.pack(expand=YES,fill=BOTH)
    root.mainloop()

"""
备注文档:

全局变量:
filename  引用endnote导出格式的处理文档
ffilter   引用自定义关键词过滤
fmap      引用自定义关键词映射
var       通过var.get()得到处理文档的文件名
vfilter   通过.get()方法得到保留词集.csv
vmap      通过.get()方法得到映射词集.csv
docs      处理文档后得到的文件对象
text      指示主界面的Text控件
コード例 #52
0
class CipherGUI(Frame):
    """
    Renders a GUI that allows enciphering/deciphering of text using Bruce Schneier's solitaire algorithm.
    """
    
    def __init__(self, parent):
        """
        Initializes the GUI elements.
        """
        Frame.__init__(self, parent)
        self.parent = parent
        self.parent.title("Solitaire Cipher")

        self.helpFile = open("help.dat", "r")
        self.helpText = self.helpFile.read()

        self.aboutFile = open("about.dat", "r")
        self.aboutText = self.aboutFile.read()

        self.toCipher = Text(self.parent, undo = 1)
        self.toCipher.grid(row = 1, column = 1, padx = 10, pady = 10)
        self.toCipher.insert(END, "Type text to encipher...")
        self.toDecipher = Text(self.parent, undo = 1)
        self.toDecipher.grid(row = 2, column = 1, padx = 10, pady = 10)
        self.toDecipher.insert(END, "Type text to decipher...")
       
        lockImage = PhotoImage(file = "lock.gif")
        unlockImage = PhotoImage(file = "unlock.gif")
        self.encipherButton = Button(self.parent, text = "Encipher", command = self._encode, padx = 10, pady = 10, image = lockImage, compound = TOP)
        self.decipherButton = Button(self.parent, text = "Decipher", command = self._decode, padx = 10, pady = 10, image = unlockImage, compound = TOP)
        #Due to weirdness with Tk's handling of image references, need to keep a throwaway reference
        #to maintain iamge icons
        self.encipherButton.image = lockImage
        self.encipherButton.grid(row = 1, column = 2, padx = 10, pady = 10)
        self.decipherButton.image = unlockImage
        self.decipherButton.grid(row = 2, column = 2, padx = 10, pady = 10)

        splashImage = PhotoImage(file = "splash.gif")
        self.splashLabel = Label(self.parent, text = "Solitaire Cipher v1.0", image = splashImage, compound = TOP, font = "Courier")
        self.splashLabel.image = splashImage
        self.splashLabel.grid(row = 2, column = 0, padx = 10)

        self.log = ScrolledText(self.parent, width = 30, height = 22)
        #Can't use console log method yet.
        self.log.insert(END, ">> Ready. View Help for entry rules.")
        self.log.state = DISABLED
        self.log.grid(row = 1, column = 0, padx = 10, pady = 10, sticky = S)
        self.log.config(state = DISABLED)

        self.passphrase = Entry(self.parent, show = "*", width = 30)
        self.passphrase.grid(row = 1, column = 0, padx = 10, pady = 10, sticky = NE)
        self.passphrase.xview_moveto(0)
        self.passphraseLabel = Label(self.parent, text = "Passcode:", padx = 8).grid(row = 1, column = 0, sticky = NW, pady = 10)

        self.menubar = Menu(self.parent)
        self.menubar.add_command(label = "About", command = self._display_about)
        self.menubar.add_command(label = "Help", command = self._display_help)
        self.menubar.add_command(label = "Quit", command = self.quit)
        self.parent.config(menu = self.menubar)

        self.parent.iconbitmap("cards-64.ico")

    def _console_log(self, message):
        """
        Logs events like decode/encode to the console.
        """
        self.log.config(state = NORMAL)
        self.log.insert(END, "\n>> " + message)  
        self.log.config(state = DISABLED)
        self.log.see(END)

    def _encode(self):
        """
        Encodes the contents of toCipher using Cipher class and places in toDecipher.
        """
        passkey = self.passphrase.get()
        #If text is retrived to END, newline is added. Must go 1 character less.
        message = self.toCipher.get(1.0, END+"-1c")
        if self._validate(message, passkey):
            passkey = passkey.upper()
            message = message.replace(" ", "").upper()
            encode = Cipher(message, passkey)
            encodedMessage = encode.encipher()
            self._console_log("Encoding successful. \nSee lower box for result.")
            self.toDecipher.delete(1.0, END)
            self.toDecipher.insert(END, encodedMessage)
        elif passkey == "":
            self._console_log("Error: no passcode entered.")
        elif message == "":
            self._console_log("Error: no message entered.")
        else:
            self._console_log("Encoding unsuccessful. \nInput contains one or more \nillegal characters. See Help \nfor rules.")

    def _decode(self):
        """
        Decodes the contents of toDecipher using Cipher class and places in toCipher.
        """
        passkey = self.passphrase.get()
        #If text is retrived to END, newline is added. Must go 1 character less.
        message = self.toDecipher.get(1.0, END+"-1c")
        if self._validate(message, passkey):
            passkey = passkey.upper()
            message = message.replace(" ", "").upper()
            decode = Cipher(message, passkey)
            decodedMessage = decode.decipher()
            self._console_log("Decoding successful. \nSee upper box for result.")
            self.toCipher.delete(1.0, END)
            self.toCipher.insert(END, decodedMessage)
        elif passkey == "":
            self._console_log("Error: no passcode entered.")
        elif message == "":
            self._console_log("Error: no message entered.")
        else:
            self._console_log("Decoding unsuccessful. \nInput contains one or more \nillegal characters. See Help \nfor rules.")

    def _validate(self, message, passkey):
        """
        Checks text input from toCipher, toDecipher, and passphrase fields for illegal characters during cipher/decipher processes.
        """
        passkeyOK = passkey.isalpha()
        messageOK = message.replace(" ", "").isalpha()
        return passkeyOK and messageOK

    def _display_help(self):
        """
        Displays help dialog on menu press.
        """
        help = Toplevel()
        help.grab_set()
        help.title("Help")
        help.resizable(0,0)
        help.iconbitmap("cards-64.ico")
        helpMessage = Message(help, text = self.helpText, padx = 10, pady = 10)
        helpMessage.pack()


    def _display_about(self):
        """
        Displays about dialog on menu press.
        """
        about = Toplevel()
        about.grab_set()
        about.title("About")
        about.resizable(0,0)
        about.iconbitmap("cards-64.ico")
        aboutMessage = Message(about, text = self.aboutText, padx = 10, pady = 10)
        aboutMessage.pack()
コード例 #53
0
ファイル: queuetest-gui.py プロジェクト: death-finger/Scripts
        time.sleep(1)
        print('put')
        dataQueue.put('[producer id=%d, count=%d]' % (id, i))
        root.insert('end', 'producer: produce id/count => %d/%d\n' % (id, i))
        root.see('end')

def consumer(root):
    try:
        print('get')
        data = dataQueue.get(block=False)
    except queue.Empty:
        pass
    else:
        root.insert('end', 'consumer got =>%s\n' % str(data))
        root.see('end')
    root.after(100, lambda: consumer(root))

def makethreads(root):
    for i in range(4):
        _thread.start_new_thread(producer, (i, root))

if __name__ == '__main__':
    from tkinter.scrolledtext import ScrolledText
    root = ScrolledText()
    root.pack()
    root.config(font=('courier', 14, 'bold'))
    root.bind('<Button-1>', lambda event: makethreads(root))
    consumer(root)
    root.mainloop()

コード例 #54
0
ファイル: rest.py プロジェクト: nenodias/tkinter-rest-client
class Rest(ttk.Frame):

    GET = 'GET'
    POST = 'POST'
    PUT = 'PUT'
    DELETE = 'DELETE'
    OPTIONS = 'OPTIONS'
    TRACE = 'TRACE'
    HEAD = 'HEAD'

    def __init__(self, root, *args, **kwargs):
        super(Rest, self).__init__(*args, **kwargs)
        self.pack()

        menubar = tkinter.Menu(root)
        menu_arquivo = tkinter.Menu(menubar, tearoff=0)
        
        menubar.add_cascade(label="Arquivo", menu=menu_arquivo)
        menu_arquivo.add_command(label="Novo", command=self.novo_arquivo)
        menu_arquivo.add_command(label="Abrir", command=self.abrir_arquivo)
        menu_arquivo.add_command(label="Salvar", command=self.salvar_arquivo)
        menu_arquivo.add_command(label="Sair",command=root.quit)

        root.config(menu=menubar)

        self.url = tkinter.StringVar()

        self.frame_url = ttk.Frame(self)
        self.frame_url.pack()
        self.lbl_url_entry = tkinter.Label(self.frame_url,text='URL')
        self.lbl_url_entry.pack(side=tkinter.LEFT)
        self.url_entry = tkinter.Entry(self.frame_url,textvariable=self.url, width=80)
        self.url_entry.pack(side=tkinter.LEFT)
        
        
        self.metodo = tkinter.StringVar()
        self.metodos_combo = ttk.Combobox(self.frame_url, textvariable=self.metodo, width=8)
        self.metodos_combo.bind("<<ComboboxSelected>>", self.metodo_select)
        self.metodos_combo['values'] = (Rest.GET, Rest.POST,Rest.PUT, Rest.DELETE, Rest.OPTIONS, Rest.TRACE, Rest.HEAD)
        self.metodos_combo.pack(side=tkinter.LEFT)
        self.metodos_combo.state(['readonly'])
        self.metodo.set( self.metodos_combo['values'][0] )
        

        self.botao_ir = ttk.Button( self.frame_url, text='IR', command=self.request)
        self.botao_ir.pack(side=tkinter.LEFT)

        self.frame_header = ttk.Frame(self)
        self.frame_header.pack(fill=tkinter.X, padx=5, pady=2)
        self.lbl_headers = tkinter.Label(self.frame_header,text='Headers')
        self.lbl_headers.pack(side=tkinter.LEFT)
        self.botao_addheader = ttk.Button( self.frame_header, text='+', command=self.add_header)
        self.botao_addheader.pack(side=tkinter.RIGHT)

        self.headers_canvas = tkinter.Canvas(self, borderwidth=0, height=100)

        self.frame_headers = ttk.Frame(self.headers_canvas)
        self.frame_headers.pack()

        #Scrollbar
        self.scroll_bar_y = tkinter.Scrollbar(self, orient=tkinter.VERTICAL, command=self.headers_canvas.yview)
        self.headers_canvas.configure(yscrollcommand=self.scroll_bar_y.set)
        self.scroll_bar_y.pack(side=tkinter.RIGHT, fill=tkinter.Y)

        self.scroll_bar_x = tkinter.Scrollbar(self, orient=tkinter.HORIZONTAL, command=self.headers_canvas.xview)
        self.headers_canvas.configure(xscrollcommand=self.scroll_bar_x.set)
        self.scroll_bar_x.pack(side=tkinter.BOTTOM, fill=tkinter.X)

        self.headers_canvas.pack(side=tkinter.LEFT, fill=tkinter.BOTH, expand=True)
        self.headers_canvas.create_window((1,1), window=self.frame_headers, anchor="nw", tags="self.frame_headers")
        self.frame_headers.bind("<Configure>", self.on_frame_configure)

        self.lista_headers = []

        frame_keyvalue = tkinter.Frame(self.frame_headers)
        frame_keyvalue.pack()
        header1 = tkinter.Label(frame_keyvalue, text='Header')
        header1.pack(side=tkinter.LEFT)
        value_header1 = tkinter.Label(frame_keyvalue, text='Valor')
        value_header1.pack(side=tkinter.LEFT)


        lbl_body = tkinter.Label(root, text='Body')
        lbl_body.pack()

        self.body = ScrolledText(root, height=10, width=100)
        self.body.pack()

        lbl_retorno = tkinter.Label(root, text='Retorno')
        lbl_retorno.pack()

        self.retorno = ScrolledText(root, height=18, width=100)
        self.retorno.pack()

        self.metodo_select()#Bloqueando o Body para edição

        self.lbl_request = tkinter.Label(root,text='')
        self.lbl_request.pack()

    def metodo_select(self, value=None):
        metodo = self.metodo.get()
        if metodo == Rest.POST or metodo == Rest.PUT:
            self.body.config(state=tkinter.NORMAL)
        elif metodo == Rest.GET or metodo == Rest.DELETE:
            self.body.config(state=tkinter.DISABLED)

    def remove_header(self, chave, frame):
        for item in self.lista_headers:
            if item[0] == chave:
                self.lista_headers.remove(item)
                frame.destroy()

    def add_header(self, key='', value=''):
        chave = tkinter.StringVar()
        chave.set(key)
        valor = tkinter.StringVar()
        valor.set(value)
        frame_keyvalue = tkinter.Frame(self.frame_headers)
        frame_keyvalue.pack()
        header1 = tkinter.Entry(frame_keyvalue,textvariable=chave)
        header1.pack(side=tkinter.LEFT)
        value_header1 = tkinter.Entry(frame_keyvalue,textvariable=valor)
        value_header1.pack(side=tkinter.LEFT)
        botao_remover = tkinter.Button(frame_keyvalue, text='-',command=lambda: self.remove_header(chave, frame_keyvalue))
        botao_remover.pack(side=tkinter.LEFT)

        self.lista_headers.append( (chave, valor, frame_keyvalue) )

    def on_frame_configure(self, event):
        '''Reset the scroll region to encompass the inner frame'''
        self.headers_canvas.configure(scrollregion=self.headers_canvas.bbox("all"))

    def get_headers(self):
        headers = {}
        for keyValue in self.lista_headers:
            headers[ keyValue[0].get() ] = keyValue[1].get()
        return headers

    def get_data(self):
        return self.body.get(0.0,tkinter.END)

    def request(self):
        resposta = ''
        try:
            metodo = self.metodo.get()
            headers = self.get_headers()
            if metodo == Rest.POST:
                data = self.get_data()
                resposta = r.post(self.url.get(), headers=headers, data=data)
            elif metodo == Rest.GET:
                resposta = r.get(self.url.get(), headers=headers)
            elif metodo == Rest.PUT:
                data = self.get_data()
                resposta = r.put(self.url.get(), headers=headers, data=data)
            elif metodo == Rest.DELETE:
                resposta = r.delete(self.url.get(), headers=headers)
            elif metodo == Rest.OPTIONS:
                resposta = r.options(self.url.get(), headers=headers)
            elif metodo == Rest.TRACE:
                resposta = r.trace(self.url.get(), headers=headers)
            elif metodo == Rest.HEAD:
                resposta = r.head(self.url.get(), headers=headers)
        except Exception as ex:
            print(ex)
            resposta = ex.message
        self.tratar_resposta(resposta)

        self.retorno.delete(0.0,tkinter.END)
        try:
            load = json.loads(resposta.text)
            self.retorno.insert(tkinter.END, json.dumps(load, indent=4, sort_keys=True) )
        except:
            soup = BeautifulSoup(resposta.text)
            self.retorno.insert(tkinter.END, soup.prettify() )

    def tratar_resposta(self, resposta):
        try:
            texto = 'Status: {0}\n'.format(resposta.status_code)
            texto += 'Headers:\n'
            for key in resposta.headers.keys():
                texto += '\t {0}:{1}\n'.format(key, resposta.headers[key])
            texto += 'Encoding:{0}\n'.format(resposta.encoding)
            self.lbl_request['text'] = texto
        except Exception as ex:
            print(ex)
            self.lbl_request['text'] = 'Erro'

    def abrir_arquivo(self):
        arquivo = askopenfilename(title='Escolher arquivo',filetypes=( ("JSON File", "*.json"), )  )
        if arquivo:
            self.novo_arquivo() # Limpa os campos
            arquivo_json = None
            with open(arquivo, 'r') as configuracao:
                arquivo_json = configuracao.read()
            arquivo_json = json.loads(arquivo_json)
            self.url.set( arquivo_json['url'] )
            if arquivo_json['method']:
                if arquivo_json['method'] == Rest.GET:
                    self.metodo.set( Rest.GET )
                elif arquivo_json['method'] == Rest.POST:
                    self.metodo.set( Rest.POST )
                elif arquivo_json['method'] == Rest.PUT:
                    self.metodo.set( Rest.PUT )
                elif arquivo_json['method'] == Rest.DELETE:
                    self.metodo.set( Rest.DELETE )
                elif arquivo_json['method'] == Rest.OPTIONS:
                    self.metodo.set( Rest.OPTIONS )
                elif arquivo_json['method'] == Rest.TRACE:
                    self.metodo.set( Rest.TRACE )
                elif arquivo_json['method'] == Rest.HEAD:
                    self.metodo.set( Rest.HEAD )
            self.metodo_select()
            if arquivo_json['data']:
                self.body.delete(0.0,tkinter.END)
                self.body.insert(tkinter.END, arquivo_json['data'])
            if 'headers' in arquivo_json:
                for key in arquivo_json['headers'].keys():
                    self.add_header(key=key, value=arquivo_json['headers'][key])

    def novo_arquivo(self):
        self.url.set('')
        self.body.delete(0.0,tkinter.END)
        self.retorno.delete(0.0,tkinter.END)
        self.lbl_request['text'] = ''
        self.metodo.set( Rest.GET )
        while True:
            if self.lista_headers:
                item = self.lista_headers[0]
                key = item[0]
                frame = item[2]
                self.remove_header( key, frame )
            else:
                break

    def salvar_arquivo(self):
        arquivo_destino = asksaveasfilename(title='Salvar JSON do Request', filetypes=[('JSON File','*.json')])
        if arquivo_destino:
            dicionario = {}
            dicionario['headers'] = self.get_headers()
            dicionario['data'] = self.get_data()
            dicionario['method'] = self.metodo.get()
            dicionario['url'] = self.url.get()
            with open(arquivo_destino, 'w') as destino:
                destino.write( json.dumps(dicionario) )
                messagebox.showinfo('Rest', 'Arquivos salvo com sucesso')