Пример #1
0
    def __init__(self, command=None):
        self.topic_list = None
        outsideFrame = Frame()
        outsideFrame.config(padx=10, pady=10)
        outsideFrame.grid(row=1, column=0, sticky="wn")

        self.frame = LabelFrame(outsideFrame, text="Topics")
        self.frame.config(font=("Arial", 14), padx=10, pady=10)
        self.frame.grid(row=0, column=0)
        self._command = command

        self.topic_filter_input = Entry(self.frame, width=33)
        self.topic_filter_input.grid(row=0, column=0, pady=10)
        self.topic_filter_input.bind("<KeyRelease>", self.filter_topic)

        treeFrame = Frame(self.frame)
        treeFrame.grid(row=1, column=0)
        self.tree = Treeview(treeFrame, style="Custom.Treeview")
        self.tree.heading('#0', text='Topic')
        self.tree.pack()
        self.tree.bind("<ButtonRelease-1>", self.OnClick)
        self.tree.tag_configure('odd', background='#f9f9f9')
        self.tree.tag_configure('even', background='#DFDFDF')

        scroll_bar = Scrollbar(self.frame,
                               orient="vertical",
                               command=self.tree.yview)
        scroll_bar.grid(row=1, column=1, sticky='nsew')
        self.tree.configure(yscrollcommand=scroll_bar.set)
    def right_frame(parent):
        rf_width = 300
        rf_height = 360
        # right side frame
        frame_right = LabelFrame(
            parent.building_pos_window,
            text="Building Position",
            width=rf_width - 10,
            height=rf_height - 10,
        )

        frame_right.grid_rowconfigure(0, weight=1)
        frame_right.grid_columnconfigure(0, weight=1)
        frame_right.grid_propagate(False)

        canvas_right = Canvas(frame_right)
        canvas_right.grid(row=0, column=0, sticky=N + W)

        # Link a scrollbar to the canvas
        def on_mousewheel(event):
            canvas_right.yview_scroll(int(-1 * (event.delta / 120)), "units")

        def bound_to_mousewheel(event):
            canvas_right.bind_all("<MouseWheel>", on_mousewheel)

        def unbound_to_mousewheel(event):
            canvas_right.unbind_all("<MouseWheel>")

        y_scrollbar = Scrollbar(frame_right,
                                orient="vertical",
                                command=canvas_right.yview)
        y_scrollbar.grid(row=0, column=1, sticky='ns')
        canvas_right.configure(yscrollcommand=y_scrollbar.set)

        inner_frame_right = Frame(canvas_right)
        inner_frame_right.bind('<Enter>', bound_to_mousewheel)
        inner_frame_right.bind('<Leave>', unbound_to_mousewheel)

        canvas_right.create_window((0, 0),
                                   window=inner_frame_right,
                                   anchor='nw')

        idx = 0
        for e_name in BuildingNames:
            building_name_xy_config_frame(
                inner_frame_right, idx, e_name.value,
                parent.bot_building_pos.get(e_name.value, [-1, -1])
                if parent.bot_building_pos is not None else [-1, -1])
            idx = idx + 1

        inner_frame_right.update_idletasks()

        frame_right.config(width=rf_width - 10, height=360 - 10)
        canvas_right.config(width=rf_width - 10,
                            height=360 - 10,
                            scrollregion=canvas_right.bbox("all"))

        frame_right.grid(row=0, column=1, padx=5, pady=5, sticky=N + W)

        return inner_frame_right
Пример #3
0
def read_p3(token):
    next_token = lambda: next(token)
    assert 'P3' == next_token(), 'Invalid PPM type'

    width, height, max_value = (int(next_token()) for i in range(3))
    root = Tk()
    image = PhotoImage(width=width, height=height)
    for h in range(0, height):
        for w in range(0, width):
            if max_value is 255:
                mask = '#%02x%02x%02x'
            else:
                mask = '#%04x%04x%04x'

            color = mask % tuple(int(next_token()) for i in range(3))
            image.put(color, (w, h))

    canvas = Canvas(root, width=600, height=500)
    canvas.grid(row=0, column=0, sticky='news')
    vertical_scrollbar = Scrollbar(root,
                                   orient='vertical',
                                   command=canvas.yview)
    vertical_scrollbar.grid(row=0, column=1, sticky='nes')
    horizontal_scrollbar = Scrollbar(root,
                                     orient='horizontal',
                                     command=canvas.xview)
    horizontal_scrollbar.grid(row=1, column=0, sticky='ews')
    canvas.configure(yscrollcommand=vertical_scrollbar.set)
    canvas.configure(xscrollcommand=horizontal_scrollbar.set)
    canvas.create_image(0, 0, image=image, anchor=NW)

    root.update()
    root.minsize(root.winfo_width(), root.winfo_height())
    root.mainloop()
Пример #4
0
    def createWidgets(self):
        "Create initial widget set."

        # Objects
        title = Label(self, text='Bandwidth (Gb/s)', bg=self.bg)
        width = self.gwidth
        height = self.gheight
        scale = self.createScale()
        graph = Canvas(self, width=width, height=height, background=self.bg)
        xbar = Scrollbar(self, orient='horizontal', command=graph.xview)
        ybar = Scrollbar(self, orient='vertical', command=self.yview)
        graph.configure(xscrollcommand=xbar.set,
                        yscrollcommand=ybar.set,
                        scrollregion=(0, 0, width, height))
        scale.configure(yscrollcommand=ybar.set)

        # Layout
        title.grid(row=0, columnspan=3, sticky='new')
        scale.grid(row=1, column=0, sticky='nsew')
        graph.grid(row=1, column=1, sticky='nsew')
        ybar.grid(row=1, column=2, sticky='ns')
        xbar.grid(row=2, column=0, columnspan=2, sticky='ew')
        self.rowconfigure(1, weight=1)
        self.columnconfigure(1, weight=1)
        return title, scale, graph
Пример #5
0
 def __init__(self, *args, **kwargs):
     Page.__init__(self, *args, **kwargs)
     photo = PhotoImage(file=resource_path("home.gif"))
     photolab = Label(self, image=photo)
     photolab.image = photo
     photolab.grid(row=0, column=2, columnspan=2, sticky='nwes')
     self.listNodes = Listbox(self,
                              width=35,
                              height=15,
                              font=("Courier", 10))
     self.listNodes.grid(row=1, column=1, columnspan=4, rowspan=2)
     scrollbar = Scrollbar(self, orient="vertical")
     scrollbar.config(command=self.listNodes.yview)
     scrollbar.grid(row=1, column=4, rowspan=2, sticky='ns')
     self.listNodes.config(yscrollcommand=scrollbar.set)
     self.lis = [k for k in DATA.keys()]
     self.variable = StringVar(self)
     self.variable.set(self.lis[0])
     self.variable2 = StringVar(self)
     self.variable2.set(self.lis[-1])
     self.opt1 = OptionMenu(self, self.variable, *self.lis)
     self.opt2 = OptionMenu(self, self.variable2, *self.lis)
     l1 = Label(self, text="From :", font=("Courier", 12))
     l2 = Label(self, text="To :", font=("Courier", 12))
     l1.grid(row=4, column=2)
     self.opt1.grid(row=4, column=3)
     l2.grid(row=5, column=2)
     self.opt2.grid(row=5, column=3)
     refb = Button(self,
                   text="Refresh!",
                   font=("Courier", 12),
                   command=self.refresh)
     refb.grid(row=5, column=4)
Пример #6
0
    def createCanvas(self):
       f = Frame(self)
       canvas = Canvas(f, width=self.canvasH, height=self.canvasH, bg='white')

       xbar = Scrollbar( f, orient='horizontal', command=canvas.xview )
       ybar = Scrollbar( f, orient='vertical', command=canvas.yview )
       canvas.configure( xscrollcommand=xbar.set, yscrollcommand=ybar.set )

       # Resize box
       resize = Label( f, bg='white' )
       # Layout
       canvas.grid( row=0, column=1, sticky='nsew')
       ybar.grid( row=0, column=2, sticky='ns')
       xbar.grid( row=1, column=1, sticky='ew' )
       resize.grid( row=1, column=2, sticky='nsew' )

       # Resize behavior
       f.rowconfigure( 0, weight=1 )
       f.columnconfigure( 1, weight=1 )
       f.grid( row=0, column=0, sticky='nsew' )
       f.bind( '<Configure>', lambda event: self.updateScrollRegion() )  

       # Mouse bindings

       canvas.bind( '<ButtonPress-1>', self.clickCanvas )
       canvas.bind( '<B1-Motion>', self.dragCanvas )
       canvas.bind( '<ButtonRelease-1>', self.releaseCanvas )
       
       return f, canvas
Пример #7
0
 def __init__(self,appli):
     self.appli=appli
     fenetre=fenetre_freqlex()
     #On crée les  polices
     police_licence=font.Font(fenetre, size=16, family='Courier')  
     #Ce cadre contient le texte de la licence
     cadre_licence = LabelFrame(fenetre, width=200, height=600, borderwidth=2,
                             relief=GROOVE,text="Licence utilisateur")
     asc_licence=Scrollbar(cadre_licence,orient=VERTICAL)
     texte_licence = Text(cadre_licence, wrap=WORD,font=police_licence)
     fichier_licence=open('Licence')
     texte_licence.insert(END,fichier_licence.read())
     texte_licence.config(state=DISABLED)
     ## association du déplacement de la glissière des scrollbar avec la position visible dans  
     ## le widget Text et inversement.  
     asc_licence.config(command = texte_licence.yview) 
     texte_licence.config(yscrollcommand = asc_licence.set)
     ##Boutons
     bouton_refuse=Button(text="Je refuse cette licence.",command=quit)
     bouton_accepte=Button(text="J'accepte cette licence.",command=self.accepter)
     bouton_questionnaire=Button(text="J'accepte cette licence et je soutiens ce projet en remplissant un questionnaire.",command=self.questionnaire)
     ## Placement du widget Text et des Scrollbar associés 
     texte_licence.grid(column=0, row=0) 
     asc_licence.grid(column=1, row=0, sticky=S+N)
     cadre_licence.grid(column=0,row=0,columnspan=3)
     bouton_refuse.grid(column=0,row=1)
     bouton_accepte.grid(column=1,row=1)
     bouton_questionnaire.grid(column=2,row=1)
     self.fenetre=fenetre
     fenetre.mainloop()
 def addScrollbar(self):
     sbar = Scrollbar(self.parent,
                      orient='vertical',
                      command=self.yview,
                      width=16)
     self.configure(yscrollcommand=sbar.set)
     sbar.grid(row=0, column=1)
Пример #9
0
 def _create_scroll(master, canvas):
     scroll = Scrollbar(master, orient='vertical', command=canvas.yview)
     scroll.grid(row=0, column=1, sticky='ns')
     canvas.config(yscrollcommand=scroll.set,
                   highlightthickness=0,
                   bg='green')
     return scroll
Пример #10
0
    def configure_tab(self, channel_name):
        self.channels.add(channel_name)

        tab = ttk.Frame(self.tab_parent)
        self.tab_parent.add(tab, text=channel_name)

        scrollbar = Scrollbar(tab)

        messages = Listbox(tab, yscrollcommand=scrollbar.set, height=15, width=50)
        messages.grid(row=0, column=0, sticky=N + S + W + E)
        self.channel_name_to_messages[channel_name] = messages

        scrollbar.grid(row=0, column=1, sticky=N + S)
        scrollbar.config(command=messages.yview)

        input_user = StringVar()
        self.channel_name_to_input_user[channel_name] = input_user

        input_field = Entry(tab, text=input_user)
        input_field.grid(row=1, column=0, sticky=W+E+S)
        self.channel_name_to_input_field[channel_name] = input_field

        send_button = Button(tab, text="Send", command=lambda: self.send_message(channel_name))
        send_button.grid(row=1, column=1, sticky=S)

        input_field.bind("<Return>", lambda key: self.send_message(channel_name))

        input_field.focus()
Пример #11
0
    def __init__(self):
        super().__init__()
        # -----------------------------------------INPUT--------------------------------------------------
        global inputText
        inputFrame = LabelFrame(self, bd=0, text='Ввод текста')
        inputText = Text(inputFrame, height=8, width=80, wrap=WORD)
        # -------------------------------------------OUTPUT------------------------------------------------
        global outputText
        outputFrame = LabelFrame(self, bd=0, text='Вывод словаря')
        outputText = Listbox(outputFrame, height=10, width=120)
        scrollb = Scrollbar(outputFrame, command=outputText.yview)
        scrollb.grid(row=4, column=5, sticky='nsew')
        outputText.grid(row=4, column=0, sticky='nsew', columnspan=5)
        outputText.configure(yscrollcommand=scrollb.set)
        # ------------------------------------------MENU---------------------------------------------------
        mainMenu = Menu(self)
        fileSubMenu = Menu(mainMenu, tearoff=0)
        fileSubMenu.add_command(label="Новый файл", command=newFile)
        fileSubMenu.add_command(label="Открыть...", command=openFile)
        fileSubMenu.add_command(label="Сохранить...", command=saveFile)
        fileSubMenu.add_command(label="Печать...", command=printFile)
        fileSubMenu.add_command(label="Выход", command=self.exitFile)

        helpSubMenu = Menu(mainMenu, tearoff=0)
        helpSubMenu.add_command(label="Помощь", command=helpMenu)
        helpSubMenu.add_command(label="О программе", command=aboutProgramMenu)

        mainMenu.add_cascade(label="Файл", menu=fileSubMenu)
        mainMenu.add_cascade(label="Справка", menu=helpSubMenu)
        self.config(menu=mainMenu)
        # ------------------------------------------Buttons---------------------------------------------------
        buttonsFrame = Frame(self, bd=5)
        addWordsButton = Button(buttonsFrame,
                                text='Добавить',
                                width=25,
                                height=2)
        addWordsButton.config(command=addWord)
        addWordsButton.pack(side='left')
        spaceLabel1 = Label(buttonsFrame, width=7, height=2)
        spaceLabel1.pack(side='left')
        addWordsButton = Button(buttonsFrame,
                                text='Очистить',
                                width=25,
                                height=2)
        addWordsButton.config(command=cleanWord)
        addWordsButton.pack(side='left')
        spaceLabel2 = Label(buttonsFrame, width=7, height=2)
        spaceLabel2.pack(side='left')
        generateNewWordsButton = Button(buttonsFrame,
                                        text='Сгенерировать',
                                        width=25,
                                        height=2)
        generateNewWordsButton.config(command=generateWord)
        generateNewWordsButton.pack(side='left')
        self.title('Lab 1')
        outputFrame.pack()
        inputFrame.pack()
        inputText.pack()
        buttonsFrame.pack()
        self.geometry('800x400')
Пример #12
0
def add_scrolling_figure(figure, frame):

    canvas = Canvas(frame)

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

    x_scrollbar = Scrollbar(frame, orient=tk.HORIZONTAL)

    y_scrollbar = Scrollbar(frame)

    x_scrollbar.grid(row=1, column=0, sticky=tk.EW)

    y_scrollbar.grid(row=0, column=1, sticky=tk.NS)

    canvas.config(xscrollcommand=x_scrollbar.set)

    x_scrollbar.config(command=canvas.xview)

    canvas.config(yscrollcommand=y_scrollbar.set)

    y_scrollbar.config(command=canvas.yview)

    # plug in the figure

    fig_agg = FigureCanvasTkAgg(figure, canvas)

    mpl_canvas = fig_agg.get_tk_widget()

    mpl_canvas.grid(sticky=tk.NSEW)

    # and connect figure with scrolling region

    canvas.create_window(0, 0, window=mpl_canvas)

    canvas.config(scrollregion=canvas.bbox(tk.ALL))
Пример #13
0
def create_user_screen():
    '''Function to create the user screen.'''
    global transaction_text_widget
    global balance_var
    root.geometry('550x700')
    Label(text="FedUni Money Manager",
          font=("Helvetica", 22)).grid(row=0, columnspan=5)

    Label(text="User Number:" + " " + user.user_number,
          font=("Helvetica")).grid(row=1, column=0)

    balance_var.set("Balance: $" + str(user.balance))
    balance_label.grid(row=1, column=1)

    Label(text="AMount ($)", font=("Helvetica")).grid(row=2, column=0)
    Label(text="Entry Type", font=("Helvetica")).grid(row=3, column=0)
    logout_button = Button(text="Log Out", width=8, height=4)
    logout_button.grid(row=1, column=3)
    logout_button.bind('<Button-1>', save_and_log_out)
    deposit_button = Button(text="Deposit", width=8, height=4)
    deposit_button.grid(row=2, column=3)
    deposit_button.bind('<Button-1>', perform_deposit)
    entry_button = Button(text="Add Entry", width=8, height=4)
    entry_button.grid(row=3, column=3)
    entry_button.bind('<Button-1>', perform_transaction)
    amount_entry.grid(row=2, column=1)
    tkVar.set("Choose Entry")
    choices = set(item_types)
    item_menu = OptionMenu(root, tkVar, *choices)
    item_menu.grid(row=3, column=1)
    transaction_text_widget.grid(row=4, column=0, columnspan=5)
    scrollbar = Scrollbar(root, command=transaction_text_widget.yview)
    scrollbar.grid(row=4, column=4, sticky='nsew')
    transaction_text_widget['yscrollcommand'] = scrollbar.set
    transaction_text_widget.config(state=DISABLED)
Пример #14
0
class   Application(Frame): 
    def __init__(self,  master=None):
        Frame.__init__(self, master)    
        self.grid(sticky=N+S+E+W)   
        self.mainframe()

    def mainframe(self):                
        self.data = Listbox(self, bg='red')
        self.scrollbar = Scrollbar(self.data, orient=VERTICAL)
        self.data.config(yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.data.yview)

        for i in range(1000):
            self.data.insert(END, str(i))

        self.run = Button(self, text="run")
        self.stop = Button(self, text="stop")
    
        self.data.grid(row=0, column=0, rowspan=4,
                       columnspan=2, sticky=N+E+S+W)
        self.data.columnconfigure(0, weight=1)
    
        self.run.grid(row=4,column=0,sticky=EW)
        self.stop.grid(row=4,column=1,sticky=EW)
    
        self.scrollbar.grid(column=2, sticky=N+S)
Пример #15
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller
        shift = StringVar()
        known = BooleanVar()   # true -> shift key known

        self.columnconfigure(0, weight=1, pad=5)
        self.columnconfigure(1, weight=1, pad=5)

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

        # Title
        bbutton = Button(self, text="<", command=lambda: controller.show_frame("MainPage"))
        bbutton.grid(row=0, column=0, padx=10, sticky=W)
        title = Label(self, text="Caesar Cipher")
        title.grid(row=0, columnspan=2, padx=10)

        # Shift Key
        sframe = Frame(self)
        sentry = Entry(sframe, textvariable=shift, width=55)
        sentry.pack(side=LEFT)
        sentry.insert(0, "Shift key")
        cb = Checkbutton(sframe, text="Unknown key", variable=known)
        cb.select()
        cb.pack(side=RIGHT, padx=10)
        sframe.grid(row=1, columnspan=2, padx=10, sticky=W+E)

        # Text input
        tinput = Text(self, wrap=WORD)
        tinput.grid(row=2, columnspan=2, padx=10, pady=10, sticky=N+E+S+W)
        scrolli = Scrollbar(self, command=tinput.yview)
        tinput.configure(yscrollcommand=scrolli.set)
        scrolli.grid(row=2, column=1, pady=10, sticky=N+S+E)
        tinput.insert(1.0, "Input")
        tinput.bind("<Control-Key-a>", select_all)  # select-all Windows/Linux
        tinput.bind("<Command-Key-a>", select_all)  # select-all Mac

        # Encode/Decode buttons
        ebutton = Button(self, text="Encode", width=15)
        ebutton.grid(row=3, column=0, padx=10, sticky=E)
        ebutton.configure(command=lambda: self.encode_prep(tinput.get(1.0, 'end-1c'), shift.get()))
        dbutton = Button(self, text="Decode", width=15)
        dbutton.grid(row=3, column=1, padx=10, sticky=W)
        dbutton.configure(command=lambda: self.decode_prep(tinput.get(1.0, 'end-1c'), shift.get(), not known.get()))

        # Output box
        self.output = Text(self, wrap=WORD)
        self.output.grid(row=4, columnspan=2, padx=10, pady=10, sticky=N+E+S+W)
        self.output.bind("<1>", lambda event: self.output.focus_set())
        scrollo = Scrollbar(self, command=self.output.yview)
        scrollo.grid(row=4, column=1, pady=10, sticky=N+S+E)
        self.output.configure(yscrollcommand=scrollo.set)
        self.output.insert(1.0, "Output")
        self.output.configure(state="disabled")
        self.output.bind("<Control-Key-a>", select_all)    # select-all Windows/Linux
        self.output.bind("<Command-Key-a>", select_all)    # select-all Mac
Пример #16
0
 def _build_listbox(self, values):
     listbox_frame = Frame()
     self._listbox = Listbox(listbox_frame, background="white",
                             selectmode=SINGLE, activestyle="none",
                             exportselection=False)
     self._listbox.grid(row=0, column=0, sticky=N+E+W+S)
     self._listbox.bind("<ButtonRelease-1>",
                        self._update_entry_from_listbox)
     self._listbox.bind("<Return>", self._update_entry_from_listbox)
     self._listbox.bind("<Escape>", lambda event: self.unpost_listbox())
     self._listbox.bind('<Control-n>', self._next)
     self._listbox.bind('<Control-p>', self._previous)
     if self._use_vscrollbar:
         vbar = Scrollbar(listbox_frame, orient=VERTICAL,
                          command=self._listbox.yview)
         vbar.grid(row=0, column=1, sticky=N+S)
         self._listbox.configure(
             yscrollcommand=lambda f, l: autoscroll(vbar, f, l))
     elif self._use_hscrollbar:
         hbar = Scrollbar(listbox_frame, orient=HORIZONTAL,
                          command=self._listbox.xview)
         hbar.grid(row=1, column=0, sticky=E+W)
         self._listbox.configure(
             xscrollcommand=lambda f, l: autoscroll(hbar, f, l))
     listbox_frame.grid_columnconfigure(0, weight=1)
     listbox_frame.grid_rowconfigure(0, weight=1)
     x = -self.cget("borderwidth") - self.cget("highlightthickness")
     y = self.winfo_height()-self.cget("borderwidth") - \
         self.cget("highlightthickness")
     elif self._listbox_width:
         width = self._listbox_width
Пример #17
0
 def _initfilepanel(self):
     frame = Frame(self)
     frame.grid(row=0, column=0, sticky=E + W + S + N)
     
     label = Label(frame, text="File List: ")
     label.grid(sticky=N + W)
     
     self.filelist = Listbox(frame, width=40)
     self.filelist.grid(row=1, column=0, rowspan=2, columnspan=3)
     
     vsl = Scrollbar(frame, orient=VERTICAL)
     vsl.grid(row=1, column=3, rowspan=2, sticky=N + S + W)
     
     hsl = Scrollbar(frame, orient=HORIZONTAL)
     hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N)
     
     self.filelist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
     self.filelist.bind('<<ListboxSelect>>', self._onfilelistselection)
     
     hsl.config(command=self.filelist.xview)
     vsl.config(command=self.filelist.yview)
     
     upbtn = Button(frame, text="Up", width=7, command=self._upfile)
     upbtn.grid(row=1, column=4, padx=5, pady=5)
     
     downbtn = Button(frame, text="Down", width=7, command=self._downfile)
     downbtn.grid(row=2, column=4, padx=5, pady=5)
     
     newbtn = Button(frame, text="New", width=7, command=self._addfile)
     newbtn.grid(row=4, column=1, pady=5, sticky=E + S)
     
     delbtn = Button(frame, text="Delete", width=7, command=self._deletefile)
     delbtn.grid(row=4, column=2, padx=5, pady=5, sticky=W + S)
Пример #18
0
class liste_mots:
    """Définit un cadre contenant une liste de mot avec un ascenseur"""
    def __init__(self,parent,titre,compare):
        police_mots=font.Font(parent, size=12, family='Courier')
        self.cadre = LabelFrame(parent, borderwidth=2,
                                relief=GROOVE,text=titre)
        self.ascenseur=Scrollbar(self.cadre,orient=VERTICAL)
        self.mots=Listbox(self.cadre, font=police_mots, width=LARGEUR_LISTE_MOTS,yscrollcommand = self.ascenseur.set )
        self.mots.bind('<<ListboxSelect>>', self.selection)
        self.mots.grid(column=0,row=0)
        self.ascenseur.grid(column=1,row=0,sticky=S+N)
        self.ascenseur.config( command = self.mots.yview )
        self.liste_mots=[]
        self.compare=compare
    def ajoute_mot_couleur(self,mot,couleur):
        fin=self.mots.size()
        self.mots.insert(fin,mot)
        self.mots.itemconfig(fin,fg=couleur)
        self.liste_mots.append(mot)
    def selection(self,e):
        mot=self.liste_mots[self.mots.curselection()[0]]
        self.compare.modifie_mot1(mot)
        self.parent.infos.delete("0.0",END)
        valeur=self.parent.dict_moyennes[mot]
        texte="Selon ce modèle, le mot '"+mot+"' a été lu en moyenne "+str(round(valeur,NB_DECIMALES))+ "fois par un élève de ce profil au cours de l'année écoulée."
        self.parent.infos.insert(END,texte)
Пример #19
0
    def __init__(self, master, text, *args, **kwargs):
        self.master = master
        Toplevel.__init__(self, master, *args, **kwargs)

        # Setup text box.
        self.text = Text(self, width=60, height=20, wrap=NONE)
        self.text.insert("1.0", text)
        self.text["state"] = "disabled"
        self.text.grid(row=0, column=0, sticky="NESW")

        # Create a vertical scrollbar.
        scrolly = Scrollbar(self, orient="vertical",
                            command=self.text.yview)
        scrolly.grid(row=0, column=1, sticky="NS")

        # Create a horizontal scrollbar.
        scrollx = Scrollbar(self, orient="horizontal",
                            command=self.text.xview)
        scrollx.grid(row=1, column=0, columnspan=2, sticky="EW")

        # Add the scroll bars.
        self.text.configure(yscrollcommand=scrolly.set,
                            xscrollcommand=scrollx.set)

        # Setup special configurings.
        self.transient(master)
        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.grab_set()
        self.focus_set()
        self.wait_window(self)
Пример #20
0
class VerticalScrollGrid(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        self.canvas = Canvas(root, borderwidth=0)
        self.frame = Frame(self.canvas)
        self.vsb = Scrollbar(root,
                             orient="vertical",
                             command=self.canvas.yview)
        self.canvas.configure(yscrollcommand=self.vsb.set)
        self.vsb.grid(row=0, column=1, sticky='NS')
        self.vsb.configure(command=self.canvas.yview)
        self.canvas.grid(row=0, column=0, sticky='NSEW')
        self.canvas.create_window((4, 4),
                                  window=self.frame,
                                  anchor="nw",
                                  tags="self.frame")
        self.frame.bind("<Configure>", self.onFrameConfigure)
        self.frame.bind_all("<MouseWheel>", self.on_mousewheel)
        # self.frame.bind("<Button-4>", self.on_mousewheel_up)
        # self.frame.bind("<Button-5>", self.on_mousewheel_down)
    def onFrameConfigure(self, event):
        '''Reset the scroll region to encompass the inner frame'''
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))

    # def on_mousewheel_down(self, event): self.canvas.yview_scroll(1, "units")
    # def on_mousewheel_up(self, event): self.canvas.yview_scroll(-1, "units")
    def on_mousewheel(self, event):
        self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")

    def go_to_top(self, event=None):
        self.canvas.yview_moveto(0)
Пример #21
0
class ScrollableFrame(Frame):

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

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

        self.canvas = Canvas(self)
        self.inner_frame = Frame(self.canvas)
        self.vertical_scrollbar = Scrollbar(self, orient=VERTICAL, command=self.canvas.yview)
        self.horizontal_scrollbar = Scrollbar(self, orient=HORIZONTAL, command=self.canvas.xview)
        self.canvas.configure(yscrollcommand=self.vertical_scrollbar.set,
                              xscrollcommand=self.horizontal_scrollbar.set)

        self.canvas.grid(row=0, column=0, sticky='news')
        self.vertical_scrollbar.grid(row=0, column=1, sticky='ns')
        self.horizontal_scrollbar.grid(row=1, column=0, stick='we')

        self.canvas.create_window((4, 4), window=self.inner_frame, anchor='nw')
        self.inner_frame.bind("<Configure>", self._on_frame_configure)

    # noinspection PyUnusedLocal
    def _on_frame_configure(self, event):
        self.canvas.configure(scrollregion=self.canvas.bbox("all"))
Пример #22
0
class TextBox(Frame):
    """docstring for TextBox"""
    def __init__(self, parent, font, width, height, *args, **kwargs):
        self.width = width
        self.height = height

        Frame.__init__(self,
                       parent,
                       width=self.width,
                       height=self.height,
                       *args,
                       **kwargs)

        self.parent = parent
        self.font = font
        self.mk_textbox()

    def mk_textbox(self):
        self.scroll = Scrollbar(self.parent)
        self.scroll.grid(row=0, column=1, sticky='ns')
        self.chat_box = Listbox(self.parent,
                                font=self.font,
                                yscrollcommand=self.scroll.set)
        self.chat_box.grid(row=0, column=0, sticky='wens')
        self.chat_box.grid_propagate(0)
        self.scroll.configure(command=self.chat_box.yview)
Пример #23
0
class Test(Tk):
    def __init__(self):
        Tk.__init__(self, None)
        self.frame = Frame(None)
        self.frame.columnconfigure(0, weight=1)
        self.frame.rowconfigure(0, weight=1)

        self.frame.grid(row=0, column=0, sticky=W + E + N + S)

        fig = Figure()

        xval = arange(500) / 10.
        yval = sin(xval)

        ax1 = fig.add_subplot(111)
        ax1.plot(xval, yval)

        self.hbar = Scrollbar(self.frame, orient=HORIZONTAL)
        self.vbar = Scrollbar(self.frame, orient=VERTICAL)

        self.canvas = FigureCanvasTkAgg(fig, master=self.frame)
        self.canvas.get_tk_widget().config(bg='#FFFFFF',
                                           scrollregion=(0, 0, 500, 500))
        self.canvas.get_tk_widget().config(width=800, height=500)
        self.canvas.get_tk_widget().config(xscrollcommand=self.hbar.set,
                                           yscrollcommand=self.vbar.set)
        self.canvas.get_tk_widget().grid(row=0, column=0, sticky=W + E + N + S)

        self.hbar.grid(row=1, column=0, sticky=W + E)
        self.hbar.config(command=self.canvas.get_tk_widget().xview)
        self.vbar.grid(row=0, column=1, sticky=N + S)
        self.vbar.config(command=self.canvas.get_tk_widget().yview)

        self.frame.config(width=100, height=100)  # this has no effect
Пример #24
0
 def _initjoincondpanel(self):
     frame = Frame(self)
     frame.grid(row=0, column=2, sticky=E + W + S + N, padx=5)
     
     label = Label(frame, text="Join Condition: ")
     label.grid(sticky=N + W)
     
     self.joincondlist = Listbox(frame)
     self.joincondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N)
     
     vsl = Scrollbar(frame, orient=VERTICAL)
     vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W)
     
     hsl = Scrollbar(frame, orient=HORIZONTAL)
     hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N)
     
     self.joincondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
     
     hsl.config(command=self.joincondlist.xview)
     vsl.config(command=self.joincondlist.yview)
     
     newbtn = Button(frame, text="New", width=7, command=self._addjoincondition)
     newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E)
     
     delbtn = Button(frame, text="Delete", width=7, command=self._deletejoincondition)
     delbtn.grid(row=3, column=1, sticky=E)
     
     modbtn = Button(frame, text="Update", width=7, command=self._modifyjoincondition)
     modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W)
Пример #25
0
    def __init__(self, parent, controller):
        Frame.__init__(self, parent)
        self.controller = controller

        self.columnconfigure(0, weight=1, pad=5)
        self.columnconfigure(1, weight=1, pad=5)

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

        # Title
        bbutton = Button(self,
                         text="<",
                         command=lambda: controller.show_frame("MainPage"))
        bbutton.grid(row=0, column=0, padx=10, sticky=W)
        title = Label(self, text="URL Encode")
        title.grid(row=0, columnspan=2, padx=10)

        # Message input
        tinput = Text(self, wrap=WORD)
        tinput.grid(row=1,
                    columnspan=2,
                    padx=10,
                    pady=10,
                    sticky=N + E + S + W)
        scrolli = Scrollbar(self, command=tinput.yview)
        tinput.configure(yscrollcommand=scrolli.set)
        scrolli.grid(row=1, column=1, pady=10, sticky=N + S + E)
        tinput.insert(1.0, "Input")
        tinput.bind("<Control-Key-a>", select_all)  # select-all Windows/Linux
        tinput.bind("<Command-Key-a>", select_all)  # select-all Mac

        # Encode/Decode buttons
        ebutton = Button(self, text="Encode", width=15)
        ebutton.grid(row=2, column=0, padx=10, sticky=E)
        ebutton.configure(
            command=lambda: self.encode_prep(tinput.get(1.0, 'end-1c')))
        dbutton = Button(self, text="Decode", width=15)
        dbutton.grid(row=2, column=1, padx=10, sticky=W)
        dbutton.configure(
            command=lambda: self.decode_prep(tinput.get(1.0, 'end-1c')))

        # Output box
        self.output = Text(self, wrap=WORD)
        self.output.grid(row=3,
                         columnspan=2,
                         padx=10,
                         pady=10,
                         sticky=N + E + S + W)
        self.output.bind("<1>", lambda event: self.output.focus_set())
        scrollo = Scrollbar(self, command=self.output.yview)
        scrollo.grid(row=3, column=1, pady=10, sticky=N + S + E)
        self.output.configure(yscrollcommand=scrollo.set)
        self.output.insert(1.0, "Output")
        self.output.configure(state="disabled")
        self.output.bind("<Control-Key-a>",
                         select_all)  # select-all Windows/Linux
        self.output.bind("<Command-Key-a>", select_all)  # select-all Mac
    def __init__(self):
        Tk.__init__(self)
        # self.configure(width=400, height=400)


        # f = Figure(figsize=(6, 5), dpi=100)
        # a = f.add_subplot(111)
        # t = arange(0.0, 3.0, 0.01)
        # s = sin(2*pi*t)
        # a.plot(t, s)

        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().grid(row=0, column=0)

        vbar=Scrollbar(self, orient = VERTICAL)
        vbar.grid(row=0, column=1)       
        hbar=Scrollbar(self, orient=HORIZONTAL)
        hbar.grid(row=1, column=0)


        canvas.get_tk_widget().config(xscrollcommand=hbar.set, yscrollcommand = vbar.set)

        hbar.config(command=canvas.get_tk_widget().xview)
        vbar.config(command=canvas.get_tk_widget().yview)
def addScrollingFigure(figure, frame):
  global canvas, mplCanvas, interior, interior_id, cwid
  # set up a canvas with scrollbars
  canvas = Canvas(frame)
  canvas.grid(row=1, column=1, sticky=Tkconstants.NSEW)

  xScrollbar = Scrollbar(frame, orient=Tkconstants.HORIZONTAL)
  yScrollbar = Scrollbar(frame)

  xScrollbar.grid(row=2, column=1, sticky=Tkconstants.EW)
  yScrollbar.grid(row=1, column=2, sticky=Tkconstants.NS)

  canvas.config(xscrollcommand=xScrollbar.set)
  xScrollbar.config(command=canvas.xview)
  canvas.config(yscrollcommand=yScrollbar.set)
  yScrollbar.config(command=canvas.yview)

  # plug in the figure
  figAgg = FigureCanvasTkAgg(figure, canvas)
  mplCanvas = figAgg.get_tk_widget()
  #mplCanvas.grid(sticky=Tkconstants.NSEW)

  # and connect figure with scrolling region
  cwid = canvas.create_window(0, 0, window=mplCanvas, anchor=Tkconstants.NW)
  printBboxes("Init")
  canvas.config(scrollregion=canvas.bbox(Tkconstants.ALL),width=200,height=200)
Пример #28
0
def login(user_id):
    log = Tk()

    website_text = StringVar()
    website_label = Label(log, text='Website', pady=20, padx=15)
    website_label.grid(row=0, column=0)
    website_entry = Entry(log, textvariable=website_text)
    website_entry.grid(row=0, column=1, padx=10)

    password_text = StringVar()
    password_label = Label(log, text='Password', padx=15)
    password_label.grid(row=1, column=0)
    password_entry = Entry(log, textvariable=password_text)
    password_entry.grid(row=1, column=1, padx=10)

    add_button = Button(
        log,
        text="Add",
        command=lambda: db.new_entry(user_id, website_entry.get(),
                                     password_entry.get()),
        width=17)
    add_button.grid(row=2, column=0, pady=10, padx=10)

    remove_button = Button(
        log,
        text="Remove",
        command=lambda: db.remove_entry(user_id, website_entry.get(),
                                        password_entry.get()),
        width=17)
    remove_button.grid(row=2, column=1)

    update_button = Button(
        log,
        text="Update",
        command=lambda: db.update_site_password(user_id, website_entry.get(),
                                                password_entry.get()),
        width=17)
    update_button.grid(row=3, column=0)

    pass_list = Listbox(log, width=45, height=8, border=0)
    pass_list.grid(row=4, column=0, columnspan=3, rowspan=4, padx=20, pady=20)

    refresh_button = Button(log,
                            text="Refresh",
                            command=lambda: populate_list(user_id, pass_list),
                            width=17)
    refresh_button.grid(row=3, column=1)

    scrollbar = Scrollbar(log)
    pass_list.configure(yscrollcommand=scrollbar.set)
    scrollbar.configure(command=pass_list.yview)
    scrollbar.grid(row=4, column=3)
    #Bind select
    #pass_list.bind('<<ListBoxSelect>>', select_item)

    populate_list(user_id, pass_list)
    log.title(f"{user_id}")
    log.geometry("350x380")
    log.mainloop()
Пример #29
0
    def __init__(self, master, mech):
        self.mech = mech
        frame = Frame(master)
        frame.grid()
        rct_label = Label(frame, text='Select Reactants')
        rct_label.grid(column=1, row=1)
        and_or = Label(frame, text='AND/OR')
        and_or.grid(column=3, row=1)
        prod_label = Label(frame, text='Select Products')
        prod_label.grid(column=4, row=1)
        what_to_do = Label(frame, text='Execute')
        what_to_do.grid(column=6, row=1)
        reactants_scrollbar = Scrollbar(frame, orient=VERTICAL)
        self.reactants = Listbox(frame,
                                 selectmode=EXTENDED,
                                 exportselection=0,
                                 yscrollcommand=reactants_scrollbar.set)
        self.reactants.grid(column=1, row=2)
        reactants_scrollbar.config(command=self.reactants.yview)
        reactants_scrollbar.grid(column=2, row=2, sticky=N + S)

        self.logical_and = IntVar()
        self.logical_and.set(1)
        c = Checkbutton(frame, text="AND", variable=self.logical_and)
        c.grid(column=3, row=2)

        products_scrollbar = Scrollbar(frame, orient=VERTICAL)
        self.products = Listbox(frame, selectmode=EXTENDED, exportselection=0)
        self.products.grid(column=4, row=2)
        products_scrollbar.config(command=self.products.yview)
        products_scrollbar.grid(column=5, row=2, sticky=N + S)

        self.method_list = Listbox(frame,
                                   selectmode=EXTENDED,
                                   exportselection=0)
        self.method_list.grid(column=6, row=2)
        #self.methods = [k for k in dir(self.mech) if k[:1] != '_' and isinstance(getattr(self.mech, k), MethodType)]
        self.methods = [
            'plot_rxns', 'find_rxns', 'print_rxns', 'print_irrs',
            'print_net_rxn', 'plot_proc'
        ]
        method_labels = [
            'Plot Reactions', 'Show Rxn Ids', 'Print Rxns', 'Print IRRs',
            'Print Net Rxn', 'Process Plot'
        ]
        for method in method_labels:
            self.method_list.insert(END, method)

        species_keys = list(self.mech.species_dict.keys())
        species_keys.sort()
        self.species_objects = [
            self.mech.species_dict[spc] for spc in species_keys
        ]

        for spc in species_keys:
            self.reactants.insert(END, spc)
            self.products.insert(END, spc)
        self.execute_button = Button(frame, text="go", command=self.execute)
        self.execute_button.grid(column=6, row=4)
Пример #30
0
def log():
    log = Text(root, width=50, height=10)
    log.insert('end', logtxt)
    scroll = Scrollbar(root)
    scroll.config(command=log.yview)
    log.config(yscrollcommand=scroll.set, state='disabled')
    log.grid(row=9, column=1, columnspan=9)
    scroll.grid(row=9, column=10, sticky='NSE')
    log.yview_pickplace('end')
Пример #31
0
 def initTextFrame(self, texts):
     # We init the frame:
     if self.textFrame is not None:
         self.textFrame.destroy()
     self.textFrame = Frame(self)
     self.textFrame.grid(row=0,
                         column=0,
                         columnspan=10,
                         rowspan=10,
                         padx=5,
                         pady=0,
                         sticky="news")
     self.textFrame.rowconfigure(0, weight=0)
     self.textFrame.rowconfigure(1, weight=1)
     # For each text:
     if not isinstance(texts, list):
         texts = [texts]
     nbColumns = len(texts)
     for i in range(nbColumns):
         self.textFrame.columnconfigure(i, weight=1)
         current = texts[i]
         try:
             # We add the head message:
             if dictContains(current, "title"):
                 headMessage = Message(self.textFrame,
                                       text=tkStripExtra(current["title"]),
                                       **self.headMessagesOption)
                 headMessage.grid(row=0,
                                  column=i,
                                  sticky='nwe',
                                  padx=2,
                                  pady=0)
             # We create the area for the text:
             textAreaFrame = Frame(self.textFrame)
             textAreaFrame.columnconfigure(0, weight=1)
             textAreaFrame.rowconfigure(0, weight=1)
             textAreaRow = 1
             textAreaRowspan = 1
             if not dictContains(current, "title"):
                 textAreaRow = 0
                 textAreaRowspan = 2
             textAreaFrame.grid(row=textAreaRow,
                                rowspan=textAreaRowspan,
                                column=i,
                                sticky="news",
                                padx=0)
             # We create the Text widget in:
             textWidget = Text(textAreaFrame)
             textWidget.grid(row=0, column=0, sticky="news")
             textWidget.insert(INSERT, tkStripExtra(current["text"]))
             textWidget.config(state=DISABLED)
             # We make the scroll bar:
             scrollBar = Scrollbar(textAreaFrame, command=textWidget.yview)
             scrollBar.grid(row=0, column=1, sticky="nse")
             textWidget['yscrollcommand'] = scrollBar.set
         except Exception as e:
             logException(e, self)
Пример #32
0
 def addInactiveListbox(self):
     labelInactiveListbox = Label(self.inactiveFrame, text=LabelConstants.INACTIVE_TAGS)
     labelInactiveListbox.grid(row=0, column=0, sticky=W, padx=4, pady=4)
     scrollbarInactive = Scrollbar(self.inactiveFrame)
     scrollbarInactive.grid(row=1, column=1, sticky="NWS")
     self.inactiveListbox = Listbox(self.inactiveFrame, selectmode=EXTENDED, yscrollcommand=scrollbarInactive.set, activestyle=NONE, width=70)
     scrollbarInactive.config(command=self.inactiveListbox.yview)
     self.inactiveListbox.bind('<<ListboxSelect>>', self.onSelectInactiveListbox)
     self.inactiveListbox.grid(row=1, column=0, sticky=NSEW, padx=(4, 0))
Пример #33
0
    def __init__(self,master,cmap=None):
        Toplevel.__init__(self,master)
        # update title
        self.title("Choose a colormap")
        # create frame
        frm = Frame(self)
        # create listbox
        self.clist = Listbox(frm)
        # bind double click
        self.clist.bind('<Button-1>',self.cmapSelect)
        # get all colormaps
        for ci,(kk,_) in enumerate(filter(lambda x : isinstance(x[1],Colormap),vars(matplotlib.cm).items())):
            self.clist.insert(ci,kk)
        # scrollbar
        scroll = Scrollbar(frm,orient='vertical')
        scroll.config(command=self.clist.yview)
        # currently selected colormap
        # if nothing is given, get matplotlib default
        if cmap == None:
            self.curr_cmap = getattr(matplotlib.cm,matplotlib.rcParams['image.cmap'])
        else:
            # if user specifies a string
            if type(cmap) == str:
                # attempt to get index of colormap from list
                # if it fails, reverts to default
                try:
                    idx = self.self.clist.get(0,END).index(cmap)
                    self.self.clist.select(idx)
                    self.curr_cmap = getattr(matplotlib.cm,self.self.clist.get(0,END)[idx])
                except ValueError:
                    self.curr_cmap = getattr(matplotlib.cm,matplotlib.rcParams['image.cmap'])
            # if the user passs a Colormap directly, store that
            elif isinstance(cmap,Colormap):
                self.curr_cmap = cmap
            # if it's something else
            # print error message and set current colormap to None
            else:
                print(f"Unsupported colormap value {cmap}!",file=sys.stderr)
                self.curr_cmap = None
        # add buttons
        btt_frm = Frame(self)
        select_btt = Button(btt_frm,text="Select",command=self.enter_handler)
        cancel_btt = Button(btt_frm,text="Cancel",command=self.cancel_handler)

        # keyboard handlers for if the button is currently selected
        select_btt.bind('<KeyPress-Return>', func=self.enter_handler)
        cancel_btt.bind('<KeyPress-Return>', func=self.cancel_handler)
        ## pack
        self.clist.grid(row=0,column=0,sticky='nswe')
        scroll.grid(row=0,column=1,sticky='ns')
        
        frm.grid(row=0,column=0,sticky='nswe')
        
        select_btt.grid(row=0,column=0,sticky='ew')
        cancel_btt.grid(row=0,column=1,sticky='ew')
        
        btt_frm.grid(row=1,column=0,columnspan=2,sticky='ew')
Пример #34
0
 def __init__(self, master:Notebook, text, *args, **kw):
     super(TextPage, self).__init__(master, *args, **kw)
     f = Frame(master)
     self.grid(in_=f, row=0, column=0, sticky=NSEW)
     self.lift(f)
     sb = Scrollbar(f, orient='vertical', command=self.yview)
     sb.grid(row=0, column=1, sticky=NS)
     self.configure(yscrollcommand=sb.set) 
     f.columnconfigure(0, weight=1)
     f.rowconfigure(0, weight=1)        
     master.add(f, text=text)
Пример #35
0
 def __init__(self, parent, filename):
     Frame.__init__(self, parent)
     text = HelpText(self, filename)
     self['background'] = text['background']
     scroll = Scrollbar(self, command=text.yview)
     text['yscrollcommand'] = scroll.set
     self.rowconfigure(0, weight=1)
     self.columnconfigure(1, weight=1)  # text
     self.toc_menu(text).grid(column=0, row=0, sticky='nw')
     text.grid(column=1, row=0, sticky='nsew')
     scroll.grid(column=2, row=0, sticky='ns')
Пример #36
0
 def create_left_toolbar(self, app_frame):
     """
     This function creates and pack the left toolbar
     :param app_frame: root for this toolbar.. (Frame obj)
     :return:
     """
     left_toolbar = Frame(app_frame)
     self.lb_users = Listbox(left_toolbar)
     self.lb_users.config(height=30)
     self.lb_users.grid(row=0, column=0)
     scroll_bar = Scrollbar(left_toolbar)
     scroll_bar.config(command=self.lb_users.yview)
     scroll_bar.grid(row=0, column=1, sticky='ns')
     left_toolbar.propagate("false")
     left_toolbar.grid(column=0, row=0)
     self.lb_users.config(yscrollcommand=scroll_bar.set)
     self.debug_event("Left toolbar was generated")
Пример #37
0
 def _initconsole(self):
     
     separator = Separator(self, orient=HORIZONTAL)
     separator.grid(row=1, columnspan=3, sticky=W + E, padx=5, pady=5)
     
     self.console = Text(self)
     self.console.grid(row=2, columnspan=3, sticky=W + E, padx=5, pady=5)
     
     vsl = Scrollbar(self, orient=VERTICAL)
     vsl.grid(row=2, column=3, sticky=N + S + W)
     
     hsl = Scrollbar(self, orient=HORIZONTAL)
     hsl.grid(row=3, column=0, columnspan=3, sticky=W + E + N)
     
     hsl.config(command=self.console.xview)
     vsl.config(command=self.console.yview)
     
     resbtn = Button(self, text="Search", width=7, comman=self._showsearchresult)
     resbtn.grid(row=4, column=2, padx=5, pady=5, sticky=E)
Пример #38
0
def new_random_swiss(main):
    players = []
    def add_player(event):
        if e.get() is "":
            return
        players.append(e.get())
        Lb.delete(0,END)
        for x in players:
            Lb.insert(0,x)
        e.delete(0,END)

    def remove_player():
        l=len(players)-1
        if Lb.curselection():
            for x in Lb.curselection():
                Lb.delete(x)
                players.pop(l-x)
        else:
            Lb.delete(0)
            players.pop(-1)
        Lb.delete(0,END)
        for x in players:
            Lb.insert(0,x)


    top = Toplevel(main)
    top.title("New Random Swiss")
    top.bind("<Return>",add_player)
    center_size(top,360,180)
    Label(top, text='Name:').grid(row=0,column=0)
    e = Entry(top,width=12)
    e.grid(row=0,column=1)
    e.focus_force()
    Button(top,text='Add',	command=lambda:add_player(None)			).grid(row=1,column=0)
    Button(top,text='Remove',	command=remove_player				).grid(row=1,column=1)
    Button(top,text='Cancel',	command=top.destroy				).grid(row=2,column=0)
    Button(top,text='Finish',	command=lambda:create_single_swiss(players,main)).grid(row=2,column=1)
    Sb = Scrollbar(top)
    Sb.grid(row=0,column=3,rowspan=3)
    Lb = Listbox(top,selectmode=EXTENDED,yscrollcommand=Sb.set)
    Lb.grid(row=0,rowspan=3,column=2)
    Sb.config(command=Lb.yview)
Пример #39
0
    def __init__(self, master, model):
        self.f = 0

        master.rowconfigure(0, weight=1)
        master.columnconfigure(0, weight=1)

        self.frame = tk.Frame(master)
        self.frame.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)

        self.frame.grid(sticky=NSEW)
        self.frame.rowconfigure(0, weight=1)
        self.frame.columnconfigure(0, weight=1)

        self.scroll_canvas = Canvas(self.frame)
        self.scroll_canvas.grid(row=0, column=0, sticky=NSEW)

        xScrollbar = Scrollbar(self.frame, orient=HORIZONTAL)
        yScrollbar = Scrollbar(self.frame)

        xScrollbar.grid(row=1, column=0, sticky=EW)
        yScrollbar.grid(row=0, column=1, sticky=NS)

        self.scroll_canvas.config(xscrollcommand=xScrollbar.set)
        xScrollbar.config(command=self.scroll_canvas.xview)
        self.scroll_canvas.config(yscrollcommand=yScrollbar.set)
        yScrollbar.config(command=self.scroll_canvas.yview)

        self.create_plot(model)

        self.figure_canvas = FigureCanvasTkAgg(self.f, master=self.scroll_canvas)
        self.canvas = self.figure_canvas.get_tk_widget()
        self.canvas.pack(side=tk.TOP, fill=tk.BOTH, padx=5, pady=5, expand=1)

        self.scroll_canvas.create_window(0, 0, window=self.canvas)
        self.scroll_canvas.config(scrollregion=self.scroll_canvas.bbox(ALL))
        self.figure_canvas.show()

        self.toolbar = NavigationToolbar2TkAgg(self.figure_canvas, self.scroll_canvas)
        self.toolbar.pack()
        self.toolbar.update()

        """
Пример #40
0
 def _initsearchcondpanel(self):
     frame = Frame(self)
     frame.grid(row=0, column=1, sticky=E + W + S + N, padx=5)
     
     label = Label(frame, text="Search Condition: ")
     label.grid(row=0, column=0, columnspan=1, sticky=W)
     
     relationlable = Label(frame, text="Relation")
     relationlable.grid(row=0, column=1, columnspan=1, sticky=E)
     
     self.condrelationvar = StringVar(frame)
     relationinput = Combobox(frame, textvariable=self.condrelationvar, values=["and", "or"])
     relationinput.grid(row=0, column=2, padx=5, sticky=E)
     relationinput.bind('<<ComboboxSelected>>', self._onrelationchange)
     
     self.searchcondlist = Listbox(frame)
     self.searchcondlist.grid(row=1, rowspan=1, columnspan=3, sticky=E + W + S + N)
     
     vsl = Scrollbar(frame, orient=VERTICAL)
     vsl.grid(row=1, column=3, rowspan=1, sticky=N + S + W)
     
     hsl = Scrollbar(frame, orient=HORIZONTAL)
     hsl.grid(row=2, column=0, columnspan=3, sticky=W + E + N)
     
     self.searchcondlist.config(yscrollcommand=vsl.set, xscrollcommand=hsl.set)
     
     hsl.config(command=self.searchcondlist.xview)
     vsl.config(command=self.searchcondlist.yview)
     
     newbtn = Button(frame, text="New", width=7, command=self._addsearchcondition)
     newbtn.grid(row=3, column=0, padx=5, pady=5, sticky=E)
     
     delbtn = Button(frame, text="Delete", width=7, command=self._deletesearchcondition)
     delbtn.grid(row=3, column=1, sticky=E)
     
     modbtn = Button(frame, text="Update", width=7, command=self._modifysearchcondition)
     modbtn.grid(row=3, column=2, padx=5, pady=5, sticky=W)
Пример #41
0
class Application(Frame):
    def __init__(self, master=None):
        self.root = master
        super().__init__(self.root)
        self.pack()
        self.createWidgets()

    def createWidgets(self):
        self.text = Text(self, height=24, width=80)
        self.scrollbar = Scrollbar(self, command=self.text.yview)
        self.text.config(yscrollcommand=self.scrollbar.set)

        self.QUIT = Button(
            self, text="QUIT", fg="red", command=self.root.destroy
        )
        self.SAVE = Button(
            self, text="SAVE", command=self.save_text
        )
        self.LOAD = Button(
            self, text="LOAD", command=self.load_text
        )

        self.QUIT.grid(row=0, column=0)
        self.SAVE.grid(row=1, column=0)
        self.LOAD.grid(row=2, column=0)
        self.text.grid(row=0, column=1, rowspan=3)
        self.scrollbar.grid(row=0, column=2, rowspan=3)

    def load_text(self):
        with open(askopenfilename()) as fd:
            self.text.delete(0.0, 'end')
            self.text.insert(END, fd.read())

    def save_text(self):
        with open(asksaveasfilename(), 'w') as fd:
            fd.write(self.text.get(1.0, END))
Пример #42
0
    def initUI(self):
        self.parent.title("TVstream manager")
        self.stytle = ttk.Style()
        self.pack(fill=BOTH, expand=1)        
        self.columnconfigure(0, weight=1, pad=2)
        self.columnconfigure(2, weight=1, pad=2)
        self.columnconfigure(4,  pad=7)
        #self.rowconfigure(3, weight=1)
        #self.rowconfigure(4, weight=1, pad=7)

        lbll = Label(self, text="Lingua")
        lbll.grid(row=0,column=0,sticky=W, pady=4, padx=5)

        lble = Label(self, text="Emittenti")
        lble.grid(row=0,column=2,sticky=W, pady=1, padx=5)

        global langlst
        scrollang = Scrollbar(self)
        langlst = Listbox(self,font='Arial 9',yscrollcommand=scrollang.set)
        scrollang.config(command = langlst.yview)
        
        for i in lingue:
            langlst.insert(END, i)
        langlst.focus_set()
        
        langlst.bind("<<ListboxSelect>>", self.onSelectLang)  
        langlst.grid(row=1,column=0, columnspan=2, padx=6,sticky=E+W+S+N)
        scrollang.grid(row=1,column=1, sticky=E+S+N)

        global emitlst
        scrollemit = Scrollbar(self)
        emitlst = Listbox(self,font='Arial 9',yscrollcommand=scrollemit.set)
        scrollemit.config(command = emitlst.yview )
        emitlst.bind("<<ListboxSelect>>", self.onSelectEmittente)
        emitlst.grid(row=1,column=2, columnspan=2, padx=5,sticky=E+W+S+N)
        scrollemit.grid(row=1,column=3,sticky=E+S+N)

        lbltxt = Label(self, text="Output log")
        lbltxt.grid(row=2,column=0, columnspan=3, sticky=W, pady=4, padx=5)
        
        global area
        area = Text(self,height=10,font='Arial 9')
        area.grid(row=3, column=0, columnspan=5, rowspan=1, padx=5, sticky=E+W+S+N)
        scrolltxt = Scrollbar(self)
        scrolltxt.config(command = area.yview)
        scrolltxt.grid(row=3,column=4, columnspan=1, rowspan=1, sticky=E+N+S)
        
        play = Button(self, text='Play', command=self.playUrl,
               bg='gray', fg='black')
        play.grid(row=1,column=4,padx=4,sticky=E+W)
Пример #43
0
class ScrollableTreeview(Frame):
    """
    An enhanced Tkinter Treeview control.
    """

    def __init__(self, master, **args):
        super().__init__(master)

        # Parse Treeview options for the Treeview
        opts = {x:args[x] for x in args if x in tree_options}

        # Create child controls
        self._vscroll = Scrollbar(self)
        self._hscroll = Scrollbar(self, orient=HORIZONTAL)

        opts['yscrollcommand'] = self._vscroll.set
        opts['xscrollcommand'] = self._hscroll.set
        self._tree = Treeview(self, **opts)

        # Setup the child controls
        self._init_controls()

        # Link some of the treeview's controls to this control
        self.item = self._tree.item
        self.tag_bind = self._tree.tag_bind
        self.tag_bind = self._tree.tag_configure
        self.insert = self._tree.insert
        self.delete = self._tree.delete
        self.detach = self._tree.detach
        self.heading = self._tree.heading

        # If a header argument was passed in, then use it
        self.set_headers(args.get('headers'))

    def _init_controls(self):
        """
        Initialize various properties of the child-controls
        :return:
        """

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

        # Place the controls
        self._tree.grid(row=0, column=0, sticky=NSEW)
        self._vscroll.grid(row=0, column=1, sticky=NS)
        self._hscroll.grid(row=1, column=0, sticky=EW)

        # Setup scrollbars
        self._vscroll.config(command=self._tree.yview)
        self._hscroll.config(command=self._tree.xview)

    def set_headers(self, headers: dict):
        """
        Update any number of column headers.
        :param headers:
        :return:
        """

        # If no headers were defined, then return
        if headers is None:
            return

        # Iterate through all of the column headers and update their values
        for col in headers:
            tp = type(headers[col])

            # Dictionary of parameters
            if tp is dict:
                self.heading(col, **headers[col])

            # Just the title
            elif tp is str:
                self.heading(col, text=headers[col])
Пример #44
0
class Example(Frame):

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

        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("")
        #self.style = Style()
        #self.style.theme_use("clam")
        #self.pack(fill=BOTH, expand = 1)


        self.quitbutton = Button(self, text="Quit", command= lambda: self.quit())

        self.quitbutton.grid(row=3, column=1, pady=4)

        self.labelErrorPointer = Label(self, text="◀")

        self.labellist = []
        self.entrylist = []
        self.verifylist = []
        self.misclist = []
                
        self.optionCreate = "Create"
        self.optionUpcoming = "Upcoming"
        self.optionPast = "Past"

        self.prevmode = self.optionCreate
        self.curmode = self.optionCreate
        self.optionvar = tkinter.StringVar(self)
        self.optionvar.trace("w",self.permaloop)
        self.optionvar.set(self.optionCreate)
        self.option = OptionMenu(self, self.optionvar, self.optionCreate, self.optionUpcoming, self.optionPast)

        self.optionpostmodevar = tkinter.StringVar(self)
        self.optionpostmodevar.trace("w",self.permaloop)
        self.optionpostmodevar.set('url')
        self.optionpostmode = OptionMenu(self, self.optionpostmodevar, 'url', 'text')

        self.labelText = Label(self, text='Selftext:')
        self.entryText = Text(self)
        self.labelURL = Label(self, text='URL:')
        self.entryURL = Entry(self)
        self.entryURL.configure(width=60)  

        self.sql = sqlite3.connect('sql.db')
        print('Loaded SQL Database')
        self.cur = self.sql.cursor()

        self.cur.execute('CREATE TABLE IF NOT EXISTS upcoming(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT)')
        self.cur.execute('CREATE TABLE IF NOT EXISTS past(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT, POSTLINK TEXT)')
        self.cur.execute('CREATE TABLE IF NOT EXISTS internal(NAME TEXT, ID INT)')
        print('Loaded Completed table')
        self.cur.execute('SELECT * FROM internal')
        f = self.cur.fetchone()
        if not f:
            print('Database is new. Adding ID counter')
            self.cur.execute('INSERT INTO internal VALUES(?, ?)', ['counter', 1])
            self.idcounter = 1
        else:
            self.idcounter = f[1]
            print('Current ID counter: ' + str(self.idcounter))

        self.sql.commit()
        

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


        w=853
        h=480
        x = (sw - w) / 2
        y = (sh - h) / 2

        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y-50))

        self.login()
        

    def login(self):

        try:
            self.quitbutton.grid_forget()
            self.quitbutton.grid(row=9000, column=0, columnspan=20)          

            self.option.grid(row=1,column=0,columnspan=80,pady=8)

            self.updategui(fullclean=True)
        except praw.errors.InvalidUserPass:
            pass
            print('Invalid username or password')
            self.entryPassword.delete(0,200)
            self.labelErrorPointer.grid(row=1, column=2)

    def permaloop(self, *args):
        self.curmode = self.optionvar.get()
        print('Was: ' + self.prevmode + ' | Now: ' + self.curmode)
        if self.curmode != self.prevmode:
            self.prevmode = self.curmode
            self.updategui(fullclean=True)
        else:
            self.updategui(False)

    def getTime(self, bool):
        timeNow = datetime.datetime.now(datetime.timezone.utc)
        timeUnix = timeNow.timestamp()
        if bool is False:
            return timeNow
        else:
            return timeUnix

    def addentrytobase(self, subreddit, title, url="", body="", mode="", ptime=""):
        curtime = round(self.getTime(True))
        try:
            t = self.entryMo.get() + ' ' + self.entryDa.get() + ' ' + self.entryYr.get() + ' ' + self.entryHH.get() + ':' + self.entryMM.get()
            plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M")
            plandate = plandate.timestamp()
        except ValueError:
            print('Invalid Day')
            return False

        if mode == 'url':
            url = self.entryURL.get()
            body = ""
            if 'http://' not in url and 'https://' not in url:
                print('Please enter a proper URL')
                return False
        if mode == 'text':
            body = self.entryText.get("1.0", "end")
            url = ""

        if plandate < curtime:
            print('Please enter a time in the future')
            return False

        if not all(char in string.ascii_letters+string.digits+'_-' for char in subreddit):
            print('Subreddit contains invalid characters')
            return False

        if len(subreddit) == 0:
            print('You must enter a subreddit')
            return False

        if len(title) == 0:
            print('You must enter a title')
            return False
        if len(title) > 300:
            print('Title is too long. ' + str(len(title)) + '/300 char max')
            return False
        if len(body) > 15000:
            print('Body is too long. ' + str(len(body)) + '/15,000 char max')

        print('Timestamp:', plandate)
        self.cur.execute('INSERT INTO upcoming VALUES(?, ?, ?, ?, ?, ?)', [self.idcounter, subreddit, int(plandate), title, url, body])
        self.idcounter += 1
        self.cur.execute('UPDATE internal SET ID=? WHERE NAME=?', [self.idcounter, 'counter'])
        self.sql.commit()
        print('\nPost Saved!')
        print(self.idcounter, subreddit, self.timestamptoday(int(plandate)))
        print(title)
        print(url, body)
        print()
        self.entryText.delete("1.0", "end")
        self.entryURL.delete(0, 'end')
        self.entryTitle.delete(0, 'end')
        #self.updategui(halfclean=True)

    def timestamptoday(self, timestamp):
        d = datetime.datetime.fromtimestamp(timestamp)
        info = datetime.datetime.strftime(d, "%b %d %H:%M")
        return info


    def dropentryfrombase(self, ID):
        if '-' not in ID:
            try:
                ID = int(ID)
                l = [ID]
            except ValueError:
                print('You must enter a number')
                return
        else:
            if ID.count('-') == 1:
                try:
                    ID = ID.replace(' ', '')
                    ID = ID.split('-')
                    ID[0] = int(ID[0])
                    ID[1] = int(ID[1])
                    if ID[1] > ID[0]:
                        l = list(range(ID[0], ID[1]+1))
                    else:
                        return
                except ValueError:
                    return

        for item in l:
            item = str(item)
            print('Dropping Item ' + item + ' from Upcoming')
            self.cur.execute('DELETE FROM upcoming WHERE ID=?', [item])
            self.sql.commit()
        self.updategui(fullclean=True)

    def printbasetofile(self, db):
        filea = open(db + '.txt', 'w')
        if db == 'past':
            self.cur.execute('SELECT * FROM past')
        if db == 'upcoming':
            self.cur.execute('SELECT * FROM upcoming')
        f = self.cur.fetchall()
        print('Printed ' + db + ' unimpeded to file')
        for item in f:
            i = list(item)
            i[2] = self.timestamptoday(i[2])
            i.remove('')

            print(str(i)[1:-1], file=filea)
        filea.close()

        


    def updategui(self, halfclean=False, fullclean=False):

        if self.curmode == self.optionCreate:
            try:
                print(self.optionpostmodevar.get())

                if self.optionpostmodevar.get() == 'url':
                    self.entryText.delete("1.0", 'end')
                    self.labelText.grid_forget()
                    self.entryText.grid_forget()
    
                    self.labelURL.grid(row=8, column=0, columnspan=30)
                    self.entryURL.grid(row=9, column=0, columnspan=12, pady=10)
    
                if self.optionpostmodevar.get() == 'text':
                    self.entryURL.delete(0, 'end')
                    self.labelURL.grid_forget()
                    self.entryURL.grid_forget()
    
                    self.labelText.grid(row=8, column=0, columnspan=30)
                    self.entryText.configure(width=40, height=8)
                    self.entryText.grid(row=9, column=0, columnspan=12)
            except AttributeError:
                pass

        if fullclean is True:
            print('Cleaning GUI')
            for item in self.labellist:
                item.grid_forget()
            for item in self.entrylist:
                item.grid_forget()
            for item in self.verifylist:
                item.grid_forget()
            for item in self.misclist:
                item.grid_forget()
            self.labellist = []
            self.entrylist = []
            self.verifylist = []
            self.misclist = []

            if self.curmode == self.optionCreate:
                self.newrowindex = 6
                self.labelSubreddit = Label(self, text="Subreddit:    /r/")
                self.labelTitle = Label(self, text="Post title:  ")
                self.entrySubreddit = Entry(self)
                self.entryTitle = Entry(self)


                self.labelHH = Label(self, text="Schedule time (Local timezone):")
                nowlist = datetime.datetime.strftime(datetime.datetime.now(), "%B %d %Y %H %M").split()

                self.entryMo = Spinbox(self, width=9, values=('January', 'February', 'March', 'April', 'May', 'June', 'July', \
                    'August', 'September', 'October', 'November', 'December'))
                self.entryMo.delete(0,'end')
                self.entryMo.insert(0, nowlist[0])


                self.entryDa = Spinbox(self, width=2, from_=1, to=31)
                self.entryDa.delete(0,'end')
                self.entryDa.insert(0, nowlist[1])

                self.entryYr = Spinbox(self, width=4, from_=2014, to=2500)
                self.entryYr.delete(0,'end')
                self.entryYr.insert(0, nowlist[2])

                self.entryHH = Spinbox(self, from_=0, to=23, width=2)
                self.entryHH.delete(0,'end')
                self.entryHH.insert(0, nowlist[3])

                self.entryMM = Spinbox(self, from_=0, to=59, width=2)
                self.entryMM.delete(0,'end')
                self.entryMM.insert(0, nowlist[4])

                self.buttonAddentry = Button(self, text='Save', command=lambda: self.addentrytobase(self.entrySubreddit.get(), self.entryTitle.get(),\
                    mode=self.optionpostmodevar.get()))


                self.misclist.append(self.labelSubreddit)
                self.misclist.append(self.entrySubreddit)
                self.misclist.append(self.labelHH)
                self.misclist.append(self.entryHH)
                self.misclist.append(self.entryMM)
                self.misclist.append(self.entryMo)
                self.misclist.append(self.entryDa)
                self.misclist.append(self.entryYr)
                self.misclist.append(self.labelTitle)
                self.misclist.append(self.entryTitle)
                self.misclist.append(self.buttonAddentry)
                self.misclist.append(self.optionpostmode)
                self.misclist.append(self.labelText)
                self.misclist.append(self.entryText)
                self.misclist.append(self.labelURL)
                self.misclist.append(self.entryURL)

                self.labelSubreddit.grid(row=2, column=0, sticky="e")
                self.labelTitle.grid(row=3, column=0, sticky="e")
                self.entrySubreddit.grid(row=2, column=1, columnspan=3, sticky="w")
                self.entryTitle.grid(row=3, column=1, columnspan=3, sticky="w")
                self.entryMo.grid(row=4, column=1,sticky="e")
                self.entryDa.grid(row=4, column=2)
                self.entryYr.grid(row=4, column=3)
                self.labelHH.grid(row=4, column=0, sticky="se", pady=5)
                self.entryHH.grid(row=5, column=1, sticky="e")
                self.entryMM.grid(row=5, column=2, sticky="w")
                self.optionpostmode.grid(row=6, column=0, columnspan=20, pady=10)
                self.buttonAddentry.grid(row=200, column=0, columnspan=20)

            if self.curmode == self.optionUpcoming:
                self.cur.execute('SELECT * FROM upcoming')
                dobutton = True

            if self.curmode == self.optionPast:
                self.cur.execute('SELECT * FROM past')
                dobutton = False

            if self.curmode == self.optionPast or self.curmode == self.optionUpcoming:

                
                self.listboxId = Listbox(self)
                self.listboxId.configure(width=118, height=20, font=("Courier 8"))
                self.misclist.append(self.listboxId)

                self.listboxScroller = Scrollbar(self, orient='horizontal', command=self.listboxId.xview)
                self.listboxScroller.grid(row=4, column=0, columnspan=900)
                self.listboxId.grid(row=3, column=0, columnspan=10)

                self.listboxId.configure(xscrollcommand=self.listboxScroller.set)
                self.misclist.append(self.listboxScroller)

                self.buttonPrinter = Button(self, text="Print to .txt file")
                if self.curmode == self.optionPast:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile('past'))
                if self.curmode == self.optionUpcoming:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile('upcoming'))   

                self.buttonPrinter.grid(row = 6, column=0, columnspan=90)
                self.misclist.append(self.buttonPrinter)

                if dobutton is True:
                    self.entryDelete = Entry(self)
                    self.buttonDelete = Button(self, text="Delete Item: ", command=lambda: self.dropentryfrombase(self.entryDelete.get()))
                    self.buttonDelete.grid(row=5, column=0, sticky='e')
                    self.entryDelete.grid(row=5, column=1, sticky='w')
                    self.misclist.append(self.entryDelete)
                    self.misclist.append(self.buttonDelete)


                fetched = self.cur.fetchall()
                for item in fetched:

                    info = self.timestamptoday(item[2])

                    if item[4] == '':
                        infx = item[5]
                    if item[5] == '':
                        infx = item[4]
                    if self.curmode == self.optionPast:
                        infy = '.' + item[6]
                    else:
                        infy = ''

                    self.listboxId.insert('end', \
                        item[0] + '.'*(6 - len(item[0])) \
                        + item[1][:10] + '.'*(12 - len(item[1][:10])) \
                        + info + '.'*(15 - len(info[:14])) \
                        + item[3][:18] + '.'*(20 - len(item[3][:14])) \
                        + infx[:45] + '.'*(47-len(infx[:45])) \
                        + infy)

                    
                



    def morerows(self, label, columnm, columnn, limit, *args):
        self.redditlabel = Label(self,text=label)
        self.redditlabel.grid(row=self.newrowindex,column=columnm, sticky="e")
        self.labellist.append(self.redditlabel)

        self.redditentry = Entry(self)
        self.redditentry.grid(row=self.newrowindex,column=columnn, columnspan=9)
        self.entrylist.append(self.redditentry)

        self.newrowindex += 1
        if self.newrowindex >= limit:
            self.morerowbutton.grid_forget()
        print(self.newrowindex)
    def initUI( self ):

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

        #setting font
        FONT = ('serif', 10)

        #setting UI grid
        self.columnconfigure(0, weight=1)
        self.columnconfigure(2, pad=10)
        self.rowconfigure(6, pad=200, weight=1)

        #setting widgets

        #Label
        available_lb = Label( self, text='Availabel sessions:', font=FONT )
        available_lb.grid( row=0, column=0, sticky=W )

        #list
        y_scroll = Scrollbar( self, orient=VERTICAL )
        y_scroll.grid( row=1, column=1, rowspan=9, sticky=N+S )

        self.script_list = Listbox( self, bg='white', font=FONT, selectmode=SINGLE,
            yscrollcommand=y_scroll.set )
        self.script_list.grid( row=1, column=0, rowspan=9, sticky=W+E+N+S )

        #button
        exec_btn = Button( self, text='Execute', width=6, font=FONT, 
            command=self.execute )
        exec_btn.grid( row=1, column=2 )

        copy_btn = Button( self, text='Copy', width=6, font=FONT, 
            command=self.copyCheck )
        copy_btn.grid( row=3, column=2 )

        create_btn = Button( self, text='Create', width=6, font=FONT, 
            command=lambda:self.popWidget( self.createFile ) )
        create_btn.grid( row=2, column=2 )

        edit_btn = Button( self, text='Edit', width=6, font=FONT, command=self.editFile )
        edit_btn.grid( row=4, column=2 )

        delete_btn = Button( self, text='Delete', width=6, font=FONT, 
            command=self.deleteFile )
        delete_btn.grid( row=5, column=2 )

        help_btn = Button( self, text='Help', width=6, font=FONT, command=self.usageHelp )
        help_btn.grid( row=7, column=3, sticky=E )

        abt_btn = Button( self, text='About', width=6, font=FONT, command=self.about )
        abt_btn.grid( row=8, column=3, sticky=E )

        quit_btn = Button( self, text='Quit', width=6, font=FONT, command=self.quit )
        quit_btn.grid( row=9, column=3, sticky=E )

        #Option
        lbl2 = Label( self, text='Exeuction Options:' )
        lbl2.grid( row=0, column=3, sticky=W )

        execute_with_term = Checkbutton( self, text='Execute with terminal',
            variable=self.opt_exec_with_term )
        execute_with_term.grid( row=1, column=3, sticky=E )
Пример #46
0
class UITree(Frame):
    def __init__(self, uicontroller, master, **options):
        super().__init__(master, **options)
        self.uicontroller = uicontroller
        self.tree = None
        self.ui_tree = None

        self.scrollbarvirt = Scrollbar(self)
        self.scrollbarhoriz = Scrollbar(self, orient=HORIZONTAL)

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

        self.scrollbarvirt.grid(row=0, column=1, sticky='nes')
        self.scrollbarhoriz.grid(row=1, column=0, sticky='wes')

        self.set_handle_tree()

    def config_new_tree(self):
        if self.tree is not None:
            self.tree.destroy()

        self.tree = ItemTreeview(self, columns=('ui type',))

        self.tree.heading('ui type', text='UI Element Type')
        self.tree.column('ui type', anchor='center', width=120, stretch=False)

        self.tree.tag_configure('odd_row', background='light grey')
        self.tree.tag_configure('even_row', background='white')

        self.scrollbarvirt.configure(command=self.tree.yview)
        self.tree.configure(yscrollcommand=self.scrollbarvirt.set)

        self.scrollbarhoriz.configure(command=self.tree.xview)
        self.tree.configure(xscrollcommand=self.scrollbarhoriz.set)

        self.tree.grid(row=0, column=0, sticky='news')

    def set_handle_tree(self, parent='', tree=None):
        if tree is None:
            self.config_new_tree()
            tree = self.uicontroller.get_ui_tree()

        is_even = True
        tags = {True: 'even_row', False: 'odd_row'}

        nodes = sorted(list(tree), key=lambda node: _get_sort_description(node))
        for node in nodes:
            if node[0].parent is None and len(node[1]) == 0:
                continue

            text = _get_node_description(node[0])
            typename = node[0].nodeclass
            typename = typename[typename.rfind('.') + 1:typename.rfind("'")]

            inserted = self.tree.insert_tracked(node[0], parent, 'end', text=text, values=typename, tags=tags[is_even])
            self.set_handle_tree(parent=inserted, tree=node[1])

            is_even = not is_even

    def get_selected(self):
        return self.tree.get_item()
class SpeciesSearchDialog:
    def __init__(self, parent, caller):
        # main window
        self.parent = parent
        # dialog that called this second dialog
        self.caller = caller
        self.gui = Toplevel(parent.guiRoot)
        self.gui.grab_set()
        self.gui.focus()

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

        self.entrySearch = Entry(self.gui)

        self.buttonSearch = Button(self.gui, text=" Search ")
        self.buttonAdd = Button(self.gui, text=" Add Species ")
        self.buttonClose = Button(self.gui, text=" Close Window ")

        self.frameResults = Frame(self.gui)
        self.frameResults.columnconfigure(0, weight=1)
        self.frameResults.rowconfigure(0, weight=1)
        self.scrollResults = Scrollbar(self.frameResults, orient="vertical")
        self.scrollResults.grid(row=0, column=1, sticky="ns")
        self.listResults = Listbox(self.frameResults, width=70, height=20)
        self.listResults.grid(row=0, column=0, sticky="nswe")

        self.listResults.config(yscrollcommand=self.scrollResults.set)
        self.scrollResults.config(command=self.listResults.yview)

        self.entrySearch.grid(row=0, column=0, columnspan=2, sticky="we", padx=5, pady=5)
        self.frameResults.grid(row=1, column=0, columnspan=3, sticky="nswe", padx=5, pady=5)
        self.buttonSearch.grid(row=0, column=2, padx=5, pady=5, sticky="e")
        self.buttonAdd.grid(row=2, column=1, padx=5, pady=5, sticky="e")
        self.buttonClose.grid(row=2, column=2, padx=5, pady=5, sticky="e")

        self.gui.protocol("WM_DELETE_WINDOW", self.actionClose)
        self.buttonClose.bind("<ButtonRelease>", self.actionClose)
        self.buttonAdd.bind("<ButtonRelease>", self.actionAdd)
        self.buttonSearch.bind("<ButtonRelease>", self.actionSearch)
        self.entrySearch.bind("<Return>", self.actionSearch)

        self.gui.update()
        self.gui.minsize(self.gui.winfo_width(), self.gui.winfo_height())

        self.gui.mainloop()

    def actionAdd(self, event):
        try:
            selection = self.listResults.selection_get()
            selectionSplit = selection.split(":\t", 1)
            selectionSplit2 = selectionSplit[1].split("\t")
            if not (selectionSplit[0], selectionSplit2[0]) in self.parent.optimizer.speciesList:
                self.parent.optimizer.speciesList.append((selectionSplit[0], selectionSplit2[0].strip()))
            self.caller.gui.event_generate("<<Update>>")
        except tkinter.TclError:
            # no selection
            pass

    def actionSearch(self, event):
        query = self.entrySearch.get()
        if query:

            self.listResults.delete(0, "end")

            results = self.parent.optimizer.SPSUMHandler.search(query)
            # sort results by nr of CDS
            results = sorted(results.items(), reverse=True, key=lambda x: (int(x[1][1])))
            for name, (taxid, ncs) in results:
                self.listResults.insert("end", taxid + ":\t " + name + " \t(" + ncs + " CDS)")

    def actionClose(self, event=None):
        self.caller.gui.event_generate("<<Update>>", when="tail")
        self.gui.destroy()
Пример #48
0
def sample_test():
    from tkinter import Tk, Scrollbar, N, S, W, E, ttk
    import numpy

    def test_cmd(event):
        if event.i == 0:
            return arr[event.r, event.c]
        else:
            arr[event.r, event.c] = event.S
            return 'set'

    def browsecmd(event):
        print("event:", event.__dict__)
        print("curselection:", test.curselection())
        print("active cell index:", test.index('active'))
        activeRow = int(test.index('active', 'row'))
        activeCol = int(test.index('active', 'col'))
        print("active:", activeRow)
        print("anchor:", test.index('anchor', 'row'))
        # the following line is operational, it shows that it is possible
        # to modiy programmatically the content of a cell.
        # var[test.index('active')] = 'toto'

    def comboValueChanged(event):
        combobox = event.widget
        print('Selected value in combobox: '+combobox.get())

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

    numrows, numcols = 6250,40

    #Using ArrayVar consumes double as much memory as NumPy+command 
    #var = ArrayVar(root)
    #for y in range(0, numrows):
    #    for x in range(0, numcols):
    #        index = "%i,%i" % (y, x)
    #        var[index] = index
    arr = numpy.empty((numrows+2, numcols), dtype=object)
    for y in range(numrows):
        for x in range(numcols):
            arr[y, x] = "%i,%i" % (y, x)

    test = Table(root,
                 rows=numrows,
                 cols=numcols,
                 state='normal',
                 width=6,
                 height=6,
                 titlerows=2,
                 titlecols=2,
                 roworigin=0,
                 colorigin=0,
                 selectmode='extended',
                 selecttype='cell',
                 rowstretch='last',
                 colstretch='last',
                 rowheight=-26,
                 colwidth=15,
                 browsecmd=browsecmd,
                 flashmode='off',
                 anchor='e',
                 #variable=var,
                 usecommand=1,
                 background='#fffffffff',
                 relief='sunken',
                 command=test_cmd,
                 takefocus=False,
                 rowseparator='\n'
                 # drawmode='slow'
                 )

    # http://effbot.org/zone/tkinter-scrollbar-patterns.htm
    verticalScrollbar = Scrollbar(root, orient='vertical', command=test.yview_scroll)
    horizontalScrollbar = Scrollbar(root, orient='horizontal', command=test.xview_scroll)
    test.config(xscrollcommand=horizontalScrollbar.set, yscrollcommand=verticalScrollbar.set)
    verticalScrollbar.grid(column="1", row='0', sticky=(N, S))
    horizontalScrollbar.grid(column="0", row='1', sticky=(W, E))

    kwargs = {'4,5': '5,3', '0,0': '0,1'}
    test.spans(index=None, **kwargs)
    for y in range(2, numrows):
        for x in range(2, numcols):
            if (x%2==0 and y%2==1) or (x%2==1 and y%2==0):
                index = "%i,%i" % (y, x)
                test.tag_cell('disabled', index)
    for x in range(2, numcols):
        index = "%i,%i" % (0, x)
        test.tag_cell('border', index)
        index = "%i,%i" % (1, x)
        test.tag_cell('border', index)
    for y in range(1, numrows):
        index = "%i,%i" % (y, 0)
        test.tag_cell('border-left-right', index)
        index = "%i,%i" % (y, 1)
        test.tag_cell('border', index)
    
    for y in range(2, numrows):
        cities = ('Brussels', 'Luxembourg', 'Strasbourg', 'Trier', 'Rome')
        combobox = ttk.Combobox(test, values=cities, state='readonly')
        test.window_configure('%i,9'%y, window=combobox, sticky=(N, E, S, W))
        combobox.bind(sequence='<<ComboboxSelected>>',
                      func=comboValueChanged,
                      add='+')

    def cellRight(event, *args):
        widget = event.widget
        titleRows = int(widget.cget('titlerows'))
        titleCols = int(widget.cget('titlecols'))
        top = int(widget.cget('roworigin'))+titleRows
        left = int(widget.cget('colorigin'))+titleCols
        try:
            col = int(widget.index('active', 'col'))
            row = int(widget.index('active', 'row'))
        except (tkinter.TclError):
            row, col = top-1, left
        maxRows = int(widget.cget('rows'))
        maxCols = int(widget.cget('cols'))

        widget.selection_clear('all')
        if row<top:
            if (col<left):
                index = '%i,%i'% (top, left)
            else:
                index = '%i,%i'% (top, col)
            widget.activate(index)
            widget.see(index)
            widget.selection_set(index)
        elif col<left:
            index = '%i,%i'% (row, left)
            widget.activate(index)
            widget.see(index)
            widget.selection_set(index)
        elif col<maxCols-titleCols-1:
            widget.moveCell(0, 1)
        elif row<maxRows-titleCols-1:
            widget.moveCell(1, left-col)
        else:
            widget.moveCell(top-row, left-col)

    def cellDown(event, *args):
        widget = event.widget
        titleRows = int(widget.cget('titlerows'))
        titleCols = int(widget.cget('titlecols'))
        top = int(widget.cget('roworigin'))+titleRows
        left = int(widget.cget('colorigin'))+titleCols
        try:
            col = int(widget.index('active', 'col'))
            row = int(widget.index('active', 'row'))
        except (tkinter.TclError):
            row, col = top-1, left
        maxRows = int(widget.cget('rows'))
        maxCols = int(widget.cget('cols'))

        widget.selection_clear('all')
        if row<top:
            if (col<left):
                index = '%i,%i'% (top, left)
            else:
                index = '%i,%i'% (top, col)
            widget.activate(index)
            widget.see(index)
            widget.selection_set(index)
        elif col<left:
            index = '%i,%i'% (row, left)
            widget.activate(index)
            widget.see(index)
            widget.selection_set(index)
        elif row<maxRows-titleRows-1:
            widget.moveCell(1, 0)
        elif col<maxCols-titleCols-1:
            widget.moveCell(top-row, 1)
        else:
            widget.moveCell(top-row, left-col)
        return 'break' # do not insert return in cell content

    menu = test.contextMenu()
    menu.add_command(label="Quit", underline=0, command=root.destroy)
    test.bind("<Tab>", func=cellRight, add="+")
    test.bind("<Return>", func=cellDown)
    test.tag_cell('border-left-top', "-2,-2")
    test.tag_raise('border-left-top', abovethis='title')
    test.tag_raise('border-left-right', abovethis='title')
    test.tag_raise('border', abovethis='title')
    test.grid(column="0", row='0', sticky=(N, W, S, E))
    test.tag_configure('sel', background = '#000400400')
    test.tag_configure('active', background = '#000a00a00')
    test.tag_configure('title', anchor='w', bg='#d00d00d00', fg='#000000000', relief='flat')
    test.tag_configure('disabled', bg='#d00d00d00', fg='#000000000', relief='flat', state='disabled')
    test.tag_configure('border-left-top', relief='ridge', borderwidth=(1,0,1,0))
    test.tag_configure('border-left-right', relief='ridge', borderwidth=(1,1,0,0))
    test.tag_configure('border', relief='ridge', borderwidth=(1,1,1,1))

    data = ('py','t','h','o','n','','+','','Tk','')

    def add_new_data(*args):
        #test.config(state='normal')
        test.insert_rows('end', 1)
        r = test.index('end').split(',')[0] #get row number <str>
        args = (r,) + args
        idx = r + ',1'
        test.set('row', idx, *args)
        test.see(idx)
        #test.config(state='disabled')

    root.after(3000, add_new_data, *data)
    root.after(4000, add_new_data, *data)
    root.mainloop()
Пример #49
0
class DownloadUI(ttk.Frame):
    def __init__(self):
        self.root = Tk()
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        self.parent = ttk.Frame(self.root)
        self.parent.grid(column=0, row=0, sticky=(N, S, E, W))
        self.parent.columnconfigure(0, weight=1)
        self.parent.rowconfigure(0, weight=1)
        ttk.Frame.__init__(self, self.parent, padding=(6, 6, 14, 2))
        self.grid(column=0, row=0, sticky=(N, S, E, W))
        self.columnconfigure(0, weight=1)
        self.rowconfigure(2, weight=1)

        self.root.title("Curse Pack Downloader v%s" % cursePackDownloaderVersion)

        self.manifestPath = StringVar()

        chooser_container = ttk.Frame(self)
        self.chooserText = ttk.Label(chooser_container, text="Locate your manifest.json: ")
        chooser_entry = ttk.Entry(chooser_container, textvariable=self.manifestPath)
        self.chooserButton = ttk.Button(chooser_container, text="Browse", command=self.choose_file)
        self.chooserText.grid(column=0, row=0, sticky=W)
        chooser_entry.grid(column=1, row=0, sticky=(E, W), padx=5)
        self.chooserButton.grid(column=2, row=0, sticky=E)
        chooser_container.grid(column=0, row=0, sticky=(E, W))
        chooser_container.columnconfigure(1, weight=1)
        self.downloadButton = ttk.Button(self, text="Download mods", command=self.go_download)
        self.downloadButton.grid(column=0, row=1, sticky=(E, W))

        self.logText = Text(self, state="disabled", wrap="none")
        self.logText.grid(column=0, row=2, sticky=(N, E, S, W))

        self.logScroll = Scrollbar(self, command=self.logText.yview)
        self.logScroll.grid(column=1, row=2, sticky=(N, E, S, W))
        self.logText['yscrollcommand'] = self.logScroll.set

        # *** Progress Bars Frame ***
        progress_bars = ttk.Frame(padding=(6, 2, 14, 2))
        progress_bars.grid(column=0, row=1, sticky=(E, W))
        progress_bars.columnconfigure(1, weight=1)

        # *** Total Un-Pack Progress ***
        self.tl_progressText = ttk.Label(progress_bars, text="Total Unpacking Progress: ")
        self.tl_progressText.grid(column=0, row=0, sticky=E)
        self.tl_progress = ttk.Progressbar(progress_bars, orient="horizontal",
                                           length=200, mode="determinate")
        self.tl_progress.grid(column=1, row=0, sticky=(E, W))
        self.tl_progress["value"] = 0
        self.tl_progress["maximum"] = 100

        # *** Download Progress ***
        self.dl_progressText = ttk.Label(progress_bars, text="Current Download Progress: ")
        self.dl_progressText.grid(column=0, row=1, sticky=E)
        self.dl_progress = ttk.Progressbar(progress_bars, orient="horizontal",
                                           length=200, mode="determinate")
        self.dl_progress.grid(column=1, row=1, sticky=(E, W))
        self.dl_progress["value"] = 0
        self.dl_progress["maximum"] = 100

    def choose_file(self):
        file_path = filedialog.askopenfilename(
            filetypes=(("Json files", "*.json"),),
            initialdir=os.path.expanduser("~"),
            parent=self)
        self.manifestPath.set(file_path)
        # Reset bars if user select old/new manifest.
        programGui.tl_progress["value"] = 0
        programGui.dl_progress["value"] = 0

    def go_download(self):
        t = Thread(target=self.go_download_background)
        t.start()

    def go_download_background(self):
        self.downloadButton.configure(state="disabled")
        self.chooserButton.configure(state="disabled")
        do_download(self.manifestPath.get())
        self.downloadButton.configure(state="enabled")
        self.chooserButton.configure(state="enabled")

    def set_output(self, message):
        self.logText["state"] = "normal"
        self.logText.insert("end", message + "\n")
        self.logText["state"] = "disabled"
        self.logText.see(END)

    def set_manifest(self, file_name):
        self.manifestPath.set(file_name)
Пример #50
0
        logfile.insert('end', line)
        logfile.see("end")
        line = f.readline()
    logfile.after(100, tail, f)


root = Tk()
""""
def callback():
	not(autoscroll)
"""
logframe = Frame(root, relief='ridge', bd=2)
logframe.grid_rowconfigure(0, weight=1)
logframe.grid_columnconfigure(0, weight=1)
sb = Scrollbar(logframe)
sb.grid(row=0, column=1, sticky='n s')
logfile = Text(logframe, wrap='word', yscrollcommand=sb.set)
logfile.grid(row=0, column=0, sticky='n s e w')
sb.config(command=logfile.yview)
logframe.pack()
"""b = Button(root, text = "autoscroll", command = callback )
b.pack(side=BOTTOM)
b.config(state = ACTIVE)
"""
termf = Frame(root, height=200, width=500, relief='ridge', bd=2)
termf.pack()
wid = termf.winfo_id()
os.system('urxvt -embed {} -geometry 500x200 -e python3 -i -c "from {} import*" &'.format(wid, sys.argv[1]))

tail(open(sys.argv[2]))
Пример #51
0
class PypeTkPad(object):

    def __init__(self, master, queue, pypeOutput):
      
        self.queue = queue
        self.pypeOutput = pypeOutput

        self.master = master
        self.master.title('PypePad')
        self.master.geometry("%dx%d%+d%+d" % (700, 500, 0, 0))
        self.master.minsize(300, 100)
        self.output_file_name = None
        
        self.BuildMainFrame()
        self.UpdateOutput()

    def NewCommand(self):
        self.ClearAllCommand()

    def OpenCommand(self):
        import tkinter.filedialog
        from tkinter import END
        openfile = tkinter.filedialog.askopenfile()
        if not openfile:
            return
        for line in openfile.readlines():
            self.text_input.insert(END,line)
 
    def SaveCommand(self):
        import tkinter.filedialog
        from tkinter import END
        saveasfile = tkinter.filedialog.asksaveasfile()
        if not saveasfile:
            return
        alltext = self.text_input.get("1.0",END)
        saveasfile.write(alltext)
 
    def QuitCommand(self):
        self.master.quit()

    def ClearInputCommand(self):
        from tkinter import END
        self.text_input.delete("1.0",END)
        
    def ClearOutputCommand(self):
        from tkinter import NORMAL, END, DISABLED
        self.text_output["state"] = NORMAL
        self.text_output.delete("1.0",END)
        self.text_output["state"] = DISABLED
        self.text_output.see(END)
        self.text_output.update()
        
    def ClearAllCommand(self):
        self.ClearInputCommand()
        self.ClearOutputCommand()

    def OutputFileCommand(self):
        import tkinter.filedialog
        outputfilename = tkinter.filedialog.asksaveasfilename()
        if sys.platform == 'win32' and len(outputfilename.split()) > 1:
            outputfilename = '"%s"' % outputfilename
        self.output_file_name = outputfilename

    def AboutCommand(self):
        self.OutputText('\n')
        self.OutputText('* PypePad, Copyright (c) Luca Antiga, David Steinman. *\n')
        self.OutputText('\n')

    def UpdateOutput(self):
        if self.pypeOutput:
            text = self.pypeOutput.pop(0)
            self.output_stream.write(text)
        self.master.after(10,self.UpdateOutput)

    def RunPype(self,arguments):
        if not arguments:
            return
        if self.output_to_file.get() is not 'n' and self.output_file_name:
            self.output_stream.output_to_file = True
            self.output_stream.output_file = open(self.output_file_name,self.output_to_file.get())
        else:
            self.output_stream.output_to_file = False

        self.queue.append(arguments)
 
    def GetWordUnderCursor(self):
        from tkinter import CURRENT
        splitindex = self.text_input.index(CURRENT).split('.')
        line = self.text_input.get(splitindex[0]+".0",splitindex[0]+".end")
        wordstart = line.rfind(' ',0,int(splitindex[1])-1)+1
        wordend = line.find(' ',int(splitindex[1]))
        if wordend == -1:
            wordend = len(line)
        word = line[wordstart:wordend]
        return word

    def GetWordIndex(self):
        startindex = self.text_input.index("insert-1c wordstart")
        endindex = self.text_input.index("insert-1c wordend")
        if self.text_input.get(startindex+'-1c') == '-' and self.text_input.get(startindex+'-2c') == '-':
           startindex = self.text_input.index("insert-1c wordstart -2c") 
        elif self.text_input.get(startindex+'-1c') == '-' and self.text_input.get(startindex+'-2c') == ' ':
           startindex = self.text_input.index("insert-1c wordstart -1c")
        self.wordIndex[0] = startindex
        self.wordIndex[1] = endindex
        word = self.text_input.get(self.wordIndex[0],self.wordIndex[1])
        return word

    def GetLogicalLine(self,physicallineid):
        indexes, lines = self.GetLogicalLines()
        return lines[indexes[physicallineid]]
 
    def GetLogicalLineRange(self,physicallinefirstid,physicallinelastid):
        indexes, lines = self.GetLogicalLines()
        return lines[indexes[physicallinefirstid]:indexes[physicallinelastid]+1]
   
    def GetAllLogicalLines(self):
        return self.GetLogicalLines()[1]
   
    def GetLogicalLines(self):
        from tkinter import END
        # Python 2 hack to remove the u'...' prefix from unicode literal strings. does not change py3 behavior
        physicallines = [str(line) for line in self.text_input.get("1.0",END).split('\n')]
        lines = []
        indexes = [0] * len(physicallines)
        lineid = 0
        previousline = ""
        join = 0
        for line in physicallines:
            if line.startswith('#'):
                if join:
                    indexes[lineid] = indexes[lineid-1]
            elif join:
                if line.endswith('\\'):
                    lines[-1] = lines[-1] + " " + line[:-1]
                    join = 1
                else:
                    lines[-1] = lines[-1] + " " + line
                    join = 0
                indexes[lineid] = indexes[lineid-1]
            else:
                if line.endswith('\\'):
                    join = 1
                    lines.append(line[:-1])
                else:
                    lines.append(line)
                    join = 0
                if lineid > 0:
                    indexes[lineid] = indexes[lineid-1]+1
            lineid += 1
        return indexes, lines

    def GetLineUnderCursor(self):
        from tkinter import INSERT
        currentlineid = int(self.text_input.index(INSERT).split('.')[0]) - 1
        return self.GetLogicalLine(currentlineid)

    def RunAllCommand(self):
        lines = self.GetAllLogicalLines()
        for line in lines:
            if line and line.strip():
                self.RunPype(line)

    def RunLineCommand(self):
        line = self.GetLineUnderCursor()
        if line and line.strip():
            self.RunPype(line)
      
    def RunSelectionCommand(self):
        from tkinter import TclError, SEL_FIRST, SEL_LAST
        try:
            firstlineid = int(self.text_input.index(SEL_FIRST).split('.')[0]) - 1
            lastlineid = int(self.text_input.index(SEL_LAST).split('.')[0]) - 1
            lines = self.GetLogicalLineRange(firstlineid,lastlineid)
            for line in lines:
                self.RunPype(line)
        except TclError:
            pass

    def GetSuggestionsList(self,word):
        list = []
        try:
            from vmtk import vmtkscripts
            from vmtk import pypes
        except ImportError:
            return None
        if word.startswith('--'):
            list = ['--pipe','--help']
        elif word.startswith('-'):
            optionlist = []
            scriptindex = self.text_input.search('vmtk',self.wordIndex[0],backwards=1)
            moduleName  = self.text_input.get( scriptindex,scriptindex+' wordend' )
            try:
                module = importlib.import_module('vmtk.'+moduleName)
                # Find the principle class to instantiate the requested action defined inside the requested writerModule script.
                # Returns a single member list (containing the principle class name) which satisfies the following criteria:
                #   1) is a class defined within the script
                #   2) the class is a subclass of pypes.pypescript
                scriptObjectClasses = [x for x in dir(module) if isclass(getattr(module, x)) and issubclass(getattr(module, x), pypes.pypeScript)]
                scriptObjectClassName = scriptObjectClasses[0]
                scriptObject = getattr(module, scriptObjectClassName)
                scriptObject = scriptObject()
                members = scriptObject.InputMembers + scriptObject.OutputMembers
                for member in members:
                    optionlist.append('-'+member.OptionName)
                list = [option for option in optionlist if option.count(word)]
            except:
                return list
        else:
            list = [scriptname for scriptname in vmtkscripts.__all__ if scriptname.count(word)]
            for index, item in enumerate(list):
                # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user.
                if 'vmtk.' == item[0:5]:
                    splitList = item.split('.')
                    list[index] = splitList[1]
                else:
                    continue
        return list

    def FillSuggestionsList(self,word):
        from tkinter import END
        self.suggestionslist.delete(0,END)
        suggestions = self.GetSuggestionsList(word)
        for suggestion in suggestions:
            self.suggestionslist.insert(END,suggestion)

    def ReplaceTextCommand(self,word):
        self.text_input.delete(self.wordIndex[0],self.wordIndex[1])
        self.text_input.insert(self.wordIndex[0],word)
        self.text_input.focus_set()

    def ShowHelpCommand(self):
        word = self.GetWordUnderCursor()
        self.OutputText(word)
        if word:
            self.RunPype(word+' --help')
        else: 
            self.OutputText('Enter your vmtk Pype above and Run.\n')

    def AutoCompleteCommand(self):
        word = self.GetWordIndex()
        self.suggestionswindow.withdraw()
        if word:
            self.FillSuggestionsList(word)
            self.suggestionswindow.geometry("%dx%d%+d%+d" % (400, 150, self.text_output.winfo_rootx(),self.text_output.winfo_rooty()))
            self.suggestionswindow.deiconify()
            self.suggestionswindow.lift()
            
    def InsertScriptName(self,scriptname):
        from tkinter import INSERT
        self.text_input.insert(INSERT,scriptname+' ')
        
    def InsertFileName(self):
        from tkinter import INSERT
        import tkinter.filedialog
        openfilename = tkinter.filedialog.askopenfilename()
        if not openfilename:
            return
        if len(openfilename.split()) > 1:
            openfilename = '"%s"' % openfilename
        self.text_input.insert(INSERT,openfilename+' ')

    def KeyPressHandler(self,event):
        if event.keysym == "Tab" :
            self.AutoCompleteCommand()
            self.suggestionslist.focus_set()
            self.suggestionslist.selection_set(0)
            return "break"
        else:
            self.text_input.focus_set()

    def TopKeyPressHandler(self,event):
        from tkinter import ACTIVE, INSERT
        if event.keysym in ['Down','Up'] :
            self.suggestionslist.focus_set()
        elif event.keysym == "Return":
            word = self.suggestionslist.get(ACTIVE)
            self.ReplaceTextCommand(word)
            self.suggestionswindow.withdraw()
            self.text_input.focus_set()
        elif len(event.keysym) == 1 :
            self.suggestionswindow.withdraw()
            self.text_input.insert(INSERT,event.keysym)
            self.text_input.focus_set()
        else :
            self.suggestionswindow.withdraw()
            self.text_input.focus_set()
    
    def NewHandler(self,event):
        self.NewCommand() 

    def OpenHandler(self,event):
        self.OpenCommand()

    def SaveHandler(self,event):
        self.SaveCommand()

    def InsertFileNameHandler(self,event):
        self.InsertFileName()
        return "break"
 
    def QuitHandler(self,event):
        self.QuitCommand()

    def ShowHelpHandler(self,event):
        self.ShowHelpCommand()

    def RunKeyboardHandler(self,event):
        from tkinter import SEL_FIRST, TclError
        try: 
            self.text_input.index(SEL_FIRST)
            self.RunSelectionCommand()
        except TclError:
            self.RunLineCommand()
        return "break"
         
    def RunAllHandler(self,event):
        self.RunAllCommand()
      
    def PopupHandler(self,event):
        try:
            self.popupmenu.tk_popup(event.x_root, event.y_root, 0)
        finally:
            self.popupmenu.grab_release()

    def OutputText(self,text):
        from tkinter import NORMAL, END, DISABLED
        self.text_output["state"] = NORMAL
        self.text_output.insert(END,text)
        self.text_output["state"] = DISABLED

    def BuildScriptMenu(self,parentmenu,modulename):
        from tkinter import Menu
        menu = Menu(parentmenu,bd=1,activeborderwidth=0)
        try:
            module = importlib.import_module('vmtk.'+modulename)
        except ImportError:
            return None
        scriptnames = [scriptname for scriptname in getattr(module, '__all__')]
        for index, scriptname in enumerate(scriptnames):
            # check if scriptname contains starting prefix 'vmtk.' and remove it before returning list to the user.
            if 'vmtk.' == scriptname[0:5]:
                splitList = scriptname.split('.')
                scriptnames[index] = splitList[1]
            else:
                continue
        menulength = 20
        for i in range(len(scriptnames)//menulength+1):
            subscriptnames = scriptnames[i*menulength:(i+1)*menulength]
            if not subscriptnames:
                break 
            submenu = Menu(menu,bd=1,activeborderwidth=0)
            menu.add_cascade(label=subscriptnames[0]+"...",menu=submenu)
            for scriptname in subscriptnames:
                callback = CallbackShim(self.InsertScriptName,scriptname)
                submenu.add_command(label=scriptname,command=callback)
        return menu 

    def BuildMainFrame(self): 
        from tkinter import Menu, IntVar, StringVar, Toplevel, Listbox, Frame, PanedWindow, Text, Scrollbar, Entry
        from tkinter import X, N, S, W, E, VERTICAL, TOP, END, DISABLED, RAISED

        menu = Menu(self.master,activeborderwidth=0,bd=0)
        self.master.config(menu=menu)
  
        filemenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="File", underline=0,  menu=filemenu)
        filemenu.add_command(label="New", accelerator='Ctrl+N',command=self.NewCommand)
        filemenu.add_command(label="Open...",accelerator='Ctrl+O', command=self.OpenCommand)
        filemenu.add_command(label="Save as...",accelerator='Ctrl+S', command=self.SaveCommand)
        filemenu.add_separator()
        filemenu.add_command(label="Quit",accelerator='Ctrl+Q', command=self.QuitCommand)

        self.log_on = IntVar()
        self.log_on.set(1)
  
        self.output_to_file = StringVar()
        self.output_to_file.set('n')
 
        scriptmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        modulenames = ['vmtkscripts']
        for modulename in modulenames:
            scriptsubmenu = self.BuildScriptMenu(menu,modulename)
            if scriptsubmenu:
                scriptmenu.add_cascade(label=modulename,menu=scriptsubmenu)
 
        editmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Edit",underline=0,  menu=editmenu)
        editmenu.add_cascade(label="Insert script",menu=scriptmenu)
        editmenu.add_command(label="Insert file name", accelerator='Ctrl+F',command=self.InsertFileName)
        editmenu.add_separator()
        editmenu.add_command(label="Clear input", command=self.ClearInputCommand)
        editmenu.add_command(label="Clear output", command=self.ClearOutputCommand)
        editmenu.add_command(label="Clear all", command=self.ClearAllCommand)
        editmenu.add_separator()
        editmenu.add_checkbutton(label="Log", variable=self.log_on)
        editmenu.add_separator()
        editmenu.add_radiobutton(label="No output to file", variable=self.output_to_file,value='n')
        editmenu.add_radiobutton(label="Write output to file", variable=self.output_to_file,value='w')
        editmenu.add_radiobutton(label="Append output to file", variable=self.output_to_file,value='a')
        editmenu.add_command(label="Output file...", command=self.OutputFileCommand)

        runmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Run", underline=0, menu=runmenu)
        runmenu.add_command(label="Run all", command=self.RunAllCommand)
        runmenu.add_command(label="Run current line", command=self.RunLineCommand)
        runmenu.add_command(label="Run selection", command=self.RunSelectionCommand)
       
        helpmenu = Menu(menu,tearoff=0,bd=1,activeborderwidth=0)
        menu.add_cascade(label="Help", underline=0, menu=helpmenu)
        helpmenu.add_command(label="Help", underline=0, accelerator='F1',command=self.ShowHelpCommand)
        helpmenu.add_command(label="About", underline=0, command=self.AboutCommand)

        self.master.bind("<Control-KeyPress-q>", self.QuitHandler)
        self.master.bind("<Control-KeyPress-n>", self.NewHandler)
        self.master.bind("<Control-KeyPress-o>", self.OpenHandler)
        self.master.bind("<Control-KeyPress-s>", self.SaveHandler)
        self.master.bind("<Control-KeyPress-f>", self.InsertFileNameHandler)
        self.master.bind("<KeyPress-F1>", self.ShowHelpHandler)
        self.master.bind("<KeyPress>", self.KeyPressHandler)
        
        self.wordIndex = ['1.0','1.0']
               
        self.suggestionswindow = Toplevel(bg='#ffffff',bd=0,height=50,width=600,highlightthickness=0,takefocus=True)
        self.suggestionswindow.overrideredirect(1)
        self.suggestionslist = Listbox(self.suggestionswindow,bg='#ffffff',bd=1,fg='#336699',activestyle='none',highlightthickness=0,height=9)
        self.suggestionslist.insert(END,"foo")
        self.suggestionslist.pack(side=TOP,fill=X)
        self.suggestionswindow.bind("<KeyPress>", self.TopKeyPressHandler)
        self.suggestionswindow.withdraw()

        self.master.rowconfigure(0,weight=1)
        self.master.columnconfigure(0,weight=1)
        content = Frame(self.master,bd=0,padx=2,pady=2) 
        content.grid(row=0,column=0,sticky=N+S+W+E)
        content.rowconfigure(0,weight=1,minsize=50)
        content.rowconfigure(1,weight=0)
        content.columnconfigure(0,weight=1)

        panes = PanedWindow(content,orient=VERTICAL,bd=1,sashwidth=8,sashpad=0,sashrelief=RAISED,showhandle=True)
        panes.grid(row=0,column=0,sticky=N+S+W+E)

        frame1 = Frame(panes,bd=0) 
        frame1.grid(row=0,column=0,sticky=N+S+W+E)
        frame1.columnconfigure(0,weight=1)
        frame1.columnconfigure(1,weight=0)
        frame1.rowconfigure(0,weight=1)

        panes.add(frame1,height=300,minsize=20)        

        frame2 = Frame(panes,bd=0) 
        frame2.grid(row=1,column=0,sticky=N+S+W+E)
        frame2.columnconfigure(0,weight=1)
        frame2.columnconfigure(1,weight=0)
        frame2.rowconfigure(0,weight=1)
        
        panes.add(frame2,minsize=20) 
 
        self.text_input = Text(frame1, bg='#ffffff',bd=1,highlightthickness=0)

        self.text_input.bind("<KeyPress>", self.KeyPressHandler)
        self.text_input.bind("<Button-3>", self.PopupHandler)
        self.text_input.bind("<Control-Return>", self.RunKeyboardHandler)
 
        self.input_scrollbar = Scrollbar(frame1,orient=VERTICAL,command=self.text_input.yview)
        self.text_input["yscrollcommand"] = self.input_scrollbar.set    

        self.text_output = Text(frame2,state=DISABLED,bd=1,bg='#ffffff',highlightthickness=0)
        
        self.output_scrollbar = Scrollbar(frame2,orient=VERTICAL,command=self.text_output.yview)
        self.text_output["yscrollcommand"] = self.output_scrollbar.set    
      
        self.text_entry = Entry(content,bd=1,bg='#ffffff',state=DISABLED,highlightthickness=0)

        self.text_input.focus_set()

        self.text_input.grid(row=0,column=0,sticky=N+S+W+E)
        self.input_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_output.grid(row=0,column=0,sticky=N+S+W+E)
        self.output_scrollbar.grid(row=0,column=1,sticky=N+S+W+E)
        self.text_entry.grid(row=1,column=0,sticky=N+S+W+E)

        self.popupmenu = Menu(self.text_input, tearoff=1, bd=0)
        self.popupmenu.add_command(label="Context help", command=self.ShowHelpCommand)
        self.popupmenu.add_cascade(label="Insert script",menu=scriptmenu)
        self.popupmenu.add_command(label="Insert file name...", command=self.InsertFileName)
        self.popupmenu.add_separator()
        self.popupmenu.add_command(label="Run all", command=self.RunAllCommand)
        self.popupmenu.add_command(label="Run current line", command=self.RunLineCommand)
        self.popupmenu.add_command(label="Run selection", command=self.RunSelectionCommand)

        self.output_stream = TkPadOutputStream(self.text_output)
        self.input_stream = TkPadInputStream(self.text_entry,self.output_stream)
Пример #52
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent
        self.initUI()

    def initUI(self):
        self.parent.title("")
        # self.style = Style()
        # self.style.theme_use("clam")
        # self.pack(fill=BOTH, expand = 1)

        self.quitbutton = Button(self, text="Quit", command=lambda: self.quit())

        self.quitbutton.grid(row=3, column=1, pady=4)

        self.labelErrorPointer = Label(self, text="◀")

        self.labellist = []
        self.entrylist = []
        self.verifylist = []
        self.misclist = []

        self.optionCreate = "Create"
        self.optionUpcoming = "Upcoming"
        self.optionPast = "Past"

        self.prevmode = self.optionCreate
        self.curmode = self.optionCreate
        self.optionvar = tkinter.StringVar(self)
        self.optionvar.trace("w", self.permaloop)
        self.optionvar.set(self.optionCreate)
        self.option = OptionMenu(self, self.optionvar, self.optionCreate, self.optionUpcoming, self.optionPast)

        self.optionpostmodevar = tkinter.StringVar(self)
        self.optionpostmodevar.trace("w", self.permaloop)
        self.optionpostmodevar.set("url")
        self.optionpostmode = OptionMenu(self, self.optionpostmodevar, "url", "text")

        self.labelText = Label(self, text="Selftext:")
        self.entryText = Text(self)
        self.labelURL = Label(self, text="URL:")
        self.entryURL = Entry(self)
        self.entryURL.configure(width=60)

        self.sql = sqlite3.connect("sql.db")
        print("Loaded SQL Database")
        self.cur = self.sql.cursor()

        self.cur.execute(
            "CREATE TABLE IF NOT EXISTS upcoming(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT)"
        )
        self.cur.execute(
            "CREATE TABLE IF NOT EXISTS past(ID TEXT, SUBREDDIT TEXT, TIME INT, TITLE TEXT, URL TEXT, BODY TEXT, POSTLINK TEXT)"
        )
        self.cur.execute("CREATE TABLE IF NOT EXISTS internal(NAME TEXT, ID INT)")
        print("Loaded Completed table")
        self.cur.execute("SELECT * FROM internal")
        f = self.cur.fetchone()
        if not f:
            print("Database is new. Adding ID counter")
            self.cur.execute("INSERT INTO internal VALUES(?, ?)", ["counter", 1])
            self.idcounter = 1
        else:
            self.idcounter = f[1]
            print("Current ID counter: " + str(self.idcounter))

        self.sql.commit()

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

        w = 853
        h = 480
        x = (sw - w) / 2
        y = (sh - h) / 2

        self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y - 50))

        self.login()

    def login(self):

        try:
            self.quitbutton.grid_forget()
            self.quitbutton.grid(row=9000, column=0, columnspan=20)

            self.option.grid(row=1, column=0, columnspan=8, pady=8)

            self.updategui(fullclean=True)
        except praw.errors.InvalidUserPass:
            pass
            print("Invalid username or password")
            self.entryPassword.delete(0, 200)
            self.labelErrorPointer.grid(row=1, column=2)

    def permaloop(self, *args):
        self.curmode = self.optionvar.get()
        print("Was: " + self.prevmode + " | Now: " + self.curmode)
        if self.curmode != self.prevmode:
            self.prevmode = self.curmode
            self.updategui(fullclean=True)
        else:
            self.updategui(False)

    def getTime(self, bool):
        timeNow = datetime.datetime.now(datetime.timezone.utc)
        timeUnix = timeNow.timestamp()
        if bool == False:
            return timeNow
        else:
            return timeUnix

    def addentrytobase(self, subreddit, title, url="", body="", mode="", ptime=""):
        curtime = round(self.getTime(True))
        try:
            t = (
                self.entryMo.get()
                + " "
                + self.entryDa.get()
                + " "
                + self.entryYr.get()
                + " "
                + self.entryHH.get()
                + ":"
                + self.entryMM.get()
            )
            plandate = datetime.datetime.strptime(t, "%B %d %Y %H:%M")
            plandate = plandate.timestamp()
        except ValueError:
            print("Invalid Day")
            return False

        if mode == "url":
            url = self.entryURL.get()
            body = ""
            if "http://" not in url and "https://" not in url:
                print("Please enter a proper URL")
                return False
        if mode == "text":
            body = self.entryText.get("1.0", "end")
            url = ""

        if plandate < curtime:
            print("Please enter a time in the future")
            return False

        if not all(char in string.ascii_letters + string.digits + "_-" for char in subreddit):
            print("Subreddit contains invalid characters")
            return False

        if len(subreddit) == 0:
            print("You must enter a subreddit")
            return False

        if len(title) == 0:
            print("You must enter a title")
            return False
        if len(title) > 300:
            print("Title is too long. " + str(len(title)) + "/300 char max")
            return False
        if len(body) > 15000:
            print("Body is too long. " + str(len(body)) + "/15,000 char max")

        print("Timestamp:", plandate)
        self.cur.execute(
            "INSERT INTO upcoming VALUES(?, ?, ?, ?, ?, ?)",
            [self.idcounter, subreddit, int(plandate), title, url, body],
        )
        self.idcounter += 1
        self.cur.execute("UPDATE internal SET ID=? WHERE NAME=?", [self.idcounter, "counter"])
        self.sql.commit()
        print("Post Saved!")
        self.entryText.delete("1.0", "end")
        self.entryURL.delete(0, "end")
        self.entryTitle.delete(0, "end")
        # self.updategui(halfclean=True)

    def dropentryfrombase(self, ID):
        try:
            ID = int(ID)
        except ValueError:
            print("You must enter a number")
            return
        print("Dropping Item " + str(ID) + " from Upcoming")
        self.cur.execute("DELETE FROM upcoming WHERE ID=?", [ID])
        self.sql.commit()
        self.updategui(fullclean=True)

    def printbasetofile(self, db):
        filea = open(db + ".txt", "w")
        if db == "past":
            self.cur.execute("SELECT * FROM past")
        if db == "upcoming":
            self.cur.execute("SELECT * FROM upcoming")
        f = self.cur.fetchall()
        print("Printed " + db + " unimpeded to file")
        for item in f:
            i = list(item)
            d = datetime.datetime.fromtimestamp(i[2])
            i[2] = datetime.datetime.strftime(d, "%b %d %H:%M")
            i.remove("")

            print(str(i)[1:-1], file=filea)
        filea.close()

    def updategui(self, halfclean=False, fullclean=False):

        if self.curmode == self.optionCreate:
            try:
                print(self.optionpostmodevar.get())

                if self.optionpostmodevar.get() == "url":
                    self.entryText.delete("1.0", "end")
                    self.labelText.grid_forget()
                    self.entryText.grid_forget()

                    self.labelURL.grid(row=8, column=0, columnspan=30)
                    self.entryURL.grid(row=9, column=0, columnspan=12, pady=10)

                if self.optionpostmodevar.get() == "text":
                    self.entryURL.delete(0, "end")
                    self.labelURL.grid_forget()
                    self.entryURL.grid_forget()

                    self.labelText.grid(row=8, column=0, columnspan=30)
                    self.entryText.configure(width=40, height=8)
                    self.entryText.grid(row=9, column=0, columnspan=12)
            except AttributeError:
                pass

        if fullclean == True:
            print("Cleaning GUI")
            for item in self.labellist:
                item.grid_forget()
            for item in self.entrylist:
                item.grid_forget()
            for item in self.verifylist:
                item.grid_forget()
            for item in self.misclist:
                item.grid_forget()
            self.labellist = []
            self.entrylist = []
            self.verifylist = []
            self.misclist = []

            if self.curmode == self.optionCreate:
                self.newrowindex = 6
                self.labelSubreddit = Label(self, text="Subreddit:    /r/")
                self.labelTitle = Label(self, text="Post title:  ")
                self.entrySubreddit = Entry(self)
                self.entryTitle = Entry(self)

                self.labelHH = Label(self, text="Schedule time (Local timezone):")
                nowlist = datetime.datetime.strftime(datetime.datetime.now(), "%B %d %Y %H %M").split()

                self.entryMo = Spinbox(
                    self,
                    width=9,
                    values=(
                        "January",
                        "February",
                        "March",
                        "April",
                        "May",
                        "June",
                        "July",
                        "August",
                        "September",
                        "October",
                        "November",
                        "December",
                    ),
                )
                self.entryMo.delete(0, "end")
                self.entryMo.insert(0, nowlist[0])

                self.entryDa = Spinbox(self, width=2, from_=1, to=31)
                self.entryDa.delete(0, "end")
                self.entryDa.insert(0, nowlist[1])

                self.entryYr = Spinbox(self, width=4, from_=2014, to=2500)
                self.entryYr.delete(0, "end")
                self.entryYr.insert(0, nowlist[2])

                self.entryHH = Spinbox(self, from_=0, to=23, width=2)
                self.entryHH.delete(0, "end")
                self.entryHH.insert(0, nowlist[3])

                self.entryMM = Spinbox(self, from_=0, to=59, width=2)
                self.entryMM.delete(0, "end")
                self.entryMM.insert(0, nowlist[4])

                self.buttonAddentry = Button(
                    self,
                    text="Save",
                    command=lambda: self.addentrytobase(
                        self.entrySubreddit.get(), self.entryTitle.get(), mode=self.optionpostmodevar.get()
                    ),
                )

                self.misclist.append(self.labelSubreddit)
                self.misclist.append(self.entrySubreddit)
                self.misclist.append(self.labelHH)
                self.misclist.append(self.entryHH)
                self.misclist.append(self.entryMM)
                self.misclist.append(self.entryMo)
                self.misclist.append(self.entryDa)
                self.misclist.append(self.entryYr)
                self.misclist.append(self.labelTitle)
                self.misclist.append(self.entryTitle)
                self.misclist.append(self.buttonAddentry)
                self.misclist.append(self.optionpostmode)
                self.misclist.append(self.labelText)
                self.misclist.append(self.entryText)
                self.misclist.append(self.labelURL)
                self.misclist.append(self.entryURL)

                self.labelSubreddit.grid(row=2, column=0, sticky="e")
                self.labelTitle.grid(row=3, column=0, sticky="e")
                self.entrySubreddit.grid(row=2, column=1, columnspan=3, sticky="w")
                self.entryTitle.grid(row=3, column=1, columnspan=3, sticky="w")
                self.entryMo.grid(row=4, column=1, sticky="e")
                self.entryDa.grid(row=4, column=2)
                self.entryYr.grid(row=4, column=3)
                self.labelHH.grid(row=4, column=0, sticky="se", pady=5)
                self.entryHH.grid(row=5, column=1, sticky="e")
                self.entryMM.grid(row=5, column=2, sticky="w")
                self.optionpostmode.grid(row=6, column=0, columnspan=20, pady=10)
                self.buttonAddentry.grid(row=200, column=0, columnspan=20)

            if self.curmode == self.optionUpcoming:
                self.cur.execute("SELECT * FROM upcoming")
                dobutton = True

            if self.curmode == self.optionPast:
                self.cur.execute("SELECT * FROM past")
                dobutton = False

            if self.curmode == self.optionPast or self.curmode == self.optionUpcoming:

                self.listboxId = Listbox(self)
                self.listboxId.configure(width=118, height=20, font=("Courier 8"))
                self.misclist.append(self.listboxId)

                self.listboxScroller = Scrollbar(self, orient="horizontal", command=self.listboxId.xview)
                self.listboxScroller.grid(row=4, column=0, columnspan=900)
                self.listboxId.grid(row=3, column=0, columnspan=10)

                self.listboxId.configure(xscrollcommand=self.listboxScroller.set)
                self.misclist.append(self.listboxScroller)

                self.buttonPrinter = Button(self, text="Print to .txt file")
                if self.curmode == self.optionPast:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile("past"))
                if self.curmode == self.optionUpcoming:
                    self.buttonPrinter.configure(command=lambda: self.printbasetofile("upcoming"))

                self.buttonPrinter.grid(row=6, column=0, columnspan=90)
                self.misclist.append(self.buttonPrinter)

                if dobutton == True:
                    self.entryDelete = Entry(self)
                    self.buttonDelete = Button(
                        self, text="Delete Item: ", command=lambda: self.dropentryfrombase(self.entryDelete.get())
                    )
                    self.buttonDelete.grid(row=5, column=0, sticky="e")
                    self.entryDelete.grid(row=5, column=1, sticky="w")
                    self.misclist.append(self.entryDelete)
                    self.misclist.append(self.buttonDelete)

                fetched = self.cur.fetchall()
                for item in fetched:
                    d = datetime.datetime.fromtimestamp(item[2])
                    info = datetime.datetime.strftime(d, "%b %d %H:%M")

                    if item[4] == "":
                        infx = item[5]
                    if item[5] == "":
                        infx = item[4]
                    if self.curmode == self.optionPast:
                        infy = "." + item[6]
                    else:
                        infy = ""

                    self.listboxId.insert(
                        "end",
                        item[0]
                        + "." * (6 - len(item[0]))
                        + item[1][:10]
                        + "." * (12 - len(item[1][:10]))
                        + info
                        + "." * (15 - len(info[:14]))
                        + item[3][:18]
                        + "." * (20 - len(item[3][:14]))
                        + infx[:45]
                        + "." * (47 - len(infx[:45]))
                        + infy,
                    )

    def morerows(self, label, columnm, columnn, limit, *args):
        self.redditlabel = Label(self, text=label)
        self.redditlabel.grid(row=self.newrowindex, column=columnm, sticky="e")
        self.labellist.append(self.redditlabel)

        self.redditentry = Entry(self)
        self.redditentry.grid(row=self.newrowindex, column=columnn, columnspan=9)
        self.entrylist.append(self.redditentry)

        self.newrowindex += 1
        if self.newrowindex >= limit:
            self.morerowbutton.grid_forget()
        print(self.newrowindex)
Пример #53
0
class MiniSedGUI(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)

        self.cfg = MiniSedConfig()

        self.source_directory = None
        self.target_directory = None

        self.create_widgets()
        self.pack(anchor=CENTER, fill=BOTH, expand=1)

        self.files_with_content = []

        self.cfg.directory.trace('w', self.disable_apply)
        self.cfg.glob.trace('w', self.disable_apply)
        self.cfg.search.trace('w', self.disable_apply)
        self.cfg.replace.trace('w', self.disable_apply)
        self.cfg.ignore_case.trace('w', self.disable_apply)

    def disable_apply(self, *args):
        self.run_btn["state"] = 'disabled'

    def create_widgets(self):

        self.directory_frame = Frame(self)
        self.directory_frame.pack(side=TOP, fill=X, expand=0, padx=4, pady=4)
        self.directory_frame.grid_columnconfigure(1, weight=1)

        self.directory_label = Label(self.directory_frame, text="Directory:")
        self.directory_label.grid(column=0, row=0)

        self.directory_entry = Entry(self.directory_frame, textvariable=self.cfg.directory)
        self.directory_entry.grid(column=1, row=0, sticky=W + E)
        self.directory_entry.bind('<Return>', lambda arg: self.do_preview())

        self.directory_button = Button(self.directory_frame, text="Browse")
        self.directory_button["command"] = lambda: do_ask_directory(self.cfg.directory)
        self.directory_button.grid(column=2, row=0)

        self.glob_label = Label(self.directory_frame, text="Glob:")
        self.glob_label.grid(column=0, row=1, stick=E)

        self.glob_entry = Entry(self.directory_frame, textvariable=self.cfg.glob)
        self.glob_entry.bind('<Return>', lambda arg: self.do_preview())
        self.glob_entry.grid(column=1, row=1, sticky=N + S + W)

        self.search_replace_frame = Frame(self)
        self.search_replace_frame.grid_columnconfigure(1, weight=1)
        self.search_replace_frame.pack(anchor=N, side=TOP, fill=X, expand=0, padx=4, pady=4)

        self.search_label = Label(self.search_replace_frame, text="Search:")
        self.search_label.grid(column=0, row=0, sticky=E)
        self.search_entry = Entry(self.search_replace_frame, textvariable=self.cfg.search)
        self.search_entry.grid(column=1, row=0, sticky=N + S + W + E)
        self.search_entry.bind('<Return>', lambda arg: self.do_preview())

        self.replace_label = Label(self.search_replace_frame, text="Replace:")
        self.replace_label.grid(column=0, row=1, sticky=E)
        self.replace_entry = Entry(self.search_replace_frame, textvariable=self.cfg.replace)
        self.replace_entry.grid(column=1, row=1, sticky=N + S + W + E)
        self.replace_entry.bind('<Return>', lambda arg: self.do_preview())

        self.option_frame = Frame(self)
        self.option_frame.pack(side=TOP, fill=X, expand=0, pady=4)

        self.work_frame = LabelFrame(self.option_frame, text="Options")
        self.work_frame.pack(side=LEFT, padx=4, pady=4)

        self.ignore_case_checkbutton = Checkbutton(
            self.work_frame, text="ignore case", variable=self.cfg.ignore_case)
        self.ignore_case_checkbutton.pack(side=TOP, anchor=W, expand=0)

        self.create_backups_checkbutton = Checkbutton(
            self.work_frame, text="create backups", variable=self.cfg.create_backups)
        self.create_backups_checkbutton.pack(side=TOP, anchor=W, expand=0)

        self.preview_frame = LabelFrame(self.option_frame, text="Preview")
        self.preview_frame.pack(side=LEFT, padx=4, pady=4)
        self.show_full_content_checkbutton = Checkbutton(
            self.preview_frame, text="show full content", variable=self.cfg.show_full_content)
        self.show_full_content_checkbutton.pack(side=TOP, anchor=W, expand=0)

        self.show_original_checkbutton = Checkbutton(
            self.preview_frame, text="show original", variable=self.cfg.show_original)
        self.show_original_checkbutton.pack(side=TOP, anchor=W, expand=0)

        self.text_frame = Frame(self)
        self.text_frame.pack(side=TOP, fill=BOTH, expand=1, pady=4)

        self.text_frame.grid_columnconfigure(0, weight=1)
        self.text_frame.grid_rowconfigure(0, weight=1)

        self.scrollbar = Scrollbar(self.text_frame)
        self.scrollbar.grid(column=1, row=0, sticky=N + S)

        self.text = Text(self.text_frame, yscrollcommand=self.scrollbar.set, width=120, height=20)

        self.text.tag_config("file", background="lightgray", foreground="black")
        self.text.tag_config("search", background="lightblue", foreground="black")
        self.text.tag_config("replace", background="orange", foreground="black")
        self.text.tag_config("hollow", foreground="gray")
        self.text.tag_config("highlight", background="lightyellow")

        self.text.config(state=DISABLED)
        self.text.grid(column=0, row=0, sticky=N + S + W + E)
        self.scrollbar.config(command=self.text.yview)

        self.confirm_button_frame = Frame(self)
        self.confirm_button_frame.pack(side=BOTTOM, anchor=E)

        self.cancel_btn = Button(self.confirm_button_frame)
        self.cancel_btn["text"] = "Quit"
        self.cancel_btn["command"] = self.quit
        self.cancel_btn.grid(column=1, row=0, sticky=S, pady=8, padx=8)

        self.preview_btn = Button(self.confirm_button_frame)
        self.preview_btn["text"] = "Preview"
        self.preview_btn["command"] = self.do_preview
        self.preview_btn.grid(column=2, row=0, sticky=S, pady=8, padx=8)

        self.run_btn = Button(self.confirm_button_frame)
        self.run_btn["text"] = "Apply"
        self.run_btn["command"] = self.do_execute
        self.run_btn.grid(column=3, row=0, sticky=S, pady=8, padx=8)
        self.run_btn["state"] = 'disabled'

    def do_preview(self):
        directory = self.cfg.directory.get()

        self.text.config(state=NORMAL)
        self.text.delete("1.0", END)
        self.text.config(state=DISABLED)

        self.files_with_content = []
        for path, dirs, files in os.walk(directory):
            for fname in files:
                filename = os.path.join(path, fname)

                if not self.cfg.glob.get() or fnmatch.fnmatch(fname.lower(), self.cfg.glob.get().lower()):
                    with open(filename, 'rt', encoding='latin-1') as fin:
                        lines = fin.read().splitlines()
                    lines = minised_on_lines(lines, self.cfg.search.get(), self.cfg.replace.get(),
                                             self.cfg.ignore_case.get())
                    self.files_with_content.append((filename, lines))

                    self.text.config(state=NORMAL)
                    self.text.insert(END, "%s:\n" % filename, "file")
                    for line in lines:
                        if isinstance(line, tuple):
                            if self.cfg.show_original.get():
                                self.text.insert(END, "%s" % line[0], "hollow")
                                self.text.insert(END, "%s" % line[1], "search")
                                self.text.insert(END, "%s\n" % line[3], "hollow")

                            self.text.insert(END, "%s" % line[0], "highlight")
                            self.text.insert(END, "%s" % line[2], "replace")
                            self.text.insert(END, "%s" % line[3], "highlight")
                            self.text.insert(END, "\n")
                        elif self.cfg.show_full_content.get():
                            self.text.insert(END, "%s\n" % line)
                    self.text.insert(END, "\n")
                    self.text.config(state=DISABLED)

                    self.master.update()
        self.run_btn["state"] = 'normal'

    def do_execute(self):
        for filename, lines in self.files_with_content:
            if self.cfg.create_backups.get():
                os.rename(filename, filename + "~")

            with open(filename, 'wt', encoding='latin-1', newline='\r\n') as fout:
                for line in lines:
                    if isinstance(line, tuple):
                        fout.write(line[0])
                        fout.write(line[2])
                        fout.write(line[3])
                    else:
                        fout.write(line)
                    fout.write("\n")

        self.run_btn["state"] = 'disabled'
        tkinter.messagebox.showinfo("Replacement successful",
                                    "Replacements have been performed successfully on the files")
Пример #54
0
class GuiPart:  
    
    def __init__(self, win, line, board, solutions):
        self.master = win
        self.line = line
        self.solutions = solutions
        self.user_points = 0
        self.board = board
        self.cpu_points = 0
        #self.lock = threading.Lock()
        self.customFont = tkinter.font.Font(family ="Helvetica", size = 12)
        self.frame1 = Frame(win)
        #frame1.pack()
        self.make_buttons()
        self.make_timer()
        self.make_input()
        self.frame3 = Frame(win)
        #frame3.pack()
        self.make_ai()
        self.frame5 = Frame(win)
        #frame5.pack()
        self.make_user()
        self.frame1.grid(row = 1, column = 1)
        self.frame3.grid(row = 1, column = 2)
        self.frame5.grid(row = 1, column = 0)
        
        
        
    def make_user(self):
        self.userWords = Listbox(self.frame5, height= 18)
        self.user_score = Label(self.frame5, text= self.user_points)
        self.scroll2 = Scrollbar(self.frame5, orient= VERTICAL)
        self.userWords.config(yscrollcommand=self.scroll2.set)
        self.scroll2.config(command= self.userWords.yview)
        self.scroll2.grid(column= 2, sticky= N+S)  
        self.userWords.grid(row= 0)
        self.user_score.grid(row= 1)
    
    def make_ai(self):
        self.select = Listbox(self.frame3, height= 18)
        self.scroll = Scrollbar(self.frame3, orient=VERTICAL)
        self.select.config(yscrollcommand=self.scroll.set)
        self.scroll.config(command=self.select.yview)
        self.scroll.grid(column= 2, sticky= N+S) 
        self.cpu_score = Label(self.frame3, text= self.cpu_points)
        self.select.grid(row = 0)
        self.cpu_score.grid(row = 1)   
        
        
    def make_input(self):
        v = StringVar()
        self.e = Entry(self.frame1, textvariable =v)
        
        self.e.bind('<Return>', self.func)
        self.e.grid(row= 5, columnspan= 4)
        self.e.focus_set()        
    
    
    def make_timer(self):
        self.timeLeft = 180
        self.clock = Label(self.frame1, text= self.timeLeft)
        self.clock.grid(row= 0, columnspan= 4)
            
    def make_buttons(self):
        self.buttons = []
        for letter in self.board:
            value = ''
            if letter.lower() == 'q':
                value = 'Qu' 
            elif letter == ' ':
                continue
            else:
                value = letter.upper()
                
            but = Button(self.frame1, text = value, height= 3, width = 3, font = self.customFont)
            self.buttons.append(but)
            y = 1
            x = 0
            for button in self.buttons:
                button.grid(row = y, column = x)
                x += 1
                if x == 4:
                    x = 0
                    y += 1
    
    def func(self, event):
        if self.timeLeft:
            #with self.lock:
            value = self.e.get()
            value = value.lower()
            try:
                if value in self.solutions:
                    self.userWords.insert(END, value)
                    self.user_points += game.score_word(self.solutions, value)
                    self.solutions.remove(value)
                    self.user_score.config(text= self.user_points)
            except ValueError:
                # all words have been found
                pass
            self.e.delete(0, 'end')
            
                
    def processUpdate(self):
        #with self.lock:
        while self.line.qsize():
            try:
                msg = self.line.get(0)
                self.select.insert(END, *msg)
                result = game.score_word(self.solutions, *msg)
                self.cpu_points += result
                self.cpu_score.config(text= self.cpu_points)
                self.solutions.remove(*msg)
            except queue.Empty:
                pass

    def countDown(self):
        self.clock.configure(text= self.timeLeft)
        self.timeLeft -= 1
        if self.timeLeft < 0:
            self.e.configure(state = 'disabled')
            return False
        else:
            return True
            #self.master.after(1000, self.countDown())
    
    def reset(self, board, solutions):
        self.timeLeft = 180
        self.board = board
        self.solutions = solutions
        self.make_buttons()
        self.user_points = 0
        self.cpu_points = 0
        self.cpu_score.config(text= self.cpu_points)
        self.user_score.config(text= self.user_points)
        self.e.configure(state = 'normal')
        self.select.delete(0,END)
        self.userWords.delete(0,END)
Пример #55
0
class simpleGui(tkinter.Tk):
    
    def __init__(self, parent):
        tkinter.Tk.__init__(self, parent)
        self.parent = parent
        self.initialize()
        
    def initialize(self):
        self.grid()
        self.config(bg="white")
        self.geometry("600x500")
        
        self.algo = ACAlgo()
        self.wordFrames=[]
        
        self.path=""
        self.lastCanvasIndex=0
        
        rowLine=0
        
        
        self.entryPath = tkinter.Entry(self, width=75)
        self.entryPath.grid(column=0, row=rowLine,columnspan=3, sticky='NEW')
        self.entryPath.bind("<Return>", self.setPath)
        
        buttonSetPath = tkinter.Button(self, text="Set path", width=21, height=1, command=self.setPath)
        buttonSetPath.grid(column=3, row=rowLine, sticky='EWN')
                
                
                
        rowLine=rowLine+1
        
        self.entry = tkinter.Entry(self, width=75)
        self.entry.grid(column=0, row=rowLine,columnspan=2, sticky='NEWS')
        self.entry.bind("<Return>", self.addWords)

        buttonAddWords = tkinter.Button(self, text="Add words", width=21,height=1, command=self.addWords)
        buttonAddWords.grid(column=3, row=rowLine, sticky='EWNS')
        
        
        
        rowLine=rowLine+1
        self.grid_rowconfigure(rowLine, weight=1)
        self.textBox = tkst.ScrolledText(self, width=20, height=10)
        self.textBox.grid(column=0, row=rowLine, columnspan=3, sticky='NWES')
        
        self.textBox.config(state=DISABLED)
        
       
        self.canvas= Canvas(master=self,width=150)
        self.vscroll = Scrollbar(self)
        
        self.vscroll.config(command=self.canvas.yview)
        self.canvas.config(yscrollcommand=self.vscroll.set) 

        self.canvas.grid( row=rowLine, column=3,  sticky='NES')
        self.vscroll.grid(padx=1,  pady=1, row=rowLine, column=4, sticky='NEWS')
        
        
        
        rowLine=rowLine+1
                
        buttonClearHighlight = tkinter.Button(self, text="Clear highlight", width=20, command=self.removeHighlightsBtn)
        buttonClearHighlight.grid(column=0, row=rowLine, sticky="WS")


        buttonDeleteWords = tkinter.Button(self, text="Delete words", width=20, command=self.resetAll)
        buttonDeleteWords.grid(column=3, row=rowLine, sticky="ES")
        
        self.grid_columnconfigure(0, weight=1)
        self.grid_columnconfigure(1, weight=1)

    def setPath(self):
        try:
            open(self.entryPath.get())
        except:
            return
        self.path=self.entryPath.get()
        self.textBox.config(state=NORMAL)
        self.textBox.insert(tkinter.INSERT, open(self.path).read())
        self.textBox.config(state=DISABLED)
        
    def removeHighlights(self):
        for wordFrame in self.wordFrames:
            wordFrame.removeHighLight()

    def removeHighlightsBtn(self, entry=""):
        for wordFrame in self.wordFrames:
            wordFrame.removeHighLight()
        
        self.update_idletasks()
            
    def resetAll(self, entry=""):
        self.removeHighlights()
        self.algo.resetTree()
        self.lastCanvasIndex=0;
        self.wordFrames=[]
        self.canvas.delete("all")
        self.update_idletasks()
        
    def addWords(self, event=""):
        if(self.path==""):
            return
        if(self.entry.get().strip()==""):
            self.entry.delete(0,len(self.entry.get()))
            return
        self.resetAll()
        for word in self.entry.get().split(" "):
            if word.lower() not in self.algo.foundWords.keys() and word != "" and word!=None:
                
                self.algo.addWord(word)
                self.addToCanvas(word)
                
                
        self.entry.delete(0,len(self.entry.get()))
        
        self.algo.addFails()
        
        self.algo.readFile(self.path)
        self.updateCanvasPositions();

    def updateCanvasPositions(self):
        
        for word in self.wordFrames:
            self.wordFrames[self.wordFrames.index(word)].updatePositions(self.algo.foundWords[word.getWord().lower()])
            self.wordFrames[self.wordFrames.index(word)].addTags()
            
    def addToCanvas(self, word):
             
        frame=wordFrame(self.canvas, self, word, self.algo.foundWords[word.lower()])
        self.wordFrames.append(frame)
        self.canvas.create_window(0, 50+self.lastCanvasIndex*50,anchor="w", window=frame, height=50)
            
                
        self.canvas.config(scrollregion=(0,0,70+self.lastCanvasIndex*50,70+self.lastCanvasIndex*50))
        self.canvas.update_idletasks()
        self.update_idletasks()
        
        self.lastCanvasIndex=self.lastCanvasIndex+1;
Пример #56
0
class Application(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def generate(self):
        n = int(self.menu_gen.get())
        seed = self.inp_seed.get()
        self.output = Generator.convert(seed, n)
        if len(self.output) > 0:
            self.generated = True
            self.butt_draw.config(    state= 'normal')
            self.chek_fullscrn.config(state= 'normal')
            self.clearOutput(self.output)

    def draw(self, n, step=False):
        p1, p2 = Draw.move(n)
        self.curr_canvas.create_line(p1[0], p1[1], p2[0], p2[1], fill= self.color, width= self.thick)
        if step:
            self.curr_canvas.update_idletasks()

    def do(self, action, step, rainbow):
        if len(action) > 1:
            p = action[1]
        else:
            p = 1.0

        self.timebuff += step
        cmd = action[0].lower()
        if cmd == "draw":
            if rainbow:
                self.incColor()
                if self.incThickYN:
                    self.incThick(self.reverseThick, False)
            elif self.incThickYN:
                self.incThick(self.reverseThick, True)
            if self.timebuff > 1.0:
                truncate = int(self.timebuff)
                self.after(truncate, self.draw(float(p), True))
                self.timebuff -= truncate
            else:
                self.draw(float(p))
        elif cmd == "turn":
            Draw.turn(float(p))
        elif cmd == "skip":
            Draw.skip(float(p))
        elif cmd == "back":
            Draw.back(float(p))
        elif cmd == "color":
            if not rainbow:
                self.color = Color.getHexString(p)
        elif cmd == "thick":
            self.thick = int(p)
        else:
            print("Unknown command " + cmd)

    def drawAll(self, newWindow= True):
        if self.generated == True:
            self.butt_print.config(state= 'disabled')
            self.timebuff = 0.0
            self.color = Color.white()
            self.thick = 2
            l = float(self.slid_linesize.get())
            a = float(self.slid_angle.get())
            Draw.init(self.startingPoint, l, a)
            if self.fullScreen.get() == 1:
                if newWindow:
                    self.curr_canvas = dc.BigCanvas(self).canvas
                self.canvas.delete("all")
            else:
                self.curr_canvas = self.canvas
            self.curr_canvas.delete("all")
            self.curr_canvas.config(bg= Color.getHexString(self.bgColor.get()))
            rainbow = self.rainbowCheck.get() == 1
            if rainbow or self.incThickYN:
                self.incStep = 1.0/float(self.getDrawCount(self.output))
                self.percent = 0.0
            for c in self.output:
                if c == '[':
                    Draw.push()
                elif c == ']':
                    Draw.pop()
                else:
                    for r in Rule.getDrawings():
                        if c == r[0]:
                            if len(r) > 2:
                                params = (r[1], r[2])
                            else:
                                params = (r[1],)
                            s = float(self.slid_timer.get())
                            self.do(params, s, rainbow)
                            break
            self.butt_print.config(state= 'normal')

    def incColor(self):
        self.color    = Color.getValueByPercent(self.percent)
        self.percent += self.incStep

    def incThick(self, reverse, incYN):
        maxthick = 5
        minthick = 1
        diff = maxthick - minthick
        if reverse:
            result = maxthick - int(diff * self.percent)
        else:
            result = minthick + int(diff * self.percent)
        self.thick = result
        if incYN:
            self.percent += self.incStep

    def getDrawCount(self, s):
        draw_commands = []
        for r in Rule.getDrawings():
            if r[1].lower() == "draw":
                draw_commands.append(r[0])
        draw_count = 0;
        for c in s:
            for d in draw_commands:
                if c == d:
                    draw_count += 1
                    break
        return draw_count

    def clearOutput(self, replacement=None):
        self.text_output.config(state= 'normal')
        self.text_output.delete(1.0, END)
        if replacement:
            self.text_output.insert(END, replacement)
        self.text_output.config(state= 'disabled')

    def formatRules(self, rules):
        ret = []
        for r in rules:
            entry = r[0] + " | " + r[1]
            if len(r) > 2:
                entry += " " + r[2]
            ret.append(entry)
        return ret

    def getRuleFromFormatted(self, s):
        if s:
            rule = s.split('|')
            rule[0] = rule[0].strip()
            rule[1] = rule[1].strip()
            prod = rule[1].split(" ")
            if len(prod) == 1:
                return (rule[0], prod[0])
            else:
                return (rule[0], prod[0], prod[1])

    def RefreshLists(self):
        self.list_prod.delete(0, END)
        self.list_draw.delete(0, END)

        l = self.formatRules(Rule.getProductions())
        for p in l:
            self.list_prod.insert(END, p)

        l = self.formatRules(Rule.getDrawings())
        for d in l:
            self.list_draw.insert(END, d)




    def AddProductionRule(self, edit=None):
        rule = dp.AddProductionRuleDialog(self, edit).result
        if rule:
            if edit:
                Rule.removeProd(edit[0])
            Rule.AddProduction(rule)
            self.RefreshLists()

    def AddDrawingRule(self, edit=None):
        rule = dd.AddDrawingRuleDialog(self, edit).result
        if rule:
            if edit:
                Rule.removeDraw(edit[0])
            Rule.AddDrawing(rule)
            self.RefreshLists()

    def EditProductionRule(self):
        s = self.list_prod.curselection()
        if s:
            idx = s[0]
            rule = (idx,) + self.getRuleFromFormatted(self.list_prod.get(idx))
            if rule:
                self.AddProductionRule(rule)

    def EditDrawingRule(self):
        s = self.list_draw.curselection()
        if s:
            idx = s[0]
            rule = (idx,) + self.getRuleFromFormatted(self.list_draw.get(idx))
            if rule:
                self.AddDrawingRule(rule)

    def DeleteProductionRule(self):
        s = self.list_prod.curselection()
        if s:
            Rule.removeProd(s[0])
            self.RefreshLists()

    def DeleteDrawingRule(self):
        s = self.list_draw.curselection()
        if s:
            Rule.removeDraw(s[0])
            self.RefreshLists()


    def packOutput(self):
        ret = ""
        ret += self.packAxiom()
        ret += self.packProdRules()
        ret += self.packDrawRules()
        return ret

    def packAxiom(self):
        return "@" + str(self.inp_seed.get()).strip()

    def packRules(self, rules):
        ret = "@"
        for r in rules:
            ret += "$" + str(r[0]) + "|" + str(r[1])
            if len(r) > 2:
                ret += ":" + str(r[2])
        return ret

    def packProdRules(self):
        return self.packRules(Rule.getProductions())

    def packDrawRules(self):
        return self.packRules(Rule.getDrawings())


    def parseProdRules(self, raw):
        rules = raw.split('$')
        for rule in rules:
            if rule is not "":
                r = rule.split('|')
                Rule.AddProduction((r[0], r[1]))

    def parseDrawRules(self, raw):
        rules = raw.split('$')
        for rule in rules:
            if rule is not "":
                r = rule.split('|')
                p = r[1].split(':')
                if len(p) == 1:
                    tup = (r[0], p[0])
                else:
                    tup = (r[0], p[0], p[1])
                Rule.AddDrawing(tup)


    def parseSaveFile(self, s):
        Rule.wipe()
        settings = s.split('@')
        self.inp_seed.set(str(settings[1]))
        self.parseProdRules(settings[2])
        self.parseDrawRules(settings[3])
        self.RefreshLists()


    def save(self):
        try:
            filename = filedialog.asksaveasfilename(**self.file_options['txt'])
            if filename:
                f = open(filename, 'w')
                f.write(self.packOutput())
                f.close()
        except Exception as e:
            print("File IO error in save\n", e)

    def load(self):
        try:
            filename = filedialog.askopenfilename(**self.file_options['txt'])
            if filename:
                f = open(filename, 'r')
                self.parseSaveFile(f.read())
                f.close()
                self.slid_linesize.set(1.0)
                self.slid_timer.set(0.0)
                self.menu_gen.set(1)
                self.clearOutput()

        except Exception as e:
            print("File IO error in load\n" + e)

    def help(self):
        help.HelpDialog(self)


    def saveImage(self):
        filename = filedialog.asksaveasfilename(**self.file_options['ps'])
        self.curr_canvas.postscript(file=filename, colormode='color')

    def click(self, event):
        self.startingPoint = (event.x, event.y)

    def clickAndRedraw(self, event):
        self.click(event)
        self.drawAll(False)

    def fileOptions(self):
        self.file_options = {}
        txt_options  = {}
        ps_options  = {}
        txt_options['defaultextension'] = '.txt'
        txt_options['filetypes'] = [('Plaintext', '.txt')]
        txt_options['initialdir'] = 'Patterns'
        ps_options['defaultextension'] = '.ps'
        ps_options['filetypes'] = [('Postscript Image', '.ps')]
        ps_options['initialdir'] = 'Images'
        self.file_options['txt'] = txt_options
        self.file_options['ps'] = ps_options

    def makeMenuBar(self):
        self.menubar = Menu(self);
        self.menubar.add_command(label="Save", command= self.save)
        self.menubar.add_command(label="Load", command= self.load)
        self.menubar.add_command(label="Help", command= self.help)
        root.config(menu= self.menubar)

    def makeInputFrame(self):
        self.inp_seed         = String()
        self.bgColor          = String()
        self.gen_value        = Int()
        self.rainbowCheck     = Int()
        self.fram_input       = Frame(self,              bd= 2, relief= self.style, width= input_frame_width, height= input_frame_height)
        self.fram_seed        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_prod        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_draw        = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_drawParams  = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_gen         = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.fram_output      = Frame(self.fram_input,   bd= 1, relief= self.style)
        self.menu_gen         = DropDown(self.fram_gen,  textvariable= self.gen_value, state= 'readonly')
        self.entr_seed        = Input(self.fram_seed,    textvariable= self.inp_seed)
        self.text_output      = Output(self.fram_output, width= 35, height= 10)
        self.scrl_output      = Scrollbar(self.fram_output)
        self.list_prod        = List(self.fram_prod,     selectmode= BROWSE, font= "Courier 8", height= 5)
        self.list_draw        = List(self.fram_draw,     selectmode= BROWSE, font= "Courier 8", height= 5)
        self.slid_linesize    = Slider(self.fram_drawParams,  from_= 0.1, to= 10.0,     orient= HORIZONTAL, resolution= 0.1, length= 180)
        self.slid_timer       = Slider(self.fram_drawParams,  from_= 0, to= 2,          orient= HORIZONTAL, resolution= 0.02, length= 180)
        self.slid_angle       = Slider(self.fram_drawParams,  from_= 0, to= 359,        orient= HORIZONTAL, length= 180)
        self.entr_bgcolor     = Input (self.fram_drawParams, textvariable= self.bgColor)
        self.butt_prodAdd     = Button(self.fram_prod,   text= "Add",    width=8, command= self.AddProductionRule)
        self.butt_prodEdit    = Button(self.fram_prod,   text= "Edit",   width=8, command= self.EditProductionRule)
        self.butt_prodDelete  = Button(self.fram_prod,   text= "Delete", width=8, command= self.DeleteProductionRule)
        self.butt_drawAdd     = Button(self.fram_draw,   text= "Add",    width=8, command= self.AddDrawingRule)
        self.butt_drawEdit    = Button(self.fram_draw,   text= "Edit",   width=8, command= self.EditDrawingRule)
        self.butt_drawDelete  = Button(self.fram_draw,   text= "Delete", width=8, command= self.DeleteDrawingRule)
        self.chek_incColor    = CheckBox(self.fram_draw, text= "Rainbow", variable= self.rainbowCheck)
        Label(self.fram_seed,       text= "Axiom:", width=8).grid             (row=0, column=0)
        Label(self.fram_prod,       text= "Production\nRules:", width=8).grid (row=0, column=0)
        Label(self.fram_draw,       text= "Drawing\nRules:", width=8).grid    (row=0, column=0)
        Label(self.fram_drawParams, text= "Line Size:").grid                  (row=0, column=0)
        Label(self.fram_drawParams, text= "Delay (ms):").grid                 (row=1, column=0)
        Label(self.fram_drawParams, text= "Starting Angle:").grid             (row=2, column=0)
        Label(self.fram_drawParams, text= "Background Color:").grid           (row=3, column=0)
        Label(self.fram_output,     text= "Output:").grid                     (row=0, column=0)
        Label(self.fram_gen,        text= "Generations:").grid                (row=0, column=0)

        self.gen_value.set(1)
        self.menu_gen['values'] = tuple(range(1, 13))
        self.slid_linesize.set(1.0)
        self.bgColor.set( Color.default() )
        self.text_output.config(state='disabled', yscrollcommand= self.scrl_output.set)
        self.scrl_output.config(command=self.text_output.yview)

        self.fram_input.grid      (row=0, column=0)
        self.fram_seed.grid       (row=1, column=0, sticky= 'ew')
        self.fram_prod.grid       (row=2, column=0, sticky= 'ew')
        self.fram_draw.grid       (row=3, column=0, sticky= 'ew')
        self.fram_drawParams.grid (row=4, column=0, sticky= 'ew')
        self.fram_gen.grid        (row=5, column=0, sticky= 'ew')
        self.fram_output.grid     (row=6, column=0, sticky= 'ew')
        self.entr_seed.grid       (row=0, column=1, sticky= 'ew')
        self.list_prod.grid       (row=0, column=1, sticky= 'ew')
        self.butt_prodAdd.grid    (row=1, column=0, sticky= 'ew')
        self.butt_prodEdit.grid   (row=1, column=1, sticky= 'ew')
        self.butt_prodDelete.grid (row=1, column=2, sticky= 'ew')
        self.list_draw.grid       (row=0, column=1)
        self.butt_drawAdd.grid    (row=1, column=0, sticky= 'ew')
        self.butt_drawEdit.grid   (row=1, column=1, sticky= 'ew')
        self.butt_drawDelete.grid (row=1, column=2, sticky= 'ew')
        self.chek_incColor.grid   (row=0, column=2)
        self.slid_linesize.grid   (row=0, column=1, sticky= 'ew')
        self.slid_timer.grid      (row=1, column=1, sticky= 'ew')
        self.slid_angle.grid      (row=2, column=1, sticky= 'ew')
        self.entr_bgcolor.grid    (row=3, column=1, sticky= 'ew')
        self.menu_gen.grid        (row=0, column=1, sticky= 'ew')
        self.text_output.grid     (row=1, column=0)
        self.scrl_output.grid     (row=1, column=1, sticky= 'ns')

    def makeCanvasFrame(self):
        self.fram_canvas = Frame(self, bd=10, relief=self.style)
        self.canvas      = Canvas(self.fram_canvas, width= canvas_width, height= canvas_height)
        self.fram_canvas.grid(row=0, column=1, sticky='nesw')
        self.canvas.grid(sticky='nesw')
        self.canvas.bind("<Button-1>", self.click)
        self.curr_canvas = self.canvas

    def makeIgnitionFrame(self):
        self.fullScreen    = Int()
        self.fram_ignition = Frame(self, bd=4, relief=self.style, width= ignition_frame_width, height= ignition_frame_height)
        self.butt_generate = Button(self.fram_ignition,   text= " -- GENERATE -- ", width=111, command= self.generate)
        self.butt_draw     = Button(self.fram_ignition,   text= " -- DRAW -- ",     width=100, command= self.drawAll, state= 'disabled')
        self.butt_print    = Button(self.fram_ignition,   text= "Save Image", command= self.saveImage, state= 'disabled')
        self.chek_fullscrn = CheckBox(self.fram_ignition, text= "Fullscreen", variable= self.fullScreen, state= 'disabled')
        self.fram_ignition.grid(row=1, column=0, columnspan=2)
        self.butt_generate.grid(row=0, column=0, columnspan=2)
        self.butt_draw.grid(    row=1, column=0)
        self.butt_print.grid(   row=0, column=2, rowspan= 2, sticky='ns')
        self.chek_fullscrn.grid(row=1, column=1)

    def createWidgets(self):
        self.incThickYN    = False
        self.reverseThick  = False
        self.style         = RIDGE
        self.startingPoint = (20, 20)
        self.generated     = False
        self.fileOptions()
        self.makeMenuBar()
        self.makeInputFrame()
        self.makeCanvasFrame()
        self.makeIgnitionFrame()
Пример #57
0
class Tkdialog:

    """ The user dialog. """

    def __init__(self, photoDescription, photo, filename):
        self.root = Tk()
        # "%dx%d%+d%+d" % (width, height, xoffset, yoffset)
        self.root.geometry("%ix%i+10-10" % (config.tkhorsize, config.tkvertsize))

        self.root.title(filename)
        self.photoDescription = photoDescription
        self.filename = filename
        self.photo = photo
        self.skip = False
        self.exit = False

        # --Init of the widgets
        # The image
        self.image = self.getImage(self.photo, 800, 600)
        self.imagePanel = Label(self.root, image=self.image)

        self.imagePanel.image = self.image

        # The filename
        self.filenameLabel = Label(self.root, text=u"Suggested filename")
        self.filenameField = Entry(self.root, width=100)
        self.filenameField.insert(END, filename)

        # The description
        self.descriptionLabel = Label(self.root, text=u"Suggested description")
        self.descriptionScrollbar = Scrollbar(self.root, orient=VERTICAL)
        self.descriptionField = Text(self.root)
        self.descriptionField.insert(END, photoDescription)
        self.descriptionField.config(state=NORMAL, height=12, width=100, padx=0, pady=0, wrap=WORD, yscrollcommand=self.descriptionScrollbar.set)
        self.descriptionScrollbar.config(command=self.descriptionField.yview)

        # The buttons
        self.okButton = Button(self.root, text="OK", command=self.okFile)
        self.skipButton = Button(self.root, text="Skip", command=self.skipFile)

        # --Start grid

        # The image
        self.imagePanel.grid(row=0, column=0, rowspan=11, columnspan=4)

        # The buttons
        self.okButton.grid(row=11, column=1, rowspan=2)
        self.skipButton.grid(row=11, column=2, rowspan=2)

        # The filename
        self.filenameLabel.grid(row=13, column=0)
        self.filenameField.grid(row=13, column=1, columnspan=3)

        # The description
        self.descriptionLabel.grid(row=14, column=0)
        self.descriptionField.grid(row=14, column=1, columnspan=3)
        self.descriptionScrollbar.grid(row=14, column=5)

    def getImage(self, photo, width, height):
        """Take the StringIO object and build an imageTK thumbnail."""
        image = Image.open(photo)
        image.thumbnail((width, height))
        imageTk = ImageTk.PhotoImage(image)
        return imageTk

    def okFile(self):
        """ The user pressed the OK button. """
        self.filename = self.filenameField.get()
        self.photoDescription = self.descriptionField.get(0.0, END)
        self.root.destroy()

    def skipFile(self):
        """ The user pressed the Skip button. """
        self.skip = True
        self.root.destroy()

    def run(self):
        """ Activate the dialog and return the new name and if the image is
        skipped.

        """
        self.root.mainloop()
        return self.photoDescription, self.filename, self.skip
Пример #58
-1
 def __createWindowOnId(self, itemId, content):
     if self.currentlyRenderedWindow != None:
         self.currentlyRenderedWindow()
     # self.__remove(self.currentlyRenderedWindow)
     idtuple = self.localCanvas.coords(itemId)
     if idtuple:
         x = idtuple[0]
         y = idtuple[1]
         frm = Frame(self.localCanvas)
         frm.grid(row=0, column=0)
         canv = Canvas(frm)            
         
         vscroll = Scrollbar(frm, orient="vertical", command=canv.yview)
         vscroll.grid(row=0, column=1, sticky=N + S)
         
         canv.grid(row=0, column=0)
         
         canv["yscrollcommand"] = vscroll.set
         aframe = Frame(canv)
         aframe.grid(row=0, column=0)
         Label(aframe, text=content, anchor="center", background="#CCFFCC", borderwidth=6, relief="ridge", justify="left").grid(row=1, column=0)
         canvWindow = canv.create_window(x, y, window=aframe)
         canv.coords(canvWindow, x, y)
         self.localCanvas.update_idletasks()
         canv["scrollregion"] = canv.bbox("all")
         
         def destroyAll():
             self.__remove(canvWindow)
             canv.destroy()
             aframe.destroy()
             vscroll.destroy()
             frm.destroy()
             
         self.currentlyRenderedWindow = destroyAll 
         Button(frm, text="Close", command=lambda :  destroyAll()).grid(row=2, column=0)