示例#1
1
def show_source_tree(head):
    root = Tk()
    frame = Frame(root)
    frame.pack(fill = 'both')
    tree = tkinter.ttk.Treeview(frame)
    
    #insert root subroutine
    # @type head Node
    parent_id = tree.insert('', 'end', '', text = head.name)
    for child in head.children:
        child.insert_to_tree(tree, parent_id)



    
    #add scrollbar
    v_scrollbar = Scrollbar(frame, orient = VERTICAL, command = tree.yview)
    h_scrollbar = Scrollbar(frame, orient = HORIZONTAL, command = tree.xview)
    tree.configure(yscrollcommand = v_scrollbar.set, xscrollcommand = h_scrollbar.set)
    
    v_scrollbar.pack(side = 'right', fill = 'y')
    h_scrollbar.pack(side = 'bottom', fill = 'x')


    tree.pack(fill = 'both')
    root.geometry("600x600")
    root.mainloop()
示例#2
0
def startGui():
    try:
        import_tk()
    except:
        logging.error("Error Starting GUI. Could Not Find Tkinter module" + "Please install the Python Tkinter module")
        return

    root = Tk()
    root.wm_title("Eagle V6 to KiCad Converter")
    root.wm_minsize(400, 200)
    frame = Frame(root, relief=RIDGE, bg="BLUE", borderwidth=2)
    frame.pack(fill=BOTH, expand=1)

    label = Label(frame, font=20, bg="BLUE", text="What Would You Like to Do:")
    label.pack(fill=X, expand=1)

    butBrd = Button(frame, text="Convert Board", command=convertBoardGUI)
    butBrd.pack(fill=X, expand=1)
    butLib = Button(frame, text="Convert Library", command=convertLibGUI)
    butLib.pack(fill=X, expand=1)
    butSch = Button(frame, text="Convert Schematic", command=convertSchGUI)
    butSch.pack(fill=X, expand=1)

    label = Label(frame, bg="BLUE", text="www.github.com/Trump211")
    label.pack(fill=X, expand=1)

    root.mainloop()
示例#3
0
    def __init__(self, parent, title=None):
        Toplevel.__init__(self, parent)
        self.transient(parent)

        if title:
            self.title(title)

        self.parent = parent
        self.result = None

        body = Frame(self)
        self.initial_focus = self.body(body)
        body.pack(padx=5, pady=5)
        self.buttonbox()
        self.grab_set()

        if not self.initial_focus:
            self.initial_focus = self

        self.protocol("WM_DELETE_WINDOW", self.cancel)
        self.geometry("+%d+%d" % (parent.winfo_rootx() + 50,
                                  parent.winfo_rooty() + 50))
        self.initial_focus.focus_set()

        self.wait_window(self)
示例#4
0
文件: wall.py 项目: rkedge/ColorWall
class Wall(object):
    MIN_RED = MIN_GREEN = MIN_BLUE = 0x0
    MAX_RED = MAX_GREEN = MAX_BLUE = 0xFF

    PIXEL_WIDTH = 50

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self._tk_init()
        self.pixels = [(0, 0, 0) for i in range(self.width * self.height)]

    def _tk_init(self):
        self.root = Tk()
        self.root.title("ColorWall %d x %d" % (self.width, self.height))
        self.root.resizable(0, 0)
        self.frame = Frame(self.root, bd=5, relief=SUNKEN)
        self.frame.pack()

        self.canvas = Canvas(self.frame,
                             width=self.PIXEL_WIDTH * self.width,
                             height=self.PIXEL_WIDTH * self.height,
                             bd=0, highlightthickness=0)
        self.canvas.pack()
        self.root.update()

    def set_pixel(self, x, y, hsv):
        self.pixels[self.width * y + x] = hsv

    def get_pixel(self, x, y):
        return self.pixels[self.width * y + x]

    def draw(self):
        self.canvas.delete(ALL)
        for x in range(len(self.pixels)):
            x_0 = (x % self.width) * self.PIXEL_WIDTH
            y_0 = (x / self.width) * self.PIXEL_WIDTH
            x_1 = x_0 + self.PIXEL_WIDTH
            y_1 = y_0 + self.PIXEL_WIDTH
            hue = "#%02x%02x%02x" % self._get_rgb(self.pixels[x])
            self.canvas.create_rectangle(x_0, y_0, x_1, y_1, fill=hue)
        self.canvas.update()

    def clear(self):
        for i in range(self.width * self.height):
            self.pixels[i] = (0, 0, 0)

    def _hsv_to_rgb(self, hsv):
        rgb = colorsys.hsv_to_rgb(*hsv)
        red = self.MAX_RED * rgb[0]
        green = self.MAX_GREEN * rgb[1]
        blue = self.MAX_BLUE * rgb[2]
        return (red, green, blue)

    def _get_rgb(self, hsv):
        red, green, blue = self._hsv_to_rgb(hsv)
        red = int(float(red) / (self.MAX_RED - self.MIN_RED) * 0xFF)
        green = int(float(green) / (self.MAX_GREEN - self.MIN_GREEN) * 0xFF)
        blue = int(float(blue) / (self.MAX_BLUE - self.MIN_BLUE) * 0xFF)
        return (red, green, blue)
示例#5
0
class GUI(object):
    """
    The base class for GUI builder
    """

    __metaclass__ = ABCMeta

    def __init__(self, root):
        self.colorPicker = ColorPicker(root)
        self.topToolbar = Frame(root, bd=1, relief=RAISED)
        self.topToolbar.pack(side=TOP, fill=X)
        self.canvas = DrawingCanvas(root, self.colorPicker)
        self.canvas.pack(expand=YES, fill=BOTH)

    # Initializes IO and Draw commands.
    @abstractmethod
    def initButtons(self, ios, commands):
        pass

    # Event handler when users click on an IO command.
    @abstractmethod
    def onIOCommandClick(self, button, command):
        pass

    # Event handler when users click on a draw command.
    @abstractmethod
    def onDrawCommandClick(self, button, command):
        pass

    # Event handler when users change the selected color.
    @abstractmethod
    def onChangeColor(self, command):
        pass
    def initUI(self):
      
        self.lineCounter = 0
      
        # create a custom font
        self.customFontHeader = font.Font(family="Calibri", slant = "italic") #family="Helvetica", weight="bold", slant="italic")
        self.customFontMessage = font.Font(family="Calibri")
        
        self.parent.title("Python Chat") 
        
        frame = Frame(self.parent)
        frame.pack(fill=BOTH, expand=1, side=LEFT)
        
        self.box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
        self.box.insert(END, 'Welcome to Python Chat!')
        self.box.config(state=DISABLED)
        self.box.pack(expand="yes", fill=BOTH, side=TOP)
        
        self.textarea = Text(frame, width=30, height=5)
        #self.textarea.insert(END, "")
        self.textarea.bind("<KeyRelease-Return>", self.gettext) #Se metto on press, rimane una newline in piu
        self.textarea.pack(expand="yes", fill=BOTH, side=TOP)

        
        okButton = Button(frame, text="Panic Button", activebackground="red", command=self.sendFile) 
        okButton.pack(expand="no", fill=BOTH, side=TOP)
        
        self.usersFrame = Frame(self.parent)
        self.usersFrame.pack(fill=BOTH, expand=1, side=RIGHT)
        
        self.userListbox = Listbox(self.usersFrame, width=3)
        self.userListbox.pack(fill=BOTH, expand=1)
            
        self.updateUsersFrame()
    def show_captcha(self,img_file):
        dialogRoot = Tk()
        dialogRoot.title("Input text.")
    
        img = PhotoImage(file=img_file)
    
        frame = Frame(dialogRoot)
    
        imal = Label(frame, image=img)
        imal.pack()
    
        label = Label(frame)
        label['text'] = "Your Input:"
        label.pack(side=LEFT)
    
        inputEntry = Entry(frame)
        inputEntry["width"] = 50
        inputEntry.pack(side=LEFT)
    
        def getInputText():
            '''callback of button'''
            # global inputEntry, dialogRoot
            if inputEntry.get().strip() == "":
                print("Please enter a message.")
            else:
                self.captcha_ans = inputEntry.get().strip()
                dialogRoot.destroy()

    
        button = Button(frame, text="Submit", command=getInputText)
        button.pack(side=LEFT)
    
        frame.pack()
        dialogRoot.mainloop()
示例#8
0
class ChoosePlayerDialog(Toplevel):
    """Dialog used to prompt the user to choose a player."""
    def __init__(self, program: GUIProgram):
        super(ChoosePlayerDialog, self).__init__(program.app)
        self.title('Choose Player')
        self.program = program
        self.body = Frame(self)
        self.initial_focus = self.body
        self.body.pack()
        self.create_widgets()
        self.initial_focus.focus_set()
        # If this window is closed, terminate the application.
        self.wm_protocol('WM_DELETE_WINDOW', self.on_close)

    def create_widgets(self):
        """Generate the label and buttons to prompt the user for a player."""
        Label(self.body, text='Choose your player:').pack()
        for player in Player:
            Button(self.body, text=player,
                   command=partial(self.click_handler, player),
                   **GUIProgram.standard_button_dimensions).pack()

    def click_handler(self, player: Player):
        """Callback used to call back into the main program to handle the
        player choice.  Once complete, the dialog is closed.
        """
        self.program.handle_player_choice(player)
        self.body.destroy()
        self.destroy()

    def on_close(self):
        """Callback used to terminate the application if closed."""
        self.program.window.quit()
示例#9
0
def makeWindow():
    'create GUI'
    frame = Frame(width=100, height=100, background = "blue")
    frame.bind("<Button-1>", handler)
    frame.bind('<Button-3>', handler2)
    frame.pack()
    frame.mainloop()
示例#10
0
def ua_win_tk(url, pipe = None):
    from tkinter import Tk, Frame, Label, Entry, StringVar, BOTH, Button, RIGHT
    import sys
    sys.stdout.flush()
    instructions = "Visit the following URL to authorize the application:"
    response = {"x": False}
    root = Tk()
    root.title("oAuth2 Authorization Required")
    webbox = Frame(root)
    instructions = Label(webbox, text = instructions)
    instructions.pack(padx = 5, pady = 5)
    urlstr = StringVar(value = url)
    urlbox = Entry(webbox, textvariable = urlstr, state = "readonly")
    urlbox.pack(padx = 5, pady = 5)
    def open_browser():
        from subprocess import Popen
        p = Popen(["sensible-browser", url])
    browserbutton = Button(webbox, text = "Open in web browser", command = open_browser)
    browserbutton.pack(padx = 5, pady = 5)
    webbox.pack(fill = BOTH, expand = 1)
    if pipe:
        def poll():
            if pipe.poll():
                root.destroy()
                #Mutability ftw... wat
                response["x"] = True
            else:
                root.after(300, poll)
        root.after(300, poll)
    cancelbutton = Button(root, text = "Cancel", command = root.destroy)
    cancelbutton.pack(side = RIGHT, padx = 5, pady = 5)
    root.mainloop()
    return response["x"]
示例#11
0
    def initUI(self):
        self.parent.title('PyZilla')
        self.padding = 5

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

        # Create a menubar
        mnuMenu = Menu(self.parent)
        self.parent.config(menu=mnuMenu)

        # Create menubar
        mnuFileMenu = Menu(mnuMenu)

        # Add File menu items
        mnuFileMenu.add_command(label='Open', command=self.onBtnOpenFile)
        mnuFileMenu.add_command(label='Exit', command=self.quit)

        # Add File menu items to File menu
        mnuMenu.add_cascade(label='File', menu=mnuFileMenu)

        # Create frame for all the widgets
        frame = Frame(self)
        frame.pack(anchor=N, fill=BOTH)

        # Create file open dialog
        btnOpenFile = Button(frame, text="Load file", command=self.onBtnOpenFile)
        btnOpenFile.pack(side=RIGHT, pady=self.padding)

        # Create filename label
        self.lblFilename = Label(frame, text='No filename chosen...')
        self.lblFilename.pack(side=LEFT, pady=self.padding, padx=self.padding)

        # Create the text widget for the results
        self.txtResults = Text(self)
        self.txtResults.pack(fill=BOTH, expand=1, pady=self.padding, padx=self.padding)
示例#12
0
    def create_widgets(self):
        """ Login form """

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

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

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

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

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

        #layout widgets in grid
        self.email_label.grid(row=1, column=0)
        self.email_entry.grid(row=1, column=1)
        self.password_label.grid(row=2, column=0)
        self.password_entry.grid(row=2, column=1)
        self.submit.grid(row=2, column=0)
示例#13
0
class PyBooguNote(Frame):
    """Main class"""
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent

        self.create_toolbar()
        self.sc = ScrolledCanvas(parent, bg="white", highlightthickness=0, takefocus=1)
        self.sc.frame.pack(expand=1, fill='both')

    def create_toolbar(self):
        self.toolbar = Frame(self.parent)
        self.btn_new = Button(self.toolbar, text='New', command=self.new_file)
        self.btn_new.grid(row=0, column=0)
        self.btn_open = Button(self.toolbar, text='Open', command=self.open_file)
        self.btn_open.grid(row=0, column=1)
        self.toolbar.pack(fill='both')

    def open_file(self):
        self.file_path = askopenfilename(filetypes=[('BooguNote Files', '.boo')])
        self.dom = parse(self.file_path)
        curItem = None
        pyBt = PyBooguTree(self.sc.canvas, self.file_path, self.dom)
    
    def new_file(self):
        self.file_path = asksaveasfilename()
        print(self.file_path)
示例#14
0
    def __init__(self, parent, handler):

        '''Initialization method.'''

        Frame.__init__(self, parent)

        button_frame = Frame(self)
        button_frame.pack(side=TOP)

        self.deal_button = Button(button_frame, text="Deal",
                                  command=lambda: handler("deal"))
        self.deal_button.pack(side=LEFT, padx=5, pady=5)

        self.quit_button = Button(button_frame, text="Quit",
                                  command=lambda: handler("quit"))
        self.quit_button.pack(side=RIGHT, padx=5, pady=5)

        self.exchange_button = Button(button_frame, text="Exchange",
                                      command=lambda: handler("exchange"))
        self.exchange_button.pack(side=RIGHT, padx=5, pady=5)

        self.show_button = Button(button_frame, text="Show",
                                  command=lambda: handler("show"))
        self.show_button.pack(side=RIGHT, padx=5, pady=5)

        label_frame = Frame(self)
        label_frame.pack(side=BOTTOM)

        self.status_label = Label(label_frame, relief=SUNKEN)
        self.set_status_text("No text to show")
        self.status_label.pack(side=TOP, padx=5, pady=5)
示例#15
0
 def __init__(self, *args, **kwargs):
     self._app = Scripting.root_node
     self.__topwin = kwargs.pop('topwin')
     super().__init__(*args, **kwargs)
     
     frm = Frame(self)
     self.__gui_images = []
     imageMatFileBtn = ImageTk.PhotoImage(
         file=Scripting.root_node.get_gui_image_path('Pattern_SaveMat_Button.png'))
     self.__gui_images.append(imageMatFileBtn)
     Button(
         frm, 
         image=imageMatFileBtn, 
         command=self._on_save_mat_file).pack(side='top')
     Button(
         frm, 
         text='mat', 
         width=6).pack(side='top')
     frm.pack(side='left')
     
     frm = Frame(self)
     imageExcelFileBtn = ImageTk.PhotoImage(
         file=Scripting.root_node.get_gui_image_path('Pattern_SaveExcel_Button.png'))
     self.__gui_images.append(imageExcelFileBtn)
     Button(frm, image=imageExcelFileBtn).pack(side='top')
     Button(frm, text='xlsx', width=6).pack(side='top')
     frm.pack(side='left')
     
     self.name = 'Corr Matrix'
示例#16
0
    def append_algorithm(self, algorithm):
        #To do: when algo is reset, the frm should be removed
        for algoName in self.__frameDict:
            self.__frameDict[algoName]['frame'].pack_forget()
        frm = Frame(self)
        frm.pack()
        paramInfo   = {}
        params = algorithm['parameters']
        for index, name in enumerate(params):
            param = params[name]
            paramitem = LabeledEntry(frm)
            paramitem.label_text = name
            paramitem.label_width = 5
            paramitem.entry_width = 8
            if self.balloon:
                tip = f'''{param.shortdesc}

Type: {param.type.__name__}.'''
                self.balloon.bind_widget(paramitem.label, balloonmsg=tip)
            if param.type is int:
                paramitem.checker_function = self._app.gui.value_checker.check_int
            elif param.type is float:
                paramitem.checker_function = self._app.gui.value_checker.check_float
            paramitem.grid(row=index%self.__MAXROW, column=index//self.__MAXROW)
            #self.__params[param.name] = {'gui':paramitem, 'meta':param}
            paramInfo[param.name] = {'gui':paramitem, 'meta':param}
        self.__algo = algorithm
        #self.__frameDict[algorithm.meta.name]   = frm
        self.__frameDict[algorithm['name']]   = dict(frame=frm, paramInfo=paramInfo)
        self.__params   = paramInfo
示例#17
0
    def __init__(self, root, title):
        self.root = root
        self.root.title(title)

        # Variable that stores file handle (may be unnecessary)
        self.file_handle = ""

        master_frame = Frame(root)
        master_frame.pack(expand="yes", fill="both")

        # Create left button frame and buttons
        button_frame = Frame(master_frame)
        self.open_button = Button(button_frame, text="Choose File", command=self.load_file)
        self.open_button.pack(expand="yes", fill="both")
        self.apply_button = Button(button_frame, text="Apply", command=self.apply_consistent, state="disabled")
        self.apply_button.pack(expand="yes", fill="both")
        self.save_button = Button(button_frame, text="Save File", command=self.save_file, state="disabled")
        self.save_button.pack(expand="yes", fill="both")

        # Create text frame and initialize text widget
        text_frame = Frame(master_frame)
        self.text_box = Text(text_frame, height=10, width=50, state="disabled")
        self.text_box.pack(side="top", expand="yes", fill="both")

        # Configure weights for grid elements
        master_frame.columnconfigure(0, weight=1)
        master_frame.columnconfigure(1, weight=5)
        for i in range(3):
            master_frame.rowconfigure(i, weight=1)

        # Position button and text frames
        button_frame.grid(row=0, column=0, rowspan=3, sticky="nsew")
        text_frame.grid(row=0, column=1, rowspan=3, sticky="nsew")
        
        self.root.minsize(500, 200)
示例#18
0
    def addPathFrame(self):
        frame=Frame(self)
        frame.pack(fill=tk.X,expand=0,side=tk.TOP,padx=8,pady=5)

        frame.columnconfigure(1,weight=1)

        #------------------Database file------------------
        label=tk.Label(frame,text=dgbk('ting.sqlite文件:'),\
                bg='#bbb')
        label.grid(row=0,column=0,\
                sticky=tk.W,padx=8)

        self.db_entry=tk.Entry(frame)
        self.db_entry.grid(row=0,column=1,sticky=tk.W+tk.E,padx=8)

        self.db_button=tk.Button(frame,text=dgbk('打开'),command=self.openFile)
        self.db_button.grid(row=0,column=2,padx=8,sticky=tk.E)

        #--------------------Output dir--------------------
        label2=tk.Label(frame,text=dgbk('导出到文件夹:'),\
                bg='#bbb')
        label2.grid(row=2,column=0,\
                sticky=tk.W,padx=8)

        self.out_entry=tk.Entry(frame)
        self.out_entry.grid(row=2,column=1,sticky=tk.W+tk.E,padx=8)
        self.out_button=tk.Button(frame,text=dgbk('选择'),command=self.openDir)
        self.out_button.grid(row=2,column=2,padx=8,sticky=tk.E)
示例#19
0
class GuiGenerateCount(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent
        self.pack()
        
        #step increment len
        self._stepLenFrm  = Frame(self); self._stepLenFrm.pack()
        self._stepLenLbl  = Label(self._stepLenFrm, text="Step Len: ");   self._stepLenLbl.pack(side=LEFT)
        self._stepLenSpin = Spinbox(self._stepLenFrm, from_=0, to=1000); self._stepLenSpin.pack(side=LEFT)
        
        #start value
        self._startFrm  = Frame(self); self._startFrm.pack()
        self._startLbl  = Label(self._startFrm, text="Start Value: ");   self._startLbl.pack(side=LEFT)
        self._startTxt  = Entry(self._startFrm);   self._startTxt.pack(side=LEFT)
        self._startTxt.insert(0, "0")
        
    def getSettings(self):
        return  {   "StepLen":      self._stepLenSpin.get(),
                    "StartValue":   self._startTxt.get()
                }
    
    def getName(self):
        return "Counter"
        
    def getGeneratorFunction(self):
        return generateCounter
示例#20
0
class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.toolbar = Frame(self, bg="#eee")
        self.toolbar.pack(side="top", fill="x")

        self.bold = Button(self.toolbar, text="Bold", command=self.make_bold)
        self.bold.pack(side="left")

        self.clear = Button(self.toolbar, text="Clear", command=self.clear)
        self.clear.pack(side="left")

        # Creates a bold font.
        self.bold_font = Font(family="Helvetica", size=14, weight="bold")

        self.text = Text(self)
        self.text.insert("end", "Select part of text and then click 'Bold'...")
        self.text.focus()
        self.text.pack(fill="both", expand=True)

        # Configures a tag called BOLD.
        self.text.tag_configure("BOLD", font=self.bold_font)

    def make_bold(self):
        # tk.TclError exception is raised if not text is selected.
        try:
            self.text.tag_add("BOLD", "sel.first", "sel.last")
        except TclError:
            pass

    def clear(self):
        self.text.tag_remove("BOLD", "1.0", 'end')
示例#21
0
 def game_window(self):
     ##Window##
     self.root.grid()
     self.root.title("Equations")
     ##Canvas##
     #Frame
     frame=Frame(self.root)
     frame.pack()
     self.canvas=tk.Canvas(frame, bg="white", width=800, height=500)
     self.canvas.pack()
     #Background/label
     bg_image=tk.PhotoImage(file="EQUATIONSbackground.gif")
     self.canvas.create_image(0, 250, image=bg_image, anchor="w")
     
     ##Score Display##
     score_label=tk.Label(self.root, text=["Score:", self.score], font=("Courier", 20), fg="red", bg="white")
     score_label.pack()
     score_label.place(x=650, y=450)
     
     ##Popup Menu##
     popupmenu=tk.Label(self.canvas, text=("Answer all eight equations correctly!"), font=("Courier", 12), anchor="n", bg="white", fg="black", height=7)
     popupmenu.place(x=280, y=180)
     #Return to Menu Button
     returnmenu=tk.Button(self.canvas, text="Main Menu", bg="white", command=self.returntomenu)
     returnmenu.place(x=425, y=240)
     #Start Button
     start=tk.Button(self.canvas, text="Start", bg="white")
     start.config(command= lambda: self.gameplay(popupmenu, start, returnmenu, score_label, 8))
     start.place(x=325, y=240)
             
     ##Keep running##
     self.root.mainloop()
 def receivePrivateChat(self, connectingUser):
     global conversationBoxList
     print("CHAT PRIVATA in arrivo con "+connectingUser)
         
     newWindow = Toplevel(self.parent)
     newWindow.title("Python Chat requested by "+connectingUser)
     newWindow.minsize(400, 475)
     newWindow.focus()
     
     def disconnectPM():
         del conversationBoxList[connectingUser]
         newWindow.destroy()
     newWindow.protocol('WM_DELETE_WINDOW', disconnectPM)
     
     #label = Label(newWindow, text="PROVA PROVA")
     #label.pack(side="top", fill="both", padx=10, pady=10)
     frame = Frame(newWindow)
     frame.pack(fill=BOTH, expand=1, side=LEFT)
     
     box = ScrolledText(frame, wrap=WORD, relief = GROOVE, width=30, height=18, font=self.customFontMessage)
     box.config(state=DISABLED)
     box.pack(expand="yes", fill=BOTH, side=TOP)
     
     textarea = Text(frame, width=30, height=5)
     textarea.bind("<KeyRelease-Return>", lambda event : self.getprivatetext(event, textarea, connectingUser)) 
     textarea.pack(expand="yes", fill=BOTH, side=TOP)
     
     #aggiungo alla mappa globale il box di conversazione
     conversationBoxList[connectingUser] = box
 def _init_paging(self, parent):
     innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
     self.prev = prev = Button(innerframe, text='Previous', command=self.previous, width='10', borderwidth=1, highlightthickness=1, state='disabled')
     prev.pack(side='left', anchor='center')
     self.next = next = Button(innerframe, text='Next', command=self.__next__, width='10', borderwidth=1, highlightthickness=1, state='disabled')
     next.pack(side='right', anchor='center')
     innerframe.pack(side='top', fill='y')
     self.current_page = 0
示例#24
0
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.entry = Entry(frame)
        self.entry.pack(side=LEFT)

        self.entry.bind('<Return>', self.on_click)
class ParseGUI(object):
    """Class used for the GUI
    The object parameter is the root widget for the Tkinter GUI
    """
    def __init__(self, master):
        """Constructor method

        :param master: A "master" wigdet
        """
        self.mainframe = Frame(master)  # Create a Frame child widget
        self.mainframe.pack()  # Make the widget visible

        self.path = ''  # Define default path for the .xmcd file
        self.texfile_path = ''  # Define path for the .tex file

        self.name = Label(self.mainframe, text="Welcome to Mathcad to LaTeX converter")  # Create a static text label
        self.name.pack(side="top")  # Make the widget visible and define location

        self.filename = StringVar()  # Create a dynamic string variable
        self.filename.set("Current selected file: none")  # Set the string value
        self.filename_label = Label(self.mainframe, textvariable=self.filename)  # Create a label with the dynamic var
        self.filename_label.pack()
        self.text_updater = Entry(self.mainframe, textvariable=self.filename)  # Create a Entry widget for auto updates

        self.status = StringVar()  # Used for displaying the status of the file operation
        self.status.set("Status: Not parsed")
        self.status_label = Label(self.mainframe, textvariable=self.status)
        self.status_label.pack()
        self.text_updater2 = Entry(self.mainframe, textvariable=self.status)

        self.parse_file = Button(self.mainframe, text="Parse and save!", command=self.parse_file)  # Button for parsing
        self.parse_file.pack(side="right")

        self.parse_file = Button(self.mainframe, text="Open LaTeX file", command=self.open_file)
        self.parse_file.pack(side="right")

        self.select_file = Button(self.mainframe, text="Select file", command=self.select_file)  # Runs a class method
        self.select_file.pack(side="right")

    def select_file(self):  # Method used for selecting a file
        self.path = askopenfilename()  # Display native os file dialog for choosing a file
        self.filename.set("Current selected file: " + os.path.basename(self.path))  # Change the dynamic variable
        self.status.set("Status: Not parsed")  # Set status

    def open_file(self):  # Method used for opening the parsed LaTeX file
        self.texfile_path = os.path.dirname(self.path) + '/ParsedLatexFile/' + os.path.splitext(os.path.basename(self.path))[0] + '.tex'
        if self.status.get() == "Status: File tried parsed! Look under the folder \ParsedLatexFile !":
            os.system("start " + "\"\" \"" + self.texfile_path + "\"")

    def parse_file(self):  # Method for parsing the chosen file
        # Make sure a file is selected and it is a Mathcad file before trying to parse it
        if self.filename.get() != 'Current selected file: none' and os.path.splitext(self.path)[1] == '.xmcd':
            self.status.set("Status: Tring to parse... (most files takes a few seconds)")
            MathcadXMLParser(self.path)  # Call the MathcadXMLParser class with the path
            self.status.set("Status: File tried parsed! Look under the folder \ParsedLatexFile !")
        # Display a error message to the user
        else:
            self.status.set("Status: You need to select a .xmcd (Mathcad) file!")
示例#26
0
  def __init__(self, *, multiple_runner_class, input_spec, left_name,
               right_name):
    """Sets up windows and the instance of RunMultipleTimes that will do the actual work."""
    #: The input_spec is an iterable of
    #: :py:class:`farg.core.read_input_spec.SpecificationForOneRun`.
    self.input_spec = input_spec
    #: Class responsible for the actual running multiple times.
    self.multiple_runner_class = multiple_runner_class
    #: Main window
    self.mw = mw = Tk()
    #: Statistics thus far, grouped by input.
    self.stats = AllStats(left_name=left_name, right_name=right_name)

    #: Are we in the process of quitting?
    self.quitting = False

    self.status_label = Label(
        mw, text='Not Started', font=('Times', 20), foreground='#000000')
    self.status_label_text = self.status_label.cget('text')
    self.status_label.pack(side=TOP, expand=True, fill=X)

    #: Has a run started? Used to ensure single run.
    self.run_started = False

    details_frame = Frame(mw)
    details_frame.pack(side=TOP)
    #: listbox on left listing inputs.
    frame = Frame(details_frame)
    scrollbar = Scrollbar(frame, orient=VERTICAL)
    listbox = Listbox(
        frame,
        yscrollcommand=scrollbar.set,
        height=25,
        width=70,
        selectmode=SINGLE)
    scrollbar.config(command=listbox.yview)
    scrollbar.pack(side=RIGHT, fill=Y)
    listbox.pack(side=LEFT, fill=BOTH, expand=1)
    listbox.bind('<ButtonRelease-1>', self.SelectForDisplay, '+')
    frame.pack(side=LEFT)
    self.listbox = listbox
    #: Canvas on right for details
    self.canvas = Canvas(
        details_frame,
        width=kCanvasWidth,
        height=kCanvasHeight,
        background='#FFFFFF')
    self.canvas.pack(side=LEFT)
    #: which input are we displaying the details of?
    self.display_details_for = None

    #: Thread used for running
    self.thread = None
    self.mw.bind('<KeyPress-q>', lambda e: self.Quit())
    self.mw.bind('<KeyPress-r>', lambda e: self.KickOffRun())
    self.Refresher()
    self.mw.after(1000, self.KickOffRun)
示例#27
0
文件: map.py 项目: jkesselring/DnDApp
 def toolbox_window(self):
     """Creates the window which will host the toolbox buttons"""
     toolbox_root = Toplevel()
     toolbox_root.title("Toolbox")
     toolbox_root.geometry("455x256")
     toolbox_frame = Frame(toolbox_root)
     toolbox_frame.pack(fill=BOTH)
     
     
示例#28
0
    def gameplay(self):
        ##Window##
        self.root.grid()
        self.root.title("Animals") #Name of the window
        ##Canvas##
        #Frame
        frame=Frame(self.root)
        frame.pack()
        self.canvas=tk.Canvas(frame, bg="white", width=800, height=500)
        self.canvas.pack()
        #Background/label
        bg_image=tk.PhotoImage(file="ANIMALSbackground.gif")
        self.canvas.create_image(0, 200, image=bg_image, anchor="w")
        
        ##Score Display##
        score_label=tk.Label(self.root, text=["Score:", self.score], font=("Courier", 20), fg="red", bg="white")
        score_label.pack()
        score_label.place(x=650, y=450)
        
        ##Popup Menu##
        popupmenu1=tk.Label(self.canvas, text=("Count all the"), font=("Courier", 12), anchor="n", bg="white", fg="black", height=7, width=20)
        popupmenu2=tk.Label(self.canvas, text=(self.chosen_animal), font=("Courier", 12), anchor="n", bg="white", fg="red", height=7)
        popupmenu1.place(x=330, y=180)
        popupmenu2.place(x=473, y=180)
        #Return to Menu Button
        returnmenu=tk.Button(self.canvas, text="Main Menu", bg="white", command=self.returntomenu)
        returnmenu.place(x=420, y=240)
        #Start Button
        start=tk.Button(self.canvas, text="Start", bg="white")
        start.config(command=lambda: self.RandomAnimals(popupmenu1, popupmenu2, start, returnmenu, tiger, zebra, lemur, elephant, panda, 20, score_label))
        start.place(x=350, y=240)
        
        ##Making Animals Into Images##
        #Tiger
        tiger_image=tk.PhotoImage(file="Tiger.gif")
        tiger=tiger_image.subsample(3, 3)
        
        #Zebra
        zebra_image=tk.PhotoImage(file="Zebra.gif")
        zebra=zebra_image.subsample(3, 3)
        
        #Lemur
        lemur_image=tk.PhotoImage(file="Lemur.gif")
        lemur=lemur_image.subsample(3, 3)
        
        #Elephant
        elephant_image=tk.PhotoImage(file="Elephant.gif")
        elephant=elephant_image.subsample(6, 6)
        
        #Panda
        panda_image=tk.PhotoImage(file="Panda.gif")
        panda=panda_image.subsample(5, 5)

        
        #Keep running
        self.root.mainloop()   
 def _init_query_box(self, parent):
     innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
     another = Frame(innerframe, background=self._BACKGROUND_COLOUR)
     self.query_box = Entry(another, width=60)
     self.query_box.pack(side='left', fill='x', pady=25, anchor='center')
     self.search_button = Button(another, text='Search', command=self.search, borderwidth=1, highlightthickness=1)
     self.search_button.pack(side='left', fill='x', pady=25, anchor='center')
     self.query_box.bind('<KeyPress-Return>', self.search_enter_keypress_handler)
     another.pack()
     innerframe.pack(side='top', fill='x', anchor='n')
示例#30
0
文件: app.py 项目: Seluwin/rp
class Application(Frame):

    def __init__(self):
        master = Tk()
        Frame.__init__(self, master)
        master.title(PROGRAM_TITLE)
        self.mid_ax = BooleanVar()
        self.button1_text = 'Reset'
        self.points = []
        self.window_geometry()
        self.create_widgets()
        self.redraw()

    def create_points(self, num_x, num_y):
        x_min = -(num_x // 2)
        x_max = num_x // 2
        x_delta = num_x % 2
        y_min = -(num_y // 2)
        y_max = num_y // 2
        y_delta = num_y % 2
        for i in range( x_min, x_max + x_delta ):
            for j in range( y_min, y_max + y_delta):
                self.points.append(Point(i, j, self.canvas))

    def add_point(self, x, y):
        self.points.append(
            Point(x, y, self.canvas)
        )
        self.redraw()

    def make_transform(self):
        tr_matrix = self.trans.get_matrix()
        for pnt in self.points:
            p = tr_matrix * pnt
            pnt.matrix = p.matrix
            pnt.x = p.matrix[0][0]
            pnt.y = p.matrix[1][0]
        self.redraw()
        #print("sucess")

    def create_widgets(self):
        self.canvas = Canvas(
            self,
            bg=CANVAS_BACKGROUND_COLOR,
            bd=0,
            highlightthickness=0,
            relief=FLAT
        )
        self.canvas.pack(side=LEFT, fill=BOTH, expand=1)

        self.control_panel = Frame(
            self,
            bg=CONTROL_PANEL_BACKGROUND_COLOR,
            width=500,
            #width=self.width/9
        )
        self.control_panel.pack(side=LEFT, fill=Y, expand=0)

        self.cp_wrap = Frame(
            self.control_panel,
            bg=CONTROL_PANEL_BACKGROUND_COLOR,
            width=150,
            #width=self.width/9
        )
        self.cp_wrap.pack(fill=X, expand=0)

        self.button1 = Button(
            self.control_panel,
            text=self.button1_text,
            command=self.reset
        )
        self.button1.pack()

        self.trans = TransformationInputs(
            self.control_panel, 
            bg=CONTROL_PANEL_BACKGROUND_COLOR
        )
        self.check_button1 = Checkbutton(
            self.control_panel,
            text='Axes on mid',
            bg=CONTROL_PANEL_BACKGROUND_COLOR,
            bd=0,
            variable=self.mid_ax,
            onvalue=True, offvalue=False
        )
        self.trans.pack()
        self.check_button1.pack(side=TOP)
        self.trans.create_elements()

    def reset(self):
        self.canvas.delete(ALL)
        identity = [[1,0], [0,1]]
        self.trans.set_matrix_to_input(identity)
        if self.points == []:
            self.create_points(PNTS_ON_X, PNTS_ON_Y)
        else:
            self.points = []
            self.button1_text = '+Points'
        self.redraw()

    def redraw(self):
        self.canvas.delete(ALL)
        if self.mid_ax.get():
            self.draw_mid_axes(points=POINTS_ON_SCREEN // 2)
        else:
            self.draw_edge_axes(points=POINTS_ON_SCREEN // 2)
        for pnt in self.points:
            pnt.draw()

    def window_geometry(self, width=780, height=420):
        self.width = width
        self.height = height
        self.master.minsize(width=width, height=height)
        x = (self.master.winfo_screenwidth() - width) / 2
        y = (self.master.winfo_screenheight() - height) / 2
        self.master.geometry('%dx%d+%d+%d' % (width, height, x, y))
        self.pack(fill=BOTH, expand=1)

    def run(self):
        self.mainloop()

    def draw_edge_axes(self, col='black', points=8):
        mx , my = (self.canvas.winfo_width() / 2, self.canvas.winfo_height() / 2)
        x, y = mx, my
        bot_y = my * 2 - 20
        length = max(x, y)
        len_x, len_y = 2*x, 2*y
        OFFSET = 25
        #draw x
        self.canvas.create_line(
            x - length,
            len_y - OFFSET,
            x + length,
            len_y - OFFSET,
            fill=col,
            width=1,
            capstyle=PROJECTING,
        )
        #draw y
        self.canvas.create_line(
            OFFSET,
            y - length,
            OFFSET,
            y + length,
            fill=col,
            width=1,
            capstyle=PROJECTING,
        )
        # markings on axes
        N = points
        spacing = min(x,y) / N
        for i in range(-N, N + 1):
            #mark x line
            self.canvas.create_line(
                x + spacing*i,
                len_y - OFFSET - 2,
                x + spacing*i,
                len_y - OFFSET + 2,
                fill=col
            )
            #mark y line
            self.canvas.create_line(
                OFFSET - 2,
                y + spacing*i,
                OFFSET + 2,
                y + spacing*i,
                fill=col
            )
            #write numbers on axes
            self.canvas.create_text(x + spacing*i, len_y - OFFSET + 8, text='%d'% (i))
            self.canvas.create_text(OFFSET - 7, y + spacing*i, text='%d'% (-i))
        self.canvas.create_text(OFFSET + 7, 25, text='y')
        self.canvas.create_text(x*2 - 25, y*2 - OFFSET + 7, text='x')

    def draw_mid_axes(self, col='black', points=8):
        mx , my = (self.canvas.winfo_width() / 2, self.canvas.winfo_height() / 2)
        #mid = x,y
        x, y = mx, my
        length = max(x, y)
        #draw x
        self.canvas.create_line(
            x - length,
            y,
            x + length,
            y,
            fill=col,
            width=1,
            capstyle=PROJECTING,
        )
        #draw y
        self.canvas.create_line(
            x,
            y - length,
            x,
            y + length,
            fill=col,
            width=1,
            capstyle=PROJECTING,
        )
        # markings on axes
        N = points
        spacing = min(x,y) / N
        for i in range(1,N):
            self.canvas.create_line(
                x + spacing*i,
                y - 2,
                x + spacing*i,
                y + 2,
                fill=col
            )
            self.canvas.create_line(
                x - spacing*i,
                y - 2,
                x - spacing*i,
                y + 2,
                fill=col
            )
            self.canvas.create_line(
                x - 2,
                y + spacing*i,
                x + 2,
                y + spacing*i,
                fill=col
            )
            self.canvas.create_line(
                x - 2,
                y - spacing*i,
                x + 2,
                y - spacing*i,
                fill=col
            )
            self.canvas.create_text(x + spacing*i, y + 7, text='%d'% (i))
            self.canvas.create_text(x - spacing*i, y + 7, text='%d'% (-i))
            self.canvas.create_text(x - 6, y + spacing*i, text='%d'% (-i))
            self.canvas.create_text(x - 6, y - spacing*i, text='%d'% (i))
        self.canvas.create_text(x + 7, 25, text='y')
        self.canvas.create_text(x*2 - 25, y + 7, text='x')
示例#31
0
class CollocationsView:
    _BACKGROUND_COLOUR = "#FFF"  # white

    def __init__(self):
        self.queue = q.Queue()
        self.model = CollocationsModel(self.queue)
        self.top = Tk()
        self._init_top(self.top)
        self._init_menubar()
        self._init_widgets(self.top)
        self.load_corpus(self.model.DEFAULT_CORPUS)
        self.after = self.top.after(POLL_INTERVAL, self._poll)

    def _init_top(self, top):
        top.geometry("550x650+50+50")
        top.title("NLTK Collocations List")
        top.bind("<Control-q>", self.destroy)
        top.protocol("WM_DELETE_WINDOW", self.destroy)
        top.minsize(550, 650)

    def _init_widgets(self, parent):
        self.main_frame = Frame(
            parent, dict(background=self._BACKGROUND_COLOUR, padx=1, pady=1, border=1)
        )
        self._init_corpus_select(self.main_frame)
        self._init_results_box(self.main_frame)
        self._init_paging(self.main_frame)
        self._init_status(self.main_frame)
        self.main_frame.pack(fill="both", expand=True)

    def _init_corpus_select(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        self.var = StringVar(innerframe)
        self.var.set(self.model.DEFAULT_CORPUS)
        Label(
            innerframe,
            justify=LEFT,
            text=" Corpus: ",
            background=self._BACKGROUND_COLOUR,
            padx=2,
            pady=1,
            border=0,
        ).pack(side="left")

        other_corpora = list(self.model.CORPORA.keys()).remove(
            self.model.DEFAULT_CORPUS
        )
        om = OptionMenu(
            innerframe,
            self.var,
            self.model.DEFAULT_CORPUS,
            command=self.corpus_selected,
            *self.model.non_default_corpora()
        )
        om["borderwidth"] = 0
        om["highlightthickness"] = 1
        om.pack(side="left")
        innerframe.pack(side="top", fill="x", anchor="n")

    def _init_status(self, parent):
        self.status = Label(
            parent,
            justify=LEFT,
            relief=SUNKEN,
            background=self._BACKGROUND_COLOUR,
            border=0,
            padx=1,
            pady=0,
        )
        self.status.pack(side="top", anchor="sw")

    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        menubar = Menu(self.top)

        filemenu = Menu(menubar, tearoff=0, borderwidth=0)
        filemenu.add_command(
            label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-q"
        )
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(
            label="20",
            variable=self._result_size,
            underline=0,
            value=20,
            command=self.set_result_size,
        )
        rescntmenu.add_radiobutton(
            label="50",
            variable=self._result_size,
            underline=0,
            value=50,
            command=self.set_result_size,
        )
        rescntmenu.add_radiobutton(
            label="100",
            variable=self._result_size,
            underline=0,
            value=100,
            command=self.set_result_size,
        )
        rescntmenu.invoke(1)
        editmenu.add_cascade(label="Result Count", underline=0, menu=rescntmenu)

        menubar.add_cascade(label="Edit", underline=0, menu=editmenu)
        self.top.config(menu=menubar)

    def set_result_size(self, **kwargs):
        self.model.result_count = self._result_size.get()

    def _init_results_box(self, parent):
        innerframe = Frame(parent)
        i1 = Frame(innerframe)
        i2 = Frame(innerframe)
        vscrollbar = Scrollbar(i1, borderwidth=1)
        hscrollbar = Scrollbar(i2, borderwidth=1, orient="horiz")
        self.results_box = Text(
            i1,
            font=Font(family="courier", size="16"),
            state="disabled",
            borderwidth=1,
            yscrollcommand=vscrollbar.set,
            xscrollcommand=hscrollbar.set,
            wrap="none",
            width="40",
            height="20",
            exportselection=1,
        )
        self.results_box.pack(side="left", fill="both", expand=True)
        vscrollbar.pack(side="left", fill="y", anchor="e")
        vscrollbar.config(command=self.results_box.yview)
        hscrollbar.pack(side="left", fill="x", expand=True, anchor="w")
        hscrollbar.config(command=self.results_box.xview)
        # there is no other way of avoiding the overlap of scrollbars while using pack layout manager!!!
        Label(i2, text="   ", background=self._BACKGROUND_COLOUR).pack(
            side="left", anchor="e"
        )
        i1.pack(side="top", fill="both", expand=True, anchor="n")
        i2.pack(side="bottom", fill="x", anchor="s")
        innerframe.pack(side="top", fill="both", expand=True)

    def _init_paging(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        self.prev = prev = Button(
            innerframe,
            text="Previous",
            command=self.previous,
            width="10",
            borderwidth=1,
            highlightthickness=1,
            state="disabled",
        )
        prev.pack(side="left", anchor="center")
        self.next = next = Button(
            innerframe,
            text="Next",
            command=self.__next__,
            width="10",
            borderwidth=1,
            highlightthickness=1,
            state="disabled",
        )
        next.pack(side="right", anchor="center")
        innerframe.pack(side="top", fill="y")
        self.reset_current_page()

    def reset_current_page(self):
        self.current_page = -1

    def _poll(self):
        try:
            event = self.queue.get(block=False)
        except q.Empty:
            pass
        else:
            if event == CORPUS_LOADED_EVENT:
                self.handle_corpus_loaded(event)
            elif event == ERROR_LOADING_CORPUS_EVENT:
                self.handle_error_loading_corpus(event)
        self.after = self.top.after(POLL_INTERVAL, self._poll)

    def handle_error_loading_corpus(self, event):
        self.status["text"] = "Error in loading " + self.var.get()
        self.unfreeze_editable()
        self.clear_results_box()
        self.freeze_editable()
        self.reset_current_page()

    def handle_corpus_loaded(self, event):
        self.status["text"] = self.var.get() + " is loaded"
        self.unfreeze_editable()
        self.clear_results_box()
        self.reset_current_page()
        # self.next()
        collocations = self.model.next(self.current_page + 1)
        self.write_results(collocations)
        self.current_page += 1

    def corpus_selected(self, *args):
        new_selection = self.var.get()
        self.load_corpus(new_selection)

    def previous(self):
        self.freeze_editable()
        collocations = self.model.prev(self.current_page - 1)
        self.current_page = self.current_page - 1
        self.clear_results_box()
        self.write_results(collocations)
        self.unfreeze_editable()

    def __next__(self):
        self.freeze_editable()
        collocations = self.model.next(self.current_page + 1)
        self.clear_results_box()
        self.write_results(collocations)
        self.current_page += 1
        self.unfreeze_editable()

    def load_corpus(self, selection):
        if self.model.selected_corpus != selection:
            self.status["text"] = "Loading " + selection + "..."
            self.freeze_editable()
            self.model.load_corpus(selection)

    def freeze_editable(self):
        self.prev["state"] = "disabled"
        self.next["state"] = "disabled"

    def clear_results_box(self):
        self.results_box["state"] = "normal"
        self.results_box.delete("1.0", END)
        self.results_box["state"] = "disabled"

    def fire_event(self, event):
        # Firing an event so that rendering of widgets happen in the mainloop thread
        self.top.event_generate(event, when="tail")

    def destroy(self, *e):
        if self.top is None:
            return
        self.top.after_cancel(self.after)
        self.top.destroy()
        self.top = None

    def mainloop(self, *args, **kwargs):
        if in_idle():
            return
        self.top.mainloop(*args, **kwargs)

    def unfreeze_editable(self):
        self.set_paging_button_states()

    def set_paging_button_states(self):
        if self.current_page == -1 or self.current_page == 0:
            self.prev["state"] = "disabled"
        else:
            self.prev["state"] = "normal"
        if self.model.is_last_page(self.current_page):
            self.next["state"] = "disabled"
        else:
            self.next["state"] = "normal"

    def write_results(self, results):
        self.results_box["state"] = "normal"
        row = 1
        for each in results:
            self.results_box.insert(str(row) + ".0", each[0] + " " + each[1] + "\n")
            row += 1
        self.results_box["state"] = "disabled"
from tkinter import Listbox, END, Button, ANCHOR, Label, Frame, Scrollbar, VERTICAL, RIGHT, Y, Tk, MULTIPLE
import tkinter as tk
root = tk.Tk()
root.geometry("600x640")
root.config(bg="#353130")
#! selcet mode CHECK LINE 19  20

# Create Frame
my_frame = Frame(root)
my_frame.pack()

#scroll bar
scroll_bar_4_my_listbox = Scrollbar(my_frame, orient=VERTICAL)
scroll_bar_4_my_listbox.pack(side=RIGHT,
                             fill=Y)  #? y is to fill UP and DOWN all the way
#? pack in on RIGHT hand side
#Listbox
#*  SELECT MODE = SINGLE IS AT DEFAULT.  <OTHER OPTIONS> BROWSE, MULTIPLE, EXTENDED
my_listbox = Listbox(
    my_frame,
    width=50,
    bg="#353130",
    fg="white",
    yscrollcommand=scroll_bar_4_my_listbox.set,
    selectmode=MULTIPLE)  #?yscrollcommand -> is for horizontal scrollbar
my_listbox.pack(pady=15)

## coz of my_listbox no defined so got to put it here

scroll_bar_4_my_listbox.config(command=my_listbox.yview)
示例#33
0
    r2 = text.get('1.0', 'end')
    print('Адрес: \n', r1)
    print('Коментарий: \n', r2)


if __name__ == '__main__':
    root = Tk()
    # Ex1
    frame1 = Frame(root)
    label1 = Label(frame1, text='Ваш адрес:')
    entry = Entry(frame1)
    label2 = Label(frame1, text='Коментарий:')
    text = Text(frame1, width='15', height='5')
    btn = Button(frame1, text='Отправить', bg='cyan', command=response)
    # Pack1
    frame1.pack()
    label1.pack()
    entry.pack()
    label2.pack()
    text.pack()
    btn.pack()
    # Ex2
    frame2 = Frame(root)
    label3 = Label(frame2, text='Сколько штук?')
    value = IntVar()
    value.set(1)
    rb1 = Radiobutton(frame2, text='0-10', variable=value, value=1)
    rb2 = Radiobutton(frame2, text='11-20', variable=value, value=2)
    rb3 = Radiobutton(frame2, text='21-30', variable=value, value=3)
    rb4 = Radiobutton(frame2, text='31-40', variable=value, value=4)
    label4 = Label(frame2, text='Какого цвета?')
    def __init__(self, parent, *args, **kwargs):
        """Constructor
 
        Args:
            parent (tk.widget): parent widget to make the frame a child of
            *args: Variable length argument list
            **kwargs: Arbitrary keyword argument list
        """
        ttk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent

        # Mutex for the networking thread
        self.socket_queue = Queue()

        # Socket server
        self.server = Server(port=25565)
        self.server.start(self.socket_queue)

        # Instantiated signals class to generate signals
        self.ecg_signals = Signals()

        # ============ GUI Variables ============
        # Instructor realtime setting variables
        self.hr = IntVar(self, value=80)
        self.threshold = IntVar(self, value=20)
        self.hr_paced = IntVar(self, value=80)

        # Manual Override variables
        self.position = IntVar(self, value=0)
        self.override_position = BooleanVar(self, value=False)

        self.hr1 = StringVar(self, value='0')

        self.pathway_1 = IntVar(self, value=0)
        self.pathway_2 = IntVar(self, value=0)
        self.is_paced = BooleanVar(self, value=False)

        # Serial in position
        self.serial_position = IntVar(self, value='0')

        # Command variables
        self.wait_for_update = BooleanVar(self, value=False)
        self.wait_for_position = BooleanVar(self, value=False)
        self.wait_for_pathway_1 = BooleanVar(self, value=False)
        self.wait_for_pathway_2 = BooleanVar(self, value=False)

        # ============ Main Frame Sides ===========
        # Signals frame
        frame_signals = Frame(self, bg='black')
        frame_signals.pack(side=tk.LEFT)

        # Monitor value frame
        frame_values = Frame(self, bg='black')
        frame_values.pack(side=tk.RIGHT, padx=10)

        # Take care of plotting
        self.plot_point = 0

        self.new_x = [0.0]
        self.new_y = [0.0]

        self.last_x = 0
        self.last_x_lim = 0

        self.position_to_show = 0

        self.variation = 0

        self.flat_span = False
        self.end_flat = 0
        self.flat_span_y = 0

        # HR Monitor setup
        tk.Label(frame_values,
                 text="HR",
                 font=self.header_2_style,
                 bg="black",
                 fg="lime green").pack()
        tk.Label(frame_values,
                 textvariable=self.hr1,
                 font=self.header_1_style,
                 bg="black",
                 fg="lime green").pack()

        # Serial selection setup
        Options = ['']
        Options.extend(serial.tools.list_ports.comports())

        self.s = 'RIP'
        self.ser = None

        self.variable = StringVar(self)
        self.variable.set(Options[0])  #Default option

        w = OptionMenu(frame_signals, self.variable, *Options)
        w.grid(row=2, column=1)

        self.variable.trace('w', self.change_dropdown)

        # Create plotting canvas
        fig = plt.Figure(figsize=(14, 4.5),
                         dpi=100,
                         facecolor='k',
                         edgecolor='k')

        canvas = FigureCanvasTkAgg(fig, master=frame_signals)
        canvas.get_tk_widget().grid(row=1, column=1)

        # Sets plot customisations
        self.ax = fig.add_subplot(111)
        self.ax.set_xlim(self.last_x_lim, 4)
        self.ax.set_ylim(-3.0, 3.0)
        self.ax.set_yticklabels([])
        self.ax.set_xticklabels([])
        self.ax.xaxis.set_tick_params(width=1, top=True)
        self.ax.set_facecolor('black')

        self.line, = self.ax.plot(0, 0)
        self.ax.get_lines()[0].set_color("xkcd:lime")

        # Starts an animated plot for the ECG signal
        self.ani = animation.FuncAnimation(fig,
                                           self.animate,
                                           interval=24,
                                           blit=True)

        # Polling Initialisation for socket connection
        self.after(10, self.read_socket)
class VacuumEnvironmentGUISimulator:
    def __init__(self):
        self.vacuum_env = None
        self.agent = None
        self.grid_frame = None
        self.grid = None
        self.previous_dims = None
        self.is_running = False
        self.marked_agent_pos = (0, 0)
        self.marked_agent_rot = (1, 0)

        self.setup_gui()
        self.setup_images()
        self.setup_selection_menus()
        self.setup_buttons()

        self.update_all(force=True)

    def setup_gui(self):
        command = yaml.load(open(CONFIG_FILE_NAME))['simulation']['command']
        self.root = Tk()
        self.root.title("Vacuum Environment")
        self.root.minsize(1024, 768)
        self.root.resizable(width=True, height=True)
        self.agent_btn_dims = 22
        self.host_frame = Frame(self.root)
        if command:
            self.setup_command_widget()
        self.setup_log_widget()
        if command:
            self.command_frame.pack(side="top")
        self.options_frame.pack(side="top")
        self.host_frame.pack(expand=True, fill=BOTH)

    def setup_log_widget(self):
        self.log = Text(self.host_frame, width=50, borderwidth=2)
        self.log.pack(side="right", expand=True, fill="y")
        self.log.configure(state="disabled")
        self.options_frame = Frame(self.host_frame)

    def setup_command_widget(self):
        command_frame = Frame(self.host_frame)
        txt = Entry(command_frame, bd=2, width=100)
        txt.pack(side="left")
        self.command_text = txt
        b = Button(command_frame, text="Do It!")
        b.pack(side="right")
        b.config(command=lambda: self.send_user_command)
        txt.bind('<Return>', self.send_user_command)
        self.command_frame = command_frame

    def setup_images(self):
        self.agent_img = dict()
        self.agent_img[(1, 0)] = PhotoImage(file="images/agent_east.png")
        self.agent_img[(0, 1)] = PhotoImage(file="images/agent_south.png")
        self.agent_img[(-1, 0)] = PhotoImage(file="images/agent_west.png")
        self.agent_img[(0, -1)] = PhotoImage(file="images/agent_north.png")
        self.images = {
            ENV_CLEAN: PhotoImage(file="images/blank.png"),
            ENV_DIRTY: PhotoImage(file="images/dirt.png"),
            ENV_WALL: PhotoImage(file="images/wall.png"),
            ENV_GOLD: PhotoImage(file="images/gold.png")
        }
        self.blank_img = PhotoImage(file="images/blank.png")

    def setup_selection_menus(self):
        # Environment wall bias
        self.wall_bias_getter = self.create_selection_menu(
            self.update_all,
            *[(str(bias), bias) for bias in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5]])
        # Environment dirt bias
        self.dirt_bias_getter = self.create_selection_menu(
            self.update_all,
            *[(str(bias), bias)
              for bias in [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]])
        # Environment goal bias
        self.gold_bias_getter = self.create_selection_menu(
            self.update_all,
            *[(str(bias), bias) for bias in [0, 1, 2, 3, 4, 5, 0.01, 0.05]])
        # Environment PRF seed
        self.seed_getter = self.create_selection_menu(
            self.update_all, ("Random", None), ("Seed 1", FIXED_SEED_1),
            ("Seed 2", FIXED_SEED_2),
            always_trigger_onselect=True)

        self.recon_getter = self.create_selection_menu(
            self.update_all, ("None", "None"), ("Full", "Full"),
            ("WallsAndGold", "WallsAndGold"), ("WallsOnly", "WallsOnly"),
            always_trigger_onselect=True)
        self.agent_getter = self.create_selection_menu(
            self.update_all,
            *list(map(lambda p: (p[1], p), agents())),
            always_trigger_onselect=True)
        self.delay_getter = self.create_selection_menu(
            None,
            *[(str(time) + "ms", time) for time in [100, 500, 1000, 10, 50]])

    def make_button(self, text, callback):
        b = Button(self.options_frame, text=text)
        b.pack(side="left")
        b.config(command=callback)

    def setup_buttons(self):
        self.make_button("Prepare", self.update_all)
        self.make_button("Run", self.start)
        self.make_button("Stop", self.stop)
        self.make_button("Step", self.step)
        self.make_button("Clear Log", self.log_clear)

    def send_user_command(self, ignore=None):
        self.agent.is_alive = True
        self.agent.send_user_command(self.command_text.get())
        self.start()
        self.command_text.delete(0, 'end')

    def start_main_loop(self):
        self.root.mainloop()

    def append_log(self, text, end="\r\n"):
        self.log.configure(state="normal")
        self.log.insert("end", str(text) + end)
        self.log.see(END)
        self.log.configure(state="disabled")

    def log_clear(self):
        self.log.configure(state="normal")
        self.log.replace("0.0", END, "")
        self.log.configure(state="disabled")

    def refresh_tile(self, x, y):
        if PLATFORM_WINDOWS:
            state = self.vacuum_env.world[x][y]
            new_state =  WORLD_COLOR_CLEAN  if state == ENV_CLEAN\
                    else WORLD_COLOR_DIRTY  if state == ENV_DIRTY\
                    else WORLD_COLOR_GOLD   if state == ENV_GOLD\
                    else WORLD_COLOR_WALL

            # Apply color to tile (if necessary)
            if new_state != self.grid[x][y].cget("bg"):
                self.grid[x][y].configure(bg=new_state)
        else:
            new_image = self.images[self.vacuum_env.world[x][y]]
            if new_image != self.grid[x][y].cget("image"):
                self.grid[x][y].configure(image=new_image)

    def refresh(self):
        for x in range(self.vacuum_env.env_x):
            for y in range(self.vacuum_env.env_y):
                self.refresh_tile(x, y)
        self.draw_agent()

    def step(self):
        """
        Run one step in environment simulation.
        This automatically refreshes tiles.
        """
        self.vacuum_env.step()
        self.refresh()

    def start(self):
        if self.is_running:
            #self.append_log("Already running")
            return
        #self.append_log("Starting...")
        self.is_running = True
        self.run()

    def run(self):
        if self.is_running:
            self.step()
            self.root.after(self.delay_getter(),
                            self.run)  # Trigger a timer for next call

    def stop(self):
        if self.is_running:
            self.append_log("Stopped")
        self.is_running = False

    def make_env_frame(self):
        """
        Create the grid layout representing the state of the vacuum environment

        :return: None
        """

        width, height = STANDARD_ENV_DIMS
        previous_width, previous_height = (self.previous_dims or (-1, -1))

        if (width != previous_width
                or height != previous_height) and self.grid:
            self.grid[self.marked_agent_pos[0]][
                self.marked_agent_pos[1]].configure(image=self.blank_img)

        padx = 5 if width > 15 else 8
        pady = 2 if height > 15 else 4

        def make_callback(x, y):
            """
            Create a callback function for the given coordinate

            :param x: X-coordinate
            :param y: Y-coordinate
            :return: Callback function for the given coordinate
            """
            return lambda: self.grid_click_callback(x, y)

        def make_button(x, y, container_frame):
            """
            Shorthand for creating a button in the tile grid

            :param x: X-coordinate of button
            :param y: Y-coordinate of button
            :param container_frame: Frame to hold button
            :return: Reference to button
            """
            nonlocal padx
            nonlocal pady

            btn = Button(container_frame,
                         text="",
                         height=self.agent_btn_dims,
                         width=self.agent_btn_dims,
                         padx=padx,
                         pady=pady,
                         image=self.blank_img)
            btn.pack(side="right")
            btn.config(command=make_callback(x, y))
            return btn

        # Create an unpopulated button ref grid (filled with None for debug purposes)
        grid = [[None for _ in range(height)] for _ in range(width)]

        frame_pad = 0 if height > 30 else 8 * (30 - height)
        if self.grid is None:
            frame = Frame(self.host_frame, pady=frame_pad, padx=0)

            for y in range(height - 1, -1, -1):
                row_frame = Frame(frame)
                for x in range(width - 1, -1, -1):
                    grid[x][y] = make_button(x, y, row_frame)
                row_frame.pack(side="bottom")

            frame.pack(side="bottom")

            self.grid_frame = frame
        else:
            # Optimization to hopefully be a bit nicer on GC (if nothing else)
            for y in range(height - 1, -1, -1):
                rel_y = height - 1 - y
                row_frame = Frame(
                    self.grid_frame
                ) if rel_y >= previous_height else self.grid[0][previous_height
                                                                - 1 -
                                                                rel_y].master
                for x in range(width - 1, -1, -1):
                    rel_x = width - 1 - x
                    grid[x][y] = self.grid[previous_width - 1 - rel_x][
                        previous_height - 1 -
                        rel_y] if rel_x < previous_width and rel_y < previous_height else make_button(
                            x, y, row_frame)

                    if rel_x < previous_width and rel_y < previous_height:
                        grid[x][y].configure(padx=padx, pady=pady)
                        grid[x][y].config(command=make_callback(x, y))

                row_frame.pack(side="bottom")

            for y in range(previous_height):
                if previous_height - y > height:
                    self.grid[0][y].master.pack_forget()
                    continue

                for x in range(previous_width):
                    if previous_width - x > width:
                        self.grid[x][y].pack_forget()

            self.grid_frame.configure(pady=frame_pad, width=frame_pad)
            self.grid_frame.pack(side="bottom")

        # Update grid
        self.grid = grid
        self.previous_dims = (width, height)
        self.draw_agent()

    def draw_agent(self):
        self.grid[self.marked_agent_pos[0]][
            self.marked_agent_pos[1]].configure(image=self.blank_img)
        self.grid[self.agent.location[0]][self.agent.location[1]].configure(
            image=self.agent_img[self.agent.facing])
        self.marked_agent_pos = self.agent.location
        self.marked_agent_rot = self.agent.facing

    def update_all(self, force=False):
        """
        Trigger a full refresh. This recreates the environment, agent and grid, as well as updates tile colours.

        :param force: Force update.
        :return: None
        """

        if self.vacuum_env is not None or force:
            # Ensure we stop the agent
            if self.is_running:
                self.stop()
            self.create_sim()
            self.make_env_frame()
            self.refresh()

    def grid_click_callback(self, x, y):
        """
        Callback to manually mark a tile as clean, dirty or a wall. Outer walls cannot be changed.
        Tile at coordinate (1, 1) cannot be a wall; only clean or dirty since this is where agents are spawned.

        :param x: X-coordinate of tile
        :param y: Y-coordinate of tile
        :return: None
        """
        w, h = self.grid_dims_getter()
        current = self.vacuum_env.world[x][y]
        if x != 0 and x != w - 1 and y != 0 and y != h - 1:
            self.vacuum_env.world[x][y] = ENV_DIRTY if current == ENV_WALL or (
                x == 1 and y == 1 and current == ENV_CLEAN
            ) else ENV_CLEAN if current == ENV_DIRTY else ENV_WALL
            self.refresh_tile(x, y)

    def create_selection_menu(self,
                              cb_on_select,
                              *opts,
                              always_trigger_onselect=False,
                              no_destructure=False,
                              pass_selection_to_callback=False):
        """
        Quick way of creating a drop-down menu with a set of options and selection callbacks.

        :param cb_on_select: Menu item selection event callback
        :param opts: Menu options. These should be a list of two-element tuples where the first item is the label and the second is the corresponding value
        :param always_trigger_onselect: Whether the selection callback should be triggered even if an already-selected item was selected
        :param no_destructure: Whether option values should be destructured into the arguments of the callback
        :param pass_selection_to_callback: Whether or not to pass the selected value to the selection callback function
        :return: Getter function for the currently selected `value` (not label)
        """

        options_dict = dict()

        selection_active = StringVar(self.root)
        selection_previous = StringVar(self.root)

        for (key, value) in opts:
            options_dict[key] = value

        menu = OptionMenu(self.options_frame, selection_active,
                          *options_dict.keys())

        def on_select(*args):
            """
            Callback function for when a menu item is selected

            :param args: Ignored arguments. Just contains the modified variable
            :return: None
            """
            # Check if a previously un-selected item was selected (or if the event should be processed anyway)
            if selection_active.get() != selection_previous.get(
            ) or always_trigger_onselect:
                selection_previous.set(selection_active.get())

                # Call callback if one was specified
                if cb_on_select:
                    if pass_selection_to_callback:
                        # Attempt to destructure parameter as much as possible
                        # This is just a lazy way of passing sets of arguments in less LOC
                        if (not no_destructure) and dir(
                                options_dict[selection_active.get(
                                )]).__contains__("__iter__"):
                            if type(options_dict[
                                    selection_active.get()]) is dict:
                                cb_on_select(
                                    **options_dict[selection_active.get()])
                            else:
                                cb_on_select(
                                    *(options_dict[selection_active.get()]))
                        else:
                            cb_on_select(options_dict[selection_active.get()])
                    else:
                        cb_on_select()

        # Set a callback for when variable changes value
        selection_active.trace("w", on_select)

        # Pack menu if a side as packed, else assume packing will be done elsewhere
        menu.pack(side="left")

        # Select a menu option. This also triggers an initial callback
        selection_active.set(opts[0][0])

        # Return a getter function to the active *value* (not key)
        return lambda: options_dict[selection_active.get()]

    def get_agent(self):
        file_name, agent_class_name = self.agent_getter(
        )  # this is (file, name)
        return make_agent(file_name, agent_class_name, self.append_log)

    def create_sim(self):
        """
        Create environment and agent and add agent to environment
        """
        self.vacuum_env = VacuumEnvironment(*STANDARD_ENV_DIMS,
                                            self.dirt_bias_getter(),
                                            self.wall_bias_getter(),
                                            self.gold_bias_getter(),
                                            self.seed_getter())
        self.agent = self.get_agent()
        self.vacuum_env.add_thing(self.agent, DEFAULT_AGENT_LOCATION)
        recon = self.recon_getter()
        self.vacuum_env.prep_agent(self.agent, recon)
示例#36
0
class ConcordanceSearchView(object):
    _BACKGROUND_COLOUR = "#FFF"  # white

    # Colour of highlighted results
    _HIGHLIGHT_WORD_COLOUR = "#F00"  # red
    _HIGHLIGHT_WORD_TAG = "HL_WRD_TAG"

    _HIGHLIGHT_LABEL_COLOUR = "#C0C0C0"  # dark grey
    _HIGHLIGHT_LABEL_TAG = "HL_LBL_TAG"

    # Percentage of text left of the scrollbar position
    _FRACTION_LEFT_TEXT = 0.30

    def __init__(self):
        self.queue = q.Queue()
        self.model = ConcordanceSearchModel(self.queue)
        self.top = Tk()
        self._init_top(self.top)
        self._init_menubar()
        self._init_widgets(self.top)
        self.load_corpus(self.model.DEFAULT_CORPUS)
        self.after = self.top.after(POLL_INTERVAL, self._poll)

    def _init_top(self, top):
        top.geometry("950x680+50+50")
        top.title("NLTK Concordance Search")
        top.bind("<Control-q>", self.destroy)
        top.protocol("WM_DELETE_WINDOW", self.destroy)
        top.minsize(950, 680)

    def _init_widgets(self, parent):
        self.main_frame = Frame(
            parent, dict(background=self._BACKGROUND_COLOUR, padx=1, pady=1, border=1)
        )
        self._init_corpus_select(self.main_frame)
        self._init_query_box(self.main_frame)
        self._init_results_box(self.main_frame)
        self._init_paging(self.main_frame)
        self._init_status(self.main_frame)
        self.main_frame.pack(fill="both", expand=True)

    def _init_menubar(self):
        self._result_size = IntVar(self.top)
        self._cntx_bf_len = IntVar(self.top)
        self._cntx_af_len = IntVar(self.top)
        menubar = Menu(self.top)

        filemenu = Menu(menubar, tearoff=0, borderwidth=0)
        filemenu.add_command(
            label="Exit", underline=1, command=self.destroy, accelerator="Ctrl-q"
        )
        menubar.add_cascade(label="File", underline=0, menu=filemenu)

        editmenu = Menu(menubar, tearoff=0)
        rescntmenu = Menu(editmenu, tearoff=0)
        rescntmenu.add_radiobutton(
            label="20",
            variable=self._result_size,
            underline=0,
            value=20,
            command=self.set_result_size,
        )
        rescntmenu.add_radiobutton(
            label="50",
            variable=self._result_size,
            underline=0,
            value=50,
            command=self.set_result_size,
        )
        rescntmenu.add_radiobutton(
            label="100",
            variable=self._result_size,
            underline=0,
            value=100,
            command=self.set_result_size,
        )
        rescntmenu.invoke(1)
        editmenu.add_cascade(label="Result Count", underline=0, menu=rescntmenu)

        cntxmenu = Menu(editmenu, tearoff=0)
        cntxbfmenu = Menu(cntxmenu, tearoff=0)
        cntxbfmenu.add_radiobutton(
            label="60 characters",
            variable=self._cntx_bf_len,
            underline=0,
            value=60,
            command=self.set_cntx_bf_len,
        )
        cntxbfmenu.add_radiobutton(
            label="80 characters",
            variable=self._cntx_bf_len,
            underline=0,
            value=80,
            command=self.set_cntx_bf_len,
        )
        cntxbfmenu.add_radiobutton(
            label="100 characters",
            variable=self._cntx_bf_len,
            underline=0,
            value=100,
            command=self.set_cntx_bf_len,
        )
        cntxbfmenu.invoke(1)
        cntxmenu.add_cascade(label="Before", underline=0, menu=cntxbfmenu)

        cntxafmenu = Menu(cntxmenu, tearoff=0)
        cntxafmenu.add_radiobutton(
            label="70 characters",
            variable=self._cntx_af_len,
            underline=0,
            value=70,
            command=self.set_cntx_af_len,
        )
        cntxafmenu.add_radiobutton(
            label="90 characters",
            variable=self._cntx_af_len,
            underline=0,
            value=90,
            command=self.set_cntx_af_len,
        )
        cntxafmenu.add_radiobutton(
            label="110 characters",
            variable=self._cntx_af_len,
            underline=0,
            value=110,
            command=self.set_cntx_af_len,
        )
        cntxafmenu.invoke(1)
        cntxmenu.add_cascade(label="After", underline=0, menu=cntxafmenu)

        editmenu.add_cascade(label="Context", underline=0, menu=cntxmenu)

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

        self.top.config(menu=menubar)

    def set_result_size(self, **kwargs):
        self.model.result_count = self._result_size.get()

    def set_cntx_af_len(self, **kwargs):
        self._char_after = self._cntx_af_len.get()

    def set_cntx_bf_len(self, **kwargs):
        self._char_before = self._cntx_bf_len.get()

    def _init_corpus_select(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        self.var = StringVar(innerframe)
        self.var.set(self.model.DEFAULT_CORPUS)
        Label(
            innerframe,
            justify=LEFT,
            text=" Corpus: ",
            background=self._BACKGROUND_COLOUR,
            padx=2,
            pady=1,
            border=0,
        ).pack(side="left")

        other_corpora = list(self.model.CORPORA.keys()).remove(
            self.model.DEFAULT_CORPUS
        )
        om = OptionMenu(
            innerframe,
            self.var,
            self.model.DEFAULT_CORPUS,
            command=self.corpus_selected,
            *self.model.non_default_corpora()
        )
        om["borderwidth"] = 0
        om["highlightthickness"] = 1
        om.pack(side="left")
        innerframe.pack(side="top", fill="x", anchor="n")

    def _init_status(self, parent):
        self.status = Label(
            parent,
            justify=LEFT,
            relief=SUNKEN,
            background=self._BACKGROUND_COLOUR,
            border=0,
            padx=1,
            pady=0,
        )
        self.status.pack(side="top", anchor="sw")

    def _init_query_box(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        another = Frame(innerframe, background=self._BACKGROUND_COLOUR)
        self.query_box = Entry(another, width=60)
        self.query_box.pack(side="left", fill="x", pady=25, anchor="center")
        self.search_button = Button(
            another,
            text="Search",
            command=self.search,
            borderwidth=1,
            highlightthickness=1,
        )
        self.search_button.pack(side="left", fill="x", pady=25, anchor="center")
        self.query_box.bind("<KeyPress-Return>", self.search_enter_keypress_handler)
        another.pack()
        innerframe.pack(side="top", fill="x", anchor="n")

    def search_enter_keypress_handler(self, *event):
        self.search()

    def _init_results_box(self, parent):
        innerframe = Frame(parent)
        i1 = Frame(innerframe)
        i2 = Frame(innerframe)
        vscrollbar = Scrollbar(i1, borderwidth=1)
        hscrollbar = Scrollbar(i2, borderwidth=1, orient="horiz")
        self.results_box = Text(
            i1,
            font=Font(family="courier", size="16"),
            state="disabled",
            borderwidth=1,
            yscrollcommand=vscrollbar.set,
            xscrollcommand=hscrollbar.set,
            wrap="none",
            width="40",
            height="20",
            exportselection=1,
        )
        self.results_box.pack(side="left", fill="both", expand=True)
        self.results_box.tag_config(
            self._HIGHLIGHT_WORD_TAG, foreground=self._HIGHLIGHT_WORD_COLOUR
        )
        self.results_box.tag_config(
            self._HIGHLIGHT_LABEL_TAG, foreground=self._HIGHLIGHT_LABEL_COLOUR
        )
        vscrollbar.pack(side="left", fill="y", anchor="e")
        vscrollbar.config(command=self.results_box.yview)
        hscrollbar.pack(side="left", fill="x", expand=True, anchor="w")
        hscrollbar.config(command=self.results_box.xview)
        # there is no other way of avoiding the overlap of scrollbars while using pack layout manager!!!
        Label(i2, text="   ", background=self._BACKGROUND_COLOUR).pack(
            side="left", anchor="e"
        )
        i1.pack(side="top", fill="both", expand=True, anchor="n")
        i2.pack(side="bottom", fill="x", anchor="s")
        innerframe.pack(side="top", fill="both", expand=True)

    def _init_paging(self, parent):
        innerframe = Frame(parent, background=self._BACKGROUND_COLOUR)
        self.prev = prev = Button(
            innerframe,
            text="Previous",
            command=self.previous,
            width="10",
            borderwidth=1,
            highlightthickness=1,
            state="disabled",
        )
        prev.pack(side="left", anchor="center")
        self.next = next = Button(
            innerframe,
            text="Next",
            command=self.__next__,
            width="10",
            borderwidth=1,
            highlightthickness=1,
            state="disabled",
        )
        next.pack(side="right", anchor="center")
        innerframe.pack(side="top", fill="y")
        self.current_page = 0

    def previous(self):
        self.clear_results_box()
        self.freeze_editable()
        self.model.prev(self.current_page - 1)

    def __next__(self):
        self.clear_results_box()
        self.freeze_editable()
        self.model.next(self.current_page + 1)

    def about(self, *e):
        ABOUT = "NLTK Concordance Search Demo\n"
        TITLE = "About: NLTK Concordance Search Demo"
        try:
            from tkinter.messagebox import Message

            Message(message=ABOUT, title=TITLE, parent=self.main_frame).show()
        except:
            ShowText(self.top, TITLE, ABOUT)

    def _bind_event_handlers(self):
        self.top.bind(CORPUS_LOADED_EVENT, self.handle_corpus_loaded)
        self.top.bind(SEARCH_TERMINATED_EVENT, self.handle_search_terminated)
        self.top.bind(SEARCH_ERROR_EVENT, self.handle_search_error)
        self.top.bind(ERROR_LOADING_CORPUS_EVENT, self.handle_error_loading_corpus)

    def _poll(self):
        try:
            event = self.queue.get(block=False)
        except q.Empty:
            pass
        else:
            if event == CORPUS_LOADED_EVENT:
                self.handle_corpus_loaded(event)
            elif event == SEARCH_TERMINATED_EVENT:
                self.handle_search_terminated(event)
            elif event == SEARCH_ERROR_EVENT:
                self.handle_search_error(event)
            elif event == ERROR_LOADING_CORPUS_EVENT:
                self.handle_error_loading_corpus(event)
        self.after = self.top.after(POLL_INTERVAL, self._poll)

    def handle_error_loading_corpus(self, event):
        self.status["text"] = "Error in loading " + self.var.get()
        self.unfreeze_editable()
        self.clear_all()
        self.freeze_editable()

    def handle_corpus_loaded(self, event):
        self.status["text"] = self.var.get() + " is loaded"
        self.unfreeze_editable()
        self.clear_all()
        self.query_box.focus_set()

    def handle_search_terminated(self, event):
        # todo: refactor the model such that it is less state sensitive
        results = self.model.get_results()
        self.write_results(results)
        self.status["text"] = ""
        if len(results) == 0:
            self.status["text"] = "No results found for " + self.model.query
        else:
            self.current_page = self.model.last_requested_page
        self.unfreeze_editable()
        self.results_box.xview_moveto(self._FRACTION_LEFT_TEXT)

    def handle_search_error(self, event):
        self.status["text"] = "Error in query " + self.model.query
        self.unfreeze_editable()

    def corpus_selected(self, *args):
        new_selection = self.var.get()
        self.load_corpus(new_selection)

    def load_corpus(self, selection):
        if self.model.selected_corpus != selection:
            self.status["text"] = "Loading " + selection + "..."
            self.freeze_editable()
            self.model.load_corpus(selection)

    def search(self):
        self.current_page = 0
        self.clear_results_box()
        self.model.reset_results()
        query = self.query_box.get()
        if len(query.strip()) == 0:
            return
        self.status["text"] = "Searching for " + query
        self.freeze_editable()
        self.model.search(query, self.current_page + 1)

    def write_results(self, results):
        self.results_box["state"] = "normal"
        row = 1
        for each in results:
            sent, pos1, pos2 = each[0].strip(), each[1], each[2]
            if len(sent) != 0:
                if pos1 < self._char_before:
                    sent, pos1, pos2 = self.pad(sent, pos1, pos2)
                sentence = sent[pos1 - self._char_before : pos1 + self._char_after]
                if not row == len(results):
                    sentence += "\n"
                self.results_box.insert(str(row) + ".0", sentence)
                word_markers, label_markers = self.words_and_labels(sent, pos1, pos2)
                for marker in word_markers:
                    self.results_box.tag_add(
                        self._HIGHLIGHT_WORD_TAG,
                        str(row) + "." + str(marker[0]),
                        str(row) + "." + str(marker[1]),
                    )
                for marker in label_markers:
                    self.results_box.tag_add(
                        self._HIGHLIGHT_LABEL_TAG,
                        str(row) + "." + str(marker[0]),
                        str(row) + "." + str(marker[1]),
                    )
                row += 1
        self.results_box["state"] = "disabled"

    def words_and_labels(self, sentence, pos1, pos2):
        search_exp = sentence[pos1:pos2]
        words, labels = [], []
        labeled_words = search_exp.split(" ")
        index = 0
        for each in labeled_words:
            if each == "":
                index += 1
            else:
                word, label = each.split("/")
                words.append(
                    (self._char_before + index, self._char_before + index + len(word))
                )
                index += len(word) + 1
                labels.append(
                    (self._char_before + index, self._char_before + index + len(label))
                )
                index += len(label)
            index += 1
        return words, labels

    def pad(self, sent, hstart, hend):
        if hstart >= self._char_before:
            return sent, hstart, hend
        d = self._char_before - hstart
        sent = "".join([" "] * d) + sent
        return sent, hstart + d, hend + d

    def destroy(self, *e):
        if self.top is None:
            return
        self.top.after_cancel(self.after)
        self.top.destroy()
        self.top = None

    def clear_all(self):
        self.query_box.delete(0, END)
        self.model.reset_query()
        self.clear_results_box()

    def clear_results_box(self):
        self.results_box["state"] = "normal"
        self.results_box.delete("1.0", END)
        self.results_box["state"] = "disabled"

    def freeze_editable(self):
        self.query_box["state"] = "disabled"
        self.search_button["state"] = "disabled"
        self.prev["state"] = "disabled"
        self.next["state"] = "disabled"

    def unfreeze_editable(self):
        self.query_box["state"] = "normal"
        self.search_button["state"] = "normal"
        self.set_paging_button_states()

    def set_paging_button_states(self):
        if self.current_page == 0 or self.current_page == 1:
            self.prev["state"] = "disabled"
        else:
            self.prev["state"] = "normal"
        if self.model.has_more_pages(self.current_page):
            self.next["state"] = "normal"
        else:
            self.next["state"] = "disabled"

    def fire_event(self, event):
        # Firing an event so that rendering of widgets happen in the mainloop thread
        self.top.event_generate(event, when="tail")

    def mainloop(self, *args, **kwargs):
        if in_idle():
            return
        self.top.mainloop(*args, **kwargs)
class AnalysisOptionsInputForm(Frame):

    # Initialize the GUI
    def __init__(self, root, prospectorFormObject):
        Frame.__init__(self, root)
        root.title("Choose Read Stat and Demultiplexing options")
        self.parent = root

        # keep a handle on the parent object. I can specify configuration using this handle
        self.prospectorFormObject = prospectorFormObject

        # To define the exit behavior.  Save and exit.
        self.parent.protocol('WM_DELETE_WINDOW', self.saveOptions)

        # Define the return behavior.  Same as "close window" etc
        root.bind('<Return>', self.returnFunction)

        # This window should not be resizeable. I guess.
        self.parent.resizable(width=False, height=False)

        #Standard Inputs widths for the form elements
        self.formInputWidth = 10
        self.labelInputWidth = 60

        self.makeAnalysisGeneralOptionsFrame()
        self.makeDemultiplexInstructionsFrame()
        self.makeDemultiplexOptionsFrame()
        self.makeLengthAndQualityFilterFrame()
        self.makeSaveOptionsFrame()
        self.makeBlastInstructionsFrame()
        self.makeBlastOptionsFrame()

        self.loadOptions()

    def makeAnalysisGeneralOptionsFrame(self):
        self.generalOptionsFrame = Frame(self)
        # TODO: Add parameters for # of threads.
        # Other generic parameters?

        # TODO Should I worry  about the # of ram the user is using? I have never ran into the limit before.
        self.generalOptionsFrame.pack()

    def makeDemultiplexInstructionsFrame(self):
        self.instructionsFrame = Frame(self)
        self.instructionText = StringVar()
        self.instructionText.set(
            '\nOptions: Read statistics and Demultiplexing.\n')
        Label(self.instructionsFrame,
              width=85,
              height=3,
              textvariable=self.instructionText).pack()
        self.instructionsFrame.pack()

    def makeDemultiplexOptionsFrame(self):
        # Demultiplexing
        self.demultiplexOptionFrame = Frame(self)
        self.demultiplexInstrStringVar = StringVar()
        self.demultiplexInstrStringVar.set(
            'Demultiplex the reads, using 96x barcode kit:')
        self.demultiplexInstrLabel = Label(
            self.demultiplexOptionFrame,
            width=self.labelInputWidth,
            height=1,
            textvariable=self.demultiplexInstrStringVar).grid(row=0, column=0)
        self.chooseDemultiplexIntVar = IntVar()
        #self.chooseDemultiplexIntVar.set(2)
        Radiobutton(self.demultiplexOptionFrame,
                    text="Yes",
                    variable=self.chooseDemultiplexIntVar,
                    value=1).grid(row=0, column=1)
        Radiobutton(self.demultiplexOptionFrame,
                    text="No",
                    variable=self.chooseDemultiplexIntVar,
                    value=2).grid(row=0, column=2)
        self.demultiplexOptionFrame.pack()

    def makeLengthAndQualityFilterFrame(self):
        # Length and Quality
        self.lengthParamsFrame = Frame(self)
        self.lengthParamsStringVar = StringVar()
        self.lengthParamsStringVar.set('Minimum & Maximum Read Length:')
        self.demultiplexInstrLabel = Label(
            self.lengthParamsFrame,
            width=self.labelInputWidth,
            height=1,
            textvariable=self.lengthParamsStringVar).grid(row=0, column=0)
        self.inputMinLength = StringVar()
        self.inputMinLengthEntry = Entry(
            self.lengthParamsFrame,
            width=self.formInputWidth,
            textvariable=self.inputMinLength).grid(row=0, column=1)
        self.inputMaxLength = StringVar()
        self.inputMaxLengthEntry = Entry(
            self.lengthParamsFrame,
            width=self.formInputWidth,
            textvariable=self.inputMaxLength).grid(row=0, column=2)
        self.qualityParamsStringVar = StringVar()
        self.qualityParamsStringVar.set('Minimum & Maximum Quality (Q-Score):')
        self.demultiplexInstrLabel = Label(
            self.lengthParamsFrame,
            width=self.labelInputWidth,
            height=1,
            textvariable=self.qualityParamsStringVar).grid(row=1, column=0)
        self.inputMinQuality = StringVar()
        self.inputMinLengthEntry = Entry(
            self.lengthParamsFrame,
            width=self.formInputWidth,
            textvariable=self.inputMinQuality).grid(row=1, column=1)
        self.inputMaxQuality = StringVar()
        self.inputMaxLengthEntry = Entry(
            self.lengthParamsFrame,
            width=self.formInputWidth,
            textvariable=self.inputMaxQuality).grid(row=1, column=2)
        self.lengthParamsFrame.pack()

    def makeBlastInstructionsFrame(self):
        self.blastInstructionsFrame = Frame(self)
        self.blastInstructionText = StringVar()
        self.blastInstructionText.set(
            '\nOptions: Blast Sorting.\n' +
            'What genes do you want to sort against?\n' +
            '(More genes = more analysis time)')
        Label(self.blastInstructionsFrame,
              width=85,
              height=5,
              textvariable=self.blastInstructionText).pack()
        self.blastInstructionsFrame.pack()

    def makeBlastOptionsFrame(self):
        self.blastOptionsFrame = Frame(self)

        # TODO: I have been adding genes as we use them. Should I add more?
        # HLA Allele Analysis makes these reference files now.
        # I can add DMA DMB DOA DOB DPA1 DPB1 DQA1 DQB1 DRA DRB1 DRB3 DRB4 DRB5
        # And E and F

        self.geneAIntVar = IntVar()
        Checkbutton(self.blastOptionsFrame,
                    text="HLA-A",
                    variable=self.geneAIntVar).grid(row=0, sticky=W)

        self.geneBIntVar = IntVar()
        Checkbutton(self.blastOptionsFrame,
                    text="HLA-B",
                    variable=self.geneBIntVar).grid(row=1, sticky=W)

        self.geneCIntVar = IntVar()
        Checkbutton(self.blastOptionsFrame,
                    text="HLA-C",
                    variable=self.geneCIntVar).grid(row=2, sticky=W)

        self.geneEIntVar = IntVar()
        Checkbutton(self.blastOptionsFrame,
                    text="HLA-E",
                    variable=self.geneEIntVar).grid(row=3, sticky=W)

        self.geneDRAIntVar = IntVar()
        Checkbutton(self.blastOptionsFrame,
                    text="HLA-DRA",
                    variable=self.geneDRAIntVar).grid(row=4, sticky=W)

        self.geneDQA1IntVar = IntVar()
        Checkbutton(self.blastOptionsFrame,
                    text="HLA-DQA1",
                    variable=self.geneDQA1IntVar).grid(row=5, sticky=W)

        self.geneDQB1IntVar = IntVar()
        Checkbutton(self.blastOptionsFrame,
                    text="HLA-DQB1",
                    variable=self.geneDQB1IntVar).grid(row=6, sticky=W)

        self.geneDRB1IntVar = IntVar()
        Checkbutton(self.blastOptionsFrame,
                    text="HLA-DRB1",
                    variable=self.geneDRB1IntVar).grid(row=7, sticky=W)

        self.blastOptionsFrame.pack()

    def makeSaveOptionsFrame(self):
        # Make a frame for the save options button.
        self.saveOptionsFrame = Frame(self)
        Button(self.saveOptionsFrame,
               text='Save Options',
               command=self.saveOptions).grid(row=0, column=0)
        self.saveOptionsFrame.pack()

    # I needed a function for the return keypress to latch onto.
    # It is just a wrapper for the saveOptions method.
    def returnFunction(self, event):
        self.saveOptions()

    def loadOptions(self):
        # Read the configuration file.
        loadConfigurationFile()

        #TODO: Number of threads. Configure this.

        if getConfigurationValue('demultiplex_reads') is not None:
            self.chooseDemultiplexIntVar.set(
                int(getConfigurationValue('demultiplex_reads')))

        if getConfigurationValue('min_length') is not None:
            self.inputMinLength.set(getConfigurationValue('min_length'))
        if getConfigurationValue('max_length') is not None:
            self.inputMaxLength.set(getConfigurationValue('max_length'))

        if getConfigurationValue('min_quality') is not None:
            self.inputMinQuality.set(getConfigurationValue('min_quality'))
        if getConfigurationValue('max_quality') is not None:
            self.inputMaxQuality.set(getConfigurationValue('max_quality'))

        if getConfigurationValue('analyze_hla_a') is not None:
            self.geneAIntVar.set(getConfigurationValue('analyze_hla_a'))
        if getConfigurationValue('analyze_hla_b') is not None:
            self.geneBIntVar.set(getConfigurationValue('analyze_hla_b'))
        if getConfigurationValue('analyze_hla_c') is not None:
            self.geneCIntVar.set(getConfigurationValue('analyze_hla_c'))
        if getConfigurationValue('analyze_hla_e') is not None:
            self.geneEIntVar.set(getConfigurationValue('analyze_hla_e'))

        if getConfigurationValue('analyze_hla_dra') is not None:
            self.geneDRAIntVar.set(getConfigurationValue('analyze_hla_dra'))
        if getConfigurationValue('analyze_hla_dqa1') is not None:
            self.geneDQA1IntVar.set(getConfigurationValue('analyze_hla_dqa1'))
        if getConfigurationValue('analyze_hla_dqb1') is not None:
            self.geneDQB1IntVar.set(getConfigurationValue('analyze_hla_dqb1'))
        if getConfigurationValue('analyze_hla_drb1') is not None:
            self.geneDRB1IntVar.set(getConfigurationValue('analyze_hla_drb1'))

    def saveOptions(self):

        print('Saving Options')

        #TODO: Number of threads. Configure this.

        assignConfigurationValue('demultiplex_reads',
                                 str(self.chooseDemultiplexIntVar.get()))

        assignConfigurationValue('min_length', self.inputMinLength.get())
        assignConfigurationValue('max_length', self.inputMaxLength.get())

        assignConfigurationValue('min_quality', self.inputMinQuality.get())
        assignConfigurationValue('max_quality', self.inputMaxQuality.get())

        assignConfigurationValue('analyze_hla_a', (self.geneAIntVar.get()))
        assignConfigurationValue('analyze_hla_b', (self.geneBIntVar.get()))
        assignConfigurationValue('analyze_hla_c', (self.geneCIntVar.get()))
        assignConfigurationValue('analyze_hla_e', (self.geneEIntVar.get()))
        assignConfigurationValue('analyze_hla_dra', (self.geneDRAIntVar.get()))
        assignConfigurationValue('analyze_hla_dqa1',
                                 (self.geneDQA1IntVar.get()))
        assignConfigurationValue('analyze_hla_dqb1',
                                 (self.geneDQB1IntVar.get()))
        assignConfigurationValue('analyze_hla_drb1',
                                 (self.geneDRB1IntVar.get()))

        writeConfigurationFile()
        self.parent.destroy()
示例#38
0
def create_voting_screen(player_names,
                         vote_function,
                         player_message="Time to vote",
                         reset_at_beggining=True,
                         reset_at_end=True):
    '''voting screen populating function'''
    global just_voted, title_label_refernce
    while window_open is False:
        pass

    player_window = WindowSingleton.get_instance().window
    if reset_at_beggining is False:
        just_voted = False
        player_window.title(player_message)
        title_label_refernce.configure(text=player_message)
        while (not just_voted) and window_open:
            pass
        if reset_at_end is True:
            WindowSingleton.reset_instance()
        return
    WindowSingleton.reset_instance()
    background_color = ANTI_FLASH_WHITE
    player_window.configure(background=background_color)
    player_window.title(player_message)
    logs_frame = Frame(player_window)
    if player_message != "Chose a game to play!":
        logs_frame.pack(side=LEFT)

    scrollbar = Scrollbar(player_window)
    scrollbar.pack(side=RIGHT)
    logs_label = Listbox(logs_frame,
                         height=60,
                         width=30,
                         font=("bold", 10),
                         background=BROWN,
                         foreground=ANTI_FLASH_WHITE,
                         yscrollcommand=scrollbar.set)
    for individual_log in log_history:
        logs_label.insert(END, individual_log)
    logs_label.pack(side=TOP)

    game_frame = Frame(player_window)
    game_frame.configure(background=background_color)
    game_frame.pack(side=LEFT)

    title_frame = Frame(game_frame)
    title_frame.configure(background=background_color)
    title_frame.pack()
    text_label = Label(title_frame,
                       text=player_message,
                       width=40,
                       font=("bold", 20),
                       bg=UMBER,
                       fg=ANTI_FLASH_WHITE,
                       anchor="w",
                       justify="center")
    title_label_refernce = text_label
    text_label.pack()

    top_frame = Frame(game_frame)
    top_frame.pack()
    top_frame.configure(background=background_color)

    bottom_frame = Frame(game_frame)
    bottom_frame.pack()
    bottom_frame.configure(background=background_color)

    number_of_players = len(player_names)
    for i in range(0, number_of_players):
        player_name = player_names[i]
        if i < number_of_players / 2:
            curr_frame = top_frame
        else:
            curr_frame = bottom_frame
        vote_button = Button(curr_frame,
                             bg=SPICY_MIX,
                             font=("Courier", 10),
                             fg=ANTI_FLASH_WHITE,
                             height=20,
                             width=17,
                             text=player_name,
                             command=vote_function(player_name))
        vote_button.pack(side=LEFT)

    just_voted = False
    while (not just_voted) and window_open:
        pass

    if reset_at_end is True:
        WindowSingleton.reset_instance()
示例#39
0
文件: run.py 项目: oagutu/aotd
"""App entry point"""

# System imports
from tkinter import (Frame, LEFT, X)

from front import main

if __name__ == "__main__":
    window = main.MainWindow()
    root = window.create_window()
    root.configure(bg="black")

    publication_frame = Frame(root, bg="red")
    publication_frame.pack(side=LEFT)

    article_frame = Frame(root)
    article_frame.pack()

    root.mainloop()
示例#40
0
		booking.connect((serverIP,7777))
		booking.send(str(chr(i+65)+str(j)).encode())
		ack=booking.recv(1024)
		print(ack)
		booking.close()
	except timeout:
		server=bully()
		if server: 
			test = socket(AF_INET, SOCK_DGRAM)
			test.connect(("8.8.8.8", 80))
			th.start_new_thread(serve,(test.getsockname()[0],))
			test.close()	
    '''


#UI code
root = Tk()
root.title("Book Ticket Online")
root.geometry("720x360")
f = Frame(root)
b = []
for i in range(0, 4):
    for j in range(0, 7):
        b.append(
            Button(f,
                   text=chr(i + 65) + str(j),
                   height=2,
                   width=6,
                   command=lambda: book(i, j)).grid(row=i, column=j))
f.pack()
root.mainloop()
示例#41
0
    multiprocessing.freeze_support()
    #Super cool json file
    with open('./json_settings.json', 'r') as settingsfile:
        jsondata = settingsfile.read()
        loadedjsonsettings = json.loads(jsondata)
        settingsfile.close()

    #beutiful gui
    root = Tk()
    root.title('Open_Clicker ' + loadedjsonsettings['about']['displayVersion'])
    root.config(bg='#0F151D')
    root.resizable(0, 0)
    root.tk.call('wm', 'iconphoto', root._w, PhotoImage(file='./favicon.png'))
    #high quality 10/10 button shit for the modern skid
    buttonFrame = Frame(root, bg='#0F151D')
    buttonFrame.pack(side=LEFT)
    #Start/Stop button
    toggleButtonImage = PhotoImage(file='./icons/general/play.png')
    toggleButton = Button(
        buttonFrame,
        command=lambda: toggle(lcbbuttonvar.get(), mcbbuttonvar.get(),
                               rcbbuttonvar.get(), keyboardentry.get(),
                               cpsvalue.get(), loadedjsonsettings),
        image=toggleButtonImage,
        bg='#2B2D31',
        fg='#C96C00',
        activebackground='#1E1B15',
        activeforeground='#066D9F')
    toggleButton.image = toggleButtonImage
    toggleButton.pack(anchor=E)
    toggleButtonTTP = toolTip.CreateToolTip(
示例#42
0
文件: 2.07.py 项目: joyfish/Programas
}

theme_choice = StringVar()
theme_choice.set('Default')
for k in sorted(color_schemes):
    themes_menu.add_radiobutton(label=k, variable=theme_choice)
menu_bar.add_cascade(label='View', menu=view_menu)

about_menu = Menu(menu_bar, tearoff=0)
about_menu.add_command(label='About')
about_menu.add_command(label='Help')
menu_bar.add_cascade(label='About',  menu=about_menu)
root.config(menu=menu_bar)

shortcut_bar = Frame(root,  height=25, background='light sea green')
shortcut_bar.pack(expand='no', fill='x')
line_number_bar = Text(root, width=4, padx=3, takefocus=0,  border=0,
                       background='khaki', state='disabled',  wrap='none')
line_number_bar.pack(side='left',  fill='y')

content_text = Text(root, wrap='word', undo=1)
content_text.pack(expand='yes', fill='both')
scroll_bar = Scrollbar(content_text)
content_text.configure(yscrollcommand=scroll_bar.set)
scroll_bar.config(command=content_text.yview)
scroll_bar.pack(side='right', fill='y')

# Shortcut key bindings for this iteration
content_text.bind('<Control-N>', new_file)
content_text.bind('<Control-n>', new_file)
content_text.bind('<Control-O>', open_file)
示例#43
0
class Session:
    def __init__(self, name, server):
        self.name = name
        self.server = server
        self.clients = {}
        self.scoreboard = {}
        self.quiz_state = 0
        self.is_accepting_answer = False

    def add_client(self, conn, name):
        if name in self.clients:
            conn.send(
                '{ "data": false, "error": "Nama panggilan sudah dipakai oleh pengguna lain" }'
                .encode("UTF-8"))
            conn.close()
        else:
            self.clients[conn] = name
            self.scoreboard[name] = 0
            conn.send('{ "data": true, "error": null }'.encode("UTF-8"))

    def __get_status(self):
        switcher = {
            0: ("Open", "DodgerBlue2", "Start"),
            1: ("Running", "limegreen", "Running"),
            2: ("Finished", "red2", "Delete")
        }

        return switcher.get(self.quiz_state)

    def bind_gui(self, master):
        self.session_frame = Frame(master)
        self.session_frame.pack()

        name_label = Label(self.session_frame, text=self.name)
        name_label.grid(row=0, column=0, sticky="NSEW")

        self.session_frame.grid_columnconfigure(0, weight=5)

        status_frame = Frame(self.session_frame)
        status_frame.grid(row=0, column=1, sticky="NSEW")

        self.session_frame.grid_columnconfigure(0, weight=2)

        label = self.__get_status()

        self.status_label = Label(status_frame, text=label[0], fg=label[1])
        self.status_button = Button(status_frame,
                                    text=label[2],
                                    command=self.__start_quiz)

        detail_button = Button(status_frame,
                               text="Status",
                               command=self.__show_status)

        self.status_label.grid(row=0, column=0, sticky="NSEW")
        self.status_button.grid(row=0, column=1, sticky="NSEW")
        detail_button.grid(row=0, column=2, sticky="NSEW")

    def __start_quiz(self):
        self.quiz_state = 1

        label = self.__get_status()

        self.status_label["text"] = label[0]
        self.status_label["fg"] = label[1]
        self.status_button["text"] = label[2]
        self.status_button["fg"] = "light grey"
        self.status_button["state"] = "disabled"

        if len(self.clients) > 0:
            quiz_loop = Thread(target=self.__begin_quiz_loop, daemon=True)
            quiz_loop.start()
        else:
            self.stop_quiz()

    def __begin_quiz_loop(self):
        self.number = 0

        for conn in self.clients:
            try:
                conn.send(
                    '{ "data": "Kuis akan dimulai dalam waktu 5 detik, selamat berjuang!", "error": null }'
                    .encode("UTF-8"))
            except ConnectionResetError:
                name = self.clients[conn]
                del self.clients[conn]
                del self.scoreboard[name]

                if len(self.clients) == 0:
                    self.stop_quiz()
                    return

        sleep(5)

        self.session_soal = deepcopy(file_soal)

        shuffle(self.session_soal)

        while self.number < len(self.session_soal):
            self.is_accepting_answer = True
            self.answers = {}  # string-tuple = (jawaban, waktu)

            soal = {
                "soal": self.session_soal[self.number]["soal"] +
                " (anda memiliki waktu 1 menit untuk menjawab)",
                "pilihan": self.session_soal[self.number]["pilihan"]
            }

            payload = self.__serialize({
                "data": self.__serialize(soal),
                "error": None
            }).encode("UTF-8")

            listeners = []

            for conn in self.clients:
                try:
                    conn.send(payload)

                    listener = Thread(target=self.__ask_answer,
                                      args=(conn, ),
                                      daemon=True)
                    listeners.append(listener)
                except ConnectionResetError:
                    del self.clients[conn]
                    continue

            for listener in listeners:
                listener.start()

            sleep(60)  # Ubah waktu disini

            self.is_accepting_answer = False

            self.__update_scoreboard()
            self.__post_scoreboard()

            sleep(3)

            self.number += 1

        result = "Kuis Selesai!\nPemenang dari kuis adalah: "
        winner = []

        for client in self.scoreboard:
            winner.append((client, self.scoreboard[client]))

        winner = sorted(winner, key=lambda x: x[1], reverse=True)

        result += winner[0][0] + " dengan skor " + str(winner[0][1])

        payload = self.__serialize({
            "data": result,
            "error": None
        }).encode("UTF-8")

        for conn in self.clients:
            conn.send(payload)
            conn.close()

        self.stop_quiz()

    def __ask_answer(self, conn):
        while self.is_accepting_answer == True:
            try:
                answer = conn.recv(1024).decode("UTF-8")

                client = self.clients[conn]

                if client in self.answers:
                    conn.send(
                        '{ "data": null, "error": "Anda telah menjawab untuk soal ini!" }'
                        .encode("UTF-8"))

                self.answers[client] = (answer, time())
                break
            except ConnectionResetError:
                del self.clients[conn]
                continue

    def __update_scoreboard(self):
        answers = []

        for answer in self.answers:
            answers.append(
                (self.answers[answer][0], self.answers[answer][1], answer))

        answers = sorted(answers, key=lambda x: x[1])

        cur_score = len(self.clients)

        for answer in answers:
            if answer[0].lower() == self.session_soal[
                    self.number]["jawaban"].lower():
                self.scoreboard[answer[2]] += cur_score
                cur_score -= 1

    def __post_scoreboard(self):
        announcements = "Jawaban benar: " + self.session_soal[
            self.number]["jawaban"] + ".\n"
        announcements += "Score saat ini:"

        winner = []

        for client in self.scoreboard:
            winner.append((client, self.scoreboard[client]))

        winner = sorted(winner, key=lambda x: x[1], reverse=True)

        for client in winner:
            announcements += "\n" + client[0] + ": " + str(client[1])

        announcements += "\nSoal selanjutnya dikirim dalam 3 detik lagi"
        announcements = announcements

        for conn in self.clients:
            try:
                verdict = ""
                name = self.clients[conn]

                if name in self.answers:
                    verdict += "Jawaban anda: " + self.answers[name][0]
                else:
                    verdict += "Anda tidak menjawab dalam batas waktu yang telah ditentukan"

                verdict += "\n"

                payload = self.__serialize({
                    "data": verdict + announcements,
                    "error": None
                }).encode("UTF-8")

                conn.send(payload)
            except ConnectionResetError:
                del self.clients[conn]
                continue

    def stop_quiz(self):
        self.quiz_state = 2

        label = self.__get_status()
        self.status_label["text"] = label[0]
        self.status_label["fg"] = label[1]
        self.status_button["text"] = label[2]
        self.status_button["state"] = "normal"
        self.status_button["fg"] = "black"
        self.status_button["command"] = self.__delete_session

    def __delete_session(self):
        self.session_frame.destroy()
        self.server.delete_session(self.name)

    def __serialize(self, obj):
        return dumps(obj, indent=4)

    def __show_status(self):
        label = "Jumlah klien yang terhubung dengan sesi ini: " + str(
            len(self.scoreboard))

        if len(self.scoreboard) > 0:
            label += "\n"
            label = "Daftar klien beserta skor saat ini:"

            for client in self.scoreboard:
                label += "\n" + client + ": " + str(self.scoreboard[client])

        messagebox.showinfo("Current Status", label)
    def make_env_frame(self):
        """
        Create the grid layout representing the state of the vacuum environment

        :return: None
        """

        width, height = STANDARD_ENV_DIMS
        previous_width, previous_height = (self.previous_dims or (-1, -1))

        if (width != previous_width
                or height != previous_height) and self.grid:
            self.grid[self.marked_agent_pos[0]][
                self.marked_agent_pos[1]].configure(image=self.blank_img)

        padx = 5 if width > 15 else 8
        pady = 2 if height > 15 else 4

        def make_callback(x, y):
            """
            Create a callback function for the given coordinate

            :param x: X-coordinate
            :param y: Y-coordinate
            :return: Callback function for the given coordinate
            """
            return lambda: self.grid_click_callback(x, y)

        def make_button(x, y, container_frame):
            """
            Shorthand for creating a button in the tile grid

            :param x: X-coordinate of button
            :param y: Y-coordinate of button
            :param container_frame: Frame to hold button
            :return: Reference to button
            """
            nonlocal padx
            nonlocal pady

            btn = Button(container_frame,
                         text="",
                         height=self.agent_btn_dims,
                         width=self.agent_btn_dims,
                         padx=padx,
                         pady=pady,
                         image=self.blank_img)
            btn.pack(side="right")
            btn.config(command=make_callback(x, y))
            return btn

        # Create an unpopulated button ref grid (filled with None for debug purposes)
        grid = [[None for _ in range(height)] for _ in range(width)]

        frame_pad = 0 if height > 30 else 8 * (30 - height)
        if self.grid is None:
            frame = Frame(self.host_frame, pady=frame_pad, padx=0)

            for y in range(height - 1, -1, -1):
                row_frame = Frame(frame)
                for x in range(width - 1, -1, -1):
                    grid[x][y] = make_button(x, y, row_frame)
                row_frame.pack(side="bottom")

            frame.pack(side="bottom")

            self.grid_frame = frame
        else:
            # Optimization to hopefully be a bit nicer on GC (if nothing else)
            for y in range(height - 1, -1, -1):
                rel_y = height - 1 - y
                row_frame = Frame(
                    self.grid_frame
                ) if rel_y >= previous_height else self.grid[0][previous_height
                                                                - 1 -
                                                                rel_y].master
                for x in range(width - 1, -1, -1):
                    rel_x = width - 1 - x
                    grid[x][y] = self.grid[previous_width - 1 - rel_x][
                        previous_height - 1 -
                        rel_y] if rel_x < previous_width and rel_y < previous_height else make_button(
                            x, y, row_frame)

                    if rel_x < previous_width and rel_y < previous_height:
                        grid[x][y].configure(padx=padx, pady=pady)
                        grid[x][y].config(command=make_callback(x, y))

                row_frame.pack(side="bottom")

            for y in range(previous_height):
                if previous_height - y > height:
                    self.grid[0][y].master.pack_forget()
                    continue

                for x in range(previous_width):
                    if previous_width - x > width:
                        self.grid[x][y].pack_forget()

            self.grid_frame.configure(pady=frame_pad, width=frame_pad)
            self.grid_frame.pack(side="bottom")

        # Update grid
        self.grid = grid
        self.previous_dims = (width, height)
        self.draw_agent()
示例#45
0
    imglabel.pack()
    root.pack()


def show(event):
    img = ImageTk.PhotoImage(Image.open("A:/mario.jpg"))
    imglabel = Label(root, image=img)
    imglabel.pack()
    root.pack()


#ento image kanabadatle kani empty di paste avtundi root window lo paste avtundaa elaaa switch control cheyu chupi naku\

root = Tk()
fr = Frame(root)
fr.pack()
b0 = Button(fr, text="choose image")
b0.bind("<Button-1>", ask)
b1 = Button(fr, text="brightness")
b1.bind("<Button-1>", brighten)
b2 = Button(fr, text="split")
b2.bind("<Button-1>", split)
b3 = Button(fr, text="sharpness")
b3.bind("<Button-1>", sharpen)
b4 = Button(fr, text="contrast")
b4.bind("<Button-1>", contrast)
b5 = Button(fr, text="show output image")
b5.bind("<Button-1>", show)
b0.pack(side=TOP)
b1.pack(side=TOP)
b2.pack(side=TOP)
示例#46
0

root = Tk()
root.title("Text Editor")
root.geometry("1000x700")

# Text Editor Label
Label(root, text="Text Editor", font="Helvetica 20 bold").pack(pady=20)

# Main Text Box
editor = Text(root, height=30, width=100, bd=3)
editor.pack()

# Button Frame
button_frame = Frame(root)
button_frame.pack()

# Open Button
Button(
    button_frame,
    text="OPEN",
    height=2,
    width=15,
    font="Helvetica 15 bold",
    bd=3,
    command=open_func,
).pack(pady=20, padx=20, side=LEFT)

# Save Button
Button(
    button_frame,
示例#47
0
class App(Tk):
    def __init__(self, testing_mode, *args, **kwargs):
        Tk.__init__(self, *args, **kwargs)

        icon_filepath = 'img/budget.ico'
        self.wm_iconbitmap(icon_filepath)
        self.iconbitmap(default=icon_filepath)

        self.resizable(False, False)

        self.set_style()

        self.testing_mode = testing_mode
        self.title("Budget Transaction Processor")
        self.backend = Backend()

        self.container = Frame(self)
        self.container.pack(side="top",
                            fill="both",
                            expand=True,
                            padx=15,
                            pady=15)
        self.container.grid_rowconfigure(0, weight=1)
        self.container.grid_columnconfigure(0, weight=1)

        self.home_frame = HomeFrame(self.container, self)
        self.home_frame.grid(row=0, column=0, sticky='nsew')

        self.file_select_frame = FileSelectFrame(self.container, self)
        self.file_select_frame.grid(row=0, column=0, sticky='nsew')

        self.create_menubar()

        self.file_select_frame.tkraise()

        if self.testing_mode:
            self.file_select_frame.submit()

    def show_frame(self, name):
        if name == 'home':
            self.home_frame.tkraise()
        elif name == 'file_select':
            self.file_select_frame.tkraise()
        else:
            raise ValueError("name must be either 'home' or 'file_select'")

    def create_menubar(self):
        self.menu = Menu(self)
        self.config(menu=self.menu)

        self.file_menu = Menu(self.menu, tearoff=0)

        self.file_menu.add_command(
            label="Select File Screen",
            command=lambda: self.show_frame('file_select'))
        self.file_menu.add_separator()
        self.file_menu.add_command(label="Exit",
                                   command=lambda: self.destroy())

        self.menu.add_cascade(label="File", menu=self.file_menu)

        self.insert_menu = Menu(self.menu, tearoff=0)
        self.insert_menu.add_command(
            label="Category",
            command=lambda: CategoryEntryPopup(self.home_frame))
        self.insert_menu.add_command(
            label="Vendor", command=lambda: VendorEntryPopup(self.home_frame))

        self.menu.add_cascade(label="Insert", menu=self.insert_menu)

    def set_style(self):
        style = ttk.Style(self)
        style.configure('.', font=('Arial', 9))  # set root style font
        style.configure(
            'DropDown.TCombobox',
            borderwidth=1,
            bordercolor='black',
            relief='solid',
        )
        style.configure('DropDown.TCombobox.textarea', font=('Arial', 9))
        style.configure('DropDown.TCombobox.border', relief='solid')
        style.configure('TableRow.TLabel',
                        height=1,
                        bd=1,
                        relief="solid",
                        background="white",
                        highlightbackground="blue",
                        padding=(1, 1, 0, 0))
        style.configure('TableHeader.TLabel',
                        foreground="white",
                        background="dark slate gray",
                        bd=1,
                        relief="flat",
                        padding=(1, 1, 0, 0))
        style.configure('Submit.TButton', font=('Arial', 8))
        style.configure('Title.TLabel',
                        font=("Arial", 18),
                        padding=(0, 15),
                        anchor='center')
        style.configure('SelectFile.TButton', font=('Arial', 8), padding=5)
from tkinter import Tk, Frame, Menu
from tkinter import TOP, RIGHT, LEFT, X, Y, BOTH

# Frame https://www.tutorialspoint.com/python/tk_frame.htm
# pack() https://www.tutorialspoint.com/python/tk_pack.htm
# Menu https://www.tutorialspoint.com/python/tk_menu.htm

# Init
root = Tk()
root.title("Layout Example")
root.geometry('800x640')

# Layout
header = Frame(root, height=100, bg='red')
header.pack(side=TOP, fill=X)
appcontent = Frame(root, bg='blue')
appcontent.pack(fill=BOTH, expand=1)

# Extended Layout

right = Frame(appcontent, bg='green')
right.pack(side=RIGHT, fill=BOTH, expand=1)

middle = Frame(appcontent, bg='yellow')
middle.pack(side=RIGHT, fill=BOTH, expand=1)

left = Frame(appcontent, bg='purple')
left.pack(side=RIGHT, fill=BOTH, expand=1)

示例#49
0
class Wall(object):
    MIN_RED = MIN_GREEN = MIN_BLUE = 0x0
    MAX_RED = MAX_GREEN = MAX_BLUE = 0xFF

    PIXEL_WIDTH = 50

    def __init__(self, width, height):
        #width and height default defined in run.py; can override w/ args
        self.width = width
        self.height = height
        self._tk_init()
        #Create list object of pixels: (0, 0, 0) tuple for total number of pixels
        self.pixels = [(0, 0, 0) for i in range(self.width * self.height)]

    def _tk_init(self):
        self.root = Tk()
        #Create new window (canvas), title it with dimensions
        self.root.title("ColorWall %d x %d" % (self.width, self.height))
        #Can it be resized? Two arguments for height & width.  False = No; True = Yes
        self.root.resizable(False, False)
        self.frame = Frame(self.root, bd=5, relief=SUNKEN)
        self.frame.pack()

        self.canvas = Canvas(self.frame,
                             width=self.PIXEL_WIDTH * self.width,
                             height=self.PIXEL_WIDTH * self.height,
                             bd=0,
                             highlightthickness=0)
        self.canvas.pack()
        self.root.update()

    def set_pixel(self, x, y, hsv):
        self.pixels[self.width * y + x] = hsv

    def get_pixel(self, x, y):
        return self.pixels[self.width * y + x]

    def draw(self):
        self.canvas.delete(ALL)
        for x in range(len(self.pixels)):
            x_0 = (x % self.width) * self.PIXEL_WIDTH
            #Fix floor division for Python 3
            y_0 = (x // self.width) * self.PIXEL_WIDTH
            x_1 = x_0 + self.PIXEL_WIDTH
            y_1 = y_0 + self.PIXEL_WIDTH
            hue = "#%02x%02x%02x" % self._get_rgb(self.pixels[x])
            self.canvas.create_rectangle(x_0, y_0, x_1, y_1, fill=hue)
        self.canvas.update()

    def clear(self):
        for i in range(self.width * self.height):
            self.pixels[i] = (0, 0, 0)

    def _hsv_to_rgb(self, hsv):
        rgb = colorsys.hsv_to_rgb(*hsv)
        red = self.MAX_RED * rgb[0]
        green = self.MAX_GREEN * rgb[1]
        blue = self.MAX_BLUE * rgb[2]
        return (red, green, blue)

    def _get_rgb(self, hsv):
        red, green, blue = self._hsv_to_rgb(hsv)
        red = int(float(red) / (self.MAX_RED - self.MIN_RED) * 0xFF)
        green = int(float(green) / (self.MAX_GREEN - self.MIN_GREEN) * 0xFF)
        blue = int(float(blue) / (self.MAX_BLUE - self.MIN_BLUE) * 0xFF)
        return (red, green, blue)
示例#50
0

menubar = Menu(top)
menubar.add_command(label="生成封面", command=runCover)
menubar.add_command(label="转码", command=runChange)
top['menu'] = menubar
'''
布局
'''
frmLeft = LabelFrame(width=300, height=100, text='状态', labelanchor='nw')
frmSelectPath = Frame(width=100, height=100)
frmTop = Frame(width=100, height=100)
frmBottom = LabelFrame(width=500, text='下载列表', height=400)

frmLeft.pack(side='left', fill='y', padx='5', pady='5')
frmSelectPath.pack(side='top', fill='x', padx='5', pady='5')
frmTop.pack(side='top', fill='x', padx='5', pady='5')
frmBottom.pack(side='right', fill=BOTH, expand='yes', padx='5', pady='5')
'''
控件
'''
clupValue = IntVar()
clipButton = Checkbutton(frmLeft,
                         text="剪贴板",
                         onvalue=1,
                         offvalue=0,
                         height=1,
                         variable=clupValue)
clipButton.pack(side='top', expand='no', fill=None)

示例#51
0
menu = Menu(root)
root.config(menu = menu)

fileMenu = Menu(menu)
menu.add_cascade(label = "File", menu = fileMenu)
fileMenu.add_command(label = "New", command = newFile)
fileMenu.add_command(label = "Open", command = openFile)
fileMenu.add_command(label = "Save", command = saveFile)
fileMenu.add_command(label = "Find", command = findInFile)
fileMenu.add_separator()
fileMenu.add_command(label = "Exit", command = exitEditor)

helpMenu = Menu(menu)
menu.add_cascade(label = "Help", menu = helpMenu)
helpMenu.add_command(label = "Help", command = help)
helpMenu.add_command(label = "About", command = about)

actionMenu = Menu(menu)
menu.add_cascade(label = "Action", menu = actionMenu)
actionMenu.add_command(label = "Shell", command = shell)
actionMenu.add_command(label = "Run", command = runFile)


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



# Keep window open
root.mainloop()
示例#52
0
class Game():
    def __init__(self, root):
        self.root = root
        self.gameFrame = ""
        self.interFrame = ""

    def initGameCallBack(self):

        if isinstance(self.interFrame, Frame):
            self.interFrame.destroy()
            self.timer.destroy()
            self.counter.destroy()

        if isinstance(self.gameFrame, Frame):
            self.gameFrame.destroy()

        storage = Storage()
        self.mines = storage.get("mines")
        h = storage.get("height")
        w = storage.get("width")
        self.isGameStarted = False

        self.tiles = [[j for j in range(w)] for i in range(h)]
        self.bombs = set()
        self.bombsPrediction = set()
        self.tilesAmount = w * h

        self.board = Board(w, h, self.mines)

        self.root.bind_class('Label', '<Button-1>', self.openTileEvent)
        self.root.bind_class('Label', '<Button-2>', self.flagTileEvent)
        self.root.bind('<KeyPress>', self.keyboardEvent)

        self.code = ""
        self.__createFrame()
        self.__initInterface()

    def showAll(self):
        for i in self.tiles:
            for tile in i:
                tile.open()
                if not isinstance(tile, Bomb) and tile.getFlagLevel() != 0:
                    tile.setImage("../res/images/bombmisflagged.gif")

    def showAllMines(self):
        print("showing...")
        for tile in self.bombs:
            tile.shade()

    def __initInterface(self):
        self.interFrame = Frame(self.root, bg="green")
        self.timer = MyTimer(self.interFrame)
        self.timer.pack(side=LEFT, padx=20)

        self.counter = Counter(self.interFrame)
        self.counter.setVal(self.mines)
        self.counter.pack(side=RIGHT, padx=20)
        self.interFrame.pack()

    def __createFrame(self):

        tileFactory = TileFactory()
        self.gameFrame = Frame(self.root)

        for row in range(self.board.getWidth()):
            for column in range(self.board.getHeight()):
                point = Point(row, column)
                type = self.board(point)
                tile = tileFactory.getTile(self.gameFrame, type, point)
                if isinstance(tile, Bomb):
                    self.bombs.add(tile)

                self.tiles[row][column] = tile
                tile.grid(row=row, column=column)
        self.gameFrame.pack(side=BOTTOM, padx=20, pady=20)

    def startGame(self):
        if not self.isGameStarted:
            self.timer.start()
            self.isGameStarted = True

    def keyboardEvent(self, event):
        self.startGame()
        self.code = self.code + event.char
        if self.code == "xyzzy":
            self.showAllMines()
        Timer(2, self.bounce).start()

    def bounce(self):
        self.code = ""

    def flagTileEvent(self, event):

        self.startGame()

        if event.widget.getFlagLevel() == 1:
            self.counter.down()
            self.newPrediction(event.widget)

        elif event.widget.getFlagLevel() == 2:
            self.counter.up()
            self.bombsPrediction.remove(event.widget)

    def openTileEvent(self, event):

        self.startGame()

        if self.tilesAmount == self.mines:
            self.gameOver("wygrałeś")

        tile = event.widget
        point = tile.point

        if not tile.isActive():
            return

        tile.disActive()

        if isinstance(tile, Bomb) and tile.getFlagLevel() == 0:
            self.root.after(10, tile.boom)
            self.gameOver("przegrałeś")

        if isinstance(tile, Number) and tile.getValue() == 0:
            zeros = self.board.getZerosFrom(point)
            for zero in zeros:
                tmpTile = self.tiles[zero[0]][zero[1]]
                tmpTile.open()
                tmpTile.disActive()
                self.tilesAmount -= 1
            self.board.clearZeros()
        else:
            self.tilesAmount -= 1
            self.checkTilesAmount()

    def checkTilesAmount(self):
        if self.tilesAmount == self.mines:
            self.gameOver("wygrałeś")

    def newPrediction(self, bomb):
        self.bombsPrediction.add(bomb)
        newSet = self.bombs - self.bombsPrediction
        if not len(newSet):
            self.gameOver("wygrałeś")

    def gameOver(self, text):
        self.timer.stop()
        self.showAll()
        messagebox.showerror("koniec Gry", text)
class UserMenu():
    """
    Wrapper class for tkinter user menu.
    """
    def _parse_solvers(self):
        """
        Based on selected items fetch `solvers` and `puzzle_size`.
        """

        self._is_destroyed = False
        self._puzzle_data = dict()

        solvers = []
        if self._tk_var_wastar_dynamic.get():
            solvers.append(Solvers.WASTAR_D)
        if self._tk_var_wastar_static.get():
            solvers.append(Solvers.WASTAR_S)
        if self._tk_var_idastar.get():
            solvers.append(Solvers.IDASTAR)
        if self._tk_var_astar.get():
            solvers.append(Solvers.ASTAR)
        self._puzzle_data["solvers"] = solvers

        # fetching solvers
        if len(solvers) != 2:
            solvers_popup = Tk()
            solvers_popup.wm_title("!")

            tk_lbl_solvers = Label(solvers_popup,
                                   text="Select 2 algorithms",
                                   padx=PADDING_X,
                                   pady=PADDING_Y)
            tk_lbl_solvers.pack(side="top", anchor="center")
            tk_btn_solvers = Button(solvers_popup,
                                    text="OK",
                                    command=solvers_popup.destroy,
                                    padx=PADDING_X)
            tk_btn_solvers.pack()

            solvers_popup.mainloop()

        # fetching puzzle size
        if self._tk_var_puzzle_size.get() == 3:
            self._puzzle_data["size"] = 3
        elif self._tk_var_puzzle_size.get() == 4:
            self._puzzle_data["size"] = 4
        else:
            puzzle_size_popup = Tk()
            puzzle_size_popup.wm_title("!")

            tk_lbl_puzzle_size = Label(puzzle_size_popup,
                                       text="Select puzzle size",
                                       padx=PADDING_X,
                                       pady=PADDING_Y)
            tk_lbl_puzzle_size.pack(side="top", anchor="center")
            tk_btn_puzzle_size = Button(puzzle_size_popup,
                                        text="OK",
                                        command=puzzle_size_popup.destroy,
                                        padx=PADDING_X)
            tk_btn_puzzle_size.pack()

            puzzle_size_popup.mainloop()

        # if everything is selected, we close user window
        if len(solvers) == 2 and self._puzzle_data.get("size") is not None:
            if not self._is_destroyed:
                self._is_destroyed = True
                self._root.destroy()

    def _setup_cb(self):
        """Setup all checkboxes in the user menu."""
        cb_shared_params = {
            "onvalue": True,
            "offvalue": False,
            "padx": PADDING_X,
            "pady": PADDING_Y
        }
        self._tk_cb_wastar_dynamic = Checkbutton(
            self._tk_frame_cb,
            text="Dynamic weighted A*",
            variable=self._tk_var_wastar_dynamic,
            **cb_shared_params)
        self._tk_cb_wastar_dynamic.pack(side=TOP, anchor=W)
        self._tk_cb_wastar_static = Checkbutton(
            self._tk_frame_cb,
            text="Static weighted A*",
            variable=self._tk_var_wastar_static,
            **cb_shared_params)
        self._tk_cb_wastar_static.pack(side=TOP, anchor=W)
        self._tk_cb_idastar = Checkbutton(self._tk_frame_cb,
                                          text="Iterative deepening A*",
                                          variable=self._tk_var_idastar,
                                          **cb_shared_params)
        self._tk_cb_idastar.pack(side=TOP, anchor=W)
        self._tk_cb_astar = Checkbutton(self._tk_frame_cb,
                                        text="Standard A*",
                                        variable=self._tk_var_astar,
                                        **cb_shared_params)
        self._tk_cb_astar.pack(side=TOP, anchor=W)

    def _setup_rb(self):
        """Setup all radio buttons in the user menu."""
        rb_shared_params = {"padx": PADDING_X, "pady": PADDING_Y}
        self._tk_rb_3x3 = Radiobutton(self._tk_frame_rb,
                                      text="3x3",
                                      variable=self._tk_var_puzzle_size,
                                      value=3,
                                      **rb_shared_params)
        self._tk_rb_3x3.pack(side=TOP, anchor=W)
        self._tk_rb_4x4 = Radiobutton(self._tk_frame_rb,
                                      text="4x4",
                                      variable=self._tk_var_puzzle_size,
                                      value=4,
                                      **rb_shared_params)
        self._tk_rb_4x4.pack(side=TOP, anchor=W)

    def _setup_submit(self):
        self._tk_btn_submit = Button(self._tk_frame_btn,
                                     text="Submit",
                                     command=self._parse_solvers)
        self._tk_btn_submit.pack(side=TOP, anchor=CENTER)

    def __init__(self):
        """Tkinter constructor."""
        self._root = Tk()
        self._root.wm_title("Loyd Puzzle A* Solvers")

        path = os.path.join(IMAGES_PATH, "icon.png")
        self._root.iconphoto(True, PhotoImage(file=path))
        self._root.resizable(False, False)
        self._root.config(background="white")

        self._tk_frame_btn = Frame(self._root)

        # three separate containers for content of the menu
        self._tk_frame_btn.pack(side="bottom", fill="both", expand=False)
        self._tk_frame_cb = Frame(self._root)
        self._tk_frame_cb.pack(side="left", fill="both", expand=False)
        self._tk_frame_rb = Frame(self._root)
        self._tk_frame_rb.pack(side="right", fill="both", expand=False)

        # special tkinter variables that contains informations from checkboxes
        self._tk_var_wastar_dynamic = BooleanVar()
        self._tk_var_wastar_static = BooleanVar()
        self._tk_var_idastar = BooleanVar()
        self._tk_var_astar = BooleanVar()
        self._tk_var_puzzle_size = IntVar()

    def show(self):
        self._setup_rb()
        self._setup_cb()
        self._setup_submit()

        self._root.mainloop()
        self._puzzle_data = Namespace(**self._puzzle_data)

    def get_puzzle_data(self):
        return self._puzzle_data
示例#54
0
class Table:
    """
    A display widget for a table of values, based on a ``MultiListbox``
    widget.  For many purposes, ``Table`` can be treated as a
    list-of-lists.  E.g., table[i] is a list of the values for row i;
    and table.append(row) adds a new row with the given lits of
    values.  Individual cells can be accessed using table[i,j], which
    refers to the j-th column of the i-th row.  This can be used to
    both read and write values from the table.  E.g.:

        >>> table[i,j] = 'hello'

    The column (j) can be given either as an index number, or as a
    column name.  E.g., the following prints the value in the 3rd row
    for the 'First Name' column:

        >>> print(table[3, 'First Name'])
        John

    You can configure the colors for individual rows, columns, or
    cells using ``rowconfig()``, ``columnconfig()``, and ``itemconfig()``.
    The color configuration for each row will be preserved if the
    table is modified; however, when new rows are added, any color
    configurations that have been made for *columns* will not be
    applied to the new row.

    Note: Although ``Table`` acts like a widget in some ways (e.g., it
    defines ``grid()``, ``pack()``, and ``bind()``), it is not itself a
    widget; it just contains one.  This is because widgets need to
    define ``__getitem__()``, ``__setitem__()``, and ``__nonzero__()`` in
    a way that's incompatible with the fact that ``Table`` behaves as a
    list-of-lists.

    :ivar _mlb: The multi-column listbox used to display this table's data.
    :ivar _rows: A list-of-lists used to hold the cell values of this
        table.  Each element of _rows is a row value, i.e., a list of
        cell values, one for each column in the row.
    """
    def __init__(self,
                 master,
                 column_names,
                 rows=None,
                 column_weights=None,
                 scrollbar=True,
                 click_to_sort=True,
                 reprfunc=None,
                 cnf={},
                 **kw):
        """
        Construct a new Table widget.

        :type master: Tkinter.Widget
        :param master: The widget that should contain the new table.
        :type column_names: list(str)
        :param column_names: A list of names for the columns; these
            names will be used to create labels for each column;
            and can be used as an index when reading or writing
            cell values from the table.
        :type rows: list(list)
        :param rows: A list of row values used to initialze the table.
            Each row value should be a tuple of cell values, one for
            each column in the row.
        :type scrollbar: bool
        :param scrollbar: If true, then create a scrollbar for the
            new table widget.
        :type click_to_sort: bool
        :param click_to_sort: If true, then create bindings that will
            sort the table's rows by a given column's values if the
            user clicks on that colum's label.
        :type reprfunc: function
        :param reprfunc: If specified, then use this function to
            convert each table cell value to a string suitable for
            display.  ``reprfunc`` has the following signature:
            reprfunc(row_index, col_index, cell_value) -> str
            (Note that the column is specified by index, not by name.)
        :param cnf, kw: Configuration parameters for this widget's
            contained ``MultiListbox``.  See ``MultiListbox.__init__()``
            for details.
        """
        self._num_columns = len(column_names)
        self._reprfunc = reprfunc
        self._frame = Frame(master)

        self._column_name_to_index = dict(
            (c, i) for (i, c) in enumerate(column_names))

        # Make a copy of the rows & check that it's valid.
        if rows is None:
            self._rows = []
        else:
            self._rows = [[v for v in row] for row in rows]
        for row in self._rows:
            self._checkrow(row)

        # Create our multi-list box.
        self._mlb = MultiListbox(self._frame, column_names, column_weights,
                                 cnf, **kw)
        self._mlb.pack(side="left", expand=True, fill="both")

        # Optional scrollbar
        if scrollbar:
            sb = Scrollbar(self._frame,
                           orient="vertical",
                           command=self._mlb.yview)
            self._mlb.listboxes[0]["yscrollcommand"] = sb.set
            # for listbox in self._mlb.listboxes:
            #    listbox['yscrollcommand'] = sb.set
            sb.pack(side="right", fill="y")
            self._scrollbar = sb

        # Set up sorting
        self._sortkey = None
        if click_to_sort:
            for i, l in enumerate(self._mlb.column_labels):
                l.bind("<Button-1>", self._sort)

        # Fill in our multi-list box.
        self._fill_table()

    # /////////////////////////////////////////////////////////////////
    # { Widget-like Methods
    # /////////////////////////////////////////////////////////////////
    # These all just delegate to either our frame or our MLB.

    def pack(self, *args, **kwargs):
        """Position this table's main frame widget in its parent
        widget.  See ``Tkinter.Frame.pack()`` for more info."""
        self._frame.pack(*args, **kwargs)

    def grid(self, *args, **kwargs):
        """Position this table's main frame widget in its parent
        widget.  See ``Tkinter.Frame.grid()`` for more info."""
        self._frame.grid(*args, **kwargs)

    def focus(self):
        """Direct (keyboard) input foxus to this widget."""
        self._mlb.focus()

    def bind(self, sequence=None, func=None, add=None):
        """Add a binding to this table's main frame that will call
        ``func`` in response to the event sequence."""
        self._mlb.bind(sequence, func, add)

    def rowconfigure(self, row_index, cnf={}, **kw):
        """:see: ``MultiListbox.rowconfigure()``"""
        self._mlb.rowconfigure(row_index, cnf, **kw)

    def columnconfigure(self, col_index, cnf={}, **kw):
        """:see: ``MultiListbox.columnconfigure()``"""
        col_index = self.column_index(col_index)
        self._mlb.columnconfigure(col_index, cnf, **kw)

    def itemconfigure(self, row_index, col_index, cnf=None, **kw):
        """:see: ``MultiListbox.itemconfigure()``"""
        col_index = self.column_index(col_index)
        return self._mlb.itemconfigure(row_index, col_index, cnf, **kw)

    def bind_to_labels(self, sequence=None, func=None, add=None):
        """:see: ``MultiListbox.bind_to_labels()``"""
        return self._mlb.bind_to_labels(sequence, func, add)

    def bind_to_listboxes(self, sequence=None, func=None, add=None):
        """:see: ``MultiListbox.bind_to_listboxes()``"""
        return self._mlb.bind_to_listboxes(sequence, func, add)

    def bind_to_columns(self, sequence=None, func=None, add=None):
        """:see: ``MultiListbox.bind_to_columns()``"""
        return self._mlb.bind_to_columns(sequence, func, add)

    rowconfig = rowconfigure
    columnconfig = columnconfigure
    itemconfig = itemconfigure

    # /////////////////////////////////////////////////////////////////
    # { Table as list-of-lists
    # /////////////////////////////////////////////////////////////////

    def insert(self, row_index, rowvalue):
        """
        Insert a new row into the table, so that its row index will be
        ``row_index``.  If the table contains any rows whose row index
        is greater than or equal to ``row_index``, then they will be
        shifted down.

        :param rowvalue: A tuple of cell values, one for each column
            in the new row.
        """
        self._checkrow(rowvalue)
        self._rows.insert(row_index, rowvalue)
        if self._reprfunc is not None:
            rowvalue = [
                self._reprfunc(row_index, j, v)
                for (j, v) in enumerate(rowvalue)
            ]
        self._mlb.insert(row_index, rowvalue)
        if self._DEBUG:
            self._check_table_vs_mlb()

    def extend(self, rowvalues):
        """
        Add new rows at the end of the table.

        :param rowvalues: A list of row values used to initialze the
            table.  Each row value should be a tuple of cell values,
            one for each column in the row.
        """
        for rowvalue in rowvalues:
            self.append(rowvalue)
        if self._DEBUG:
            self._check_table_vs_mlb()

    def append(self, rowvalue):
        """
        Add a new row to the end of the table.

        :param rowvalue: A tuple of cell values, one for each column
            in the new row.
        """
        self.insert(len(self._rows), rowvalue)
        if self._DEBUG:
            self._check_table_vs_mlb()

    def clear(self):
        """
        Delete all rows in this table.
        """
        self._rows = []
        self._mlb.delete(0, "end")
        if self._DEBUG:
            self._check_table_vs_mlb()

    def __getitem__(self, index):
        """
        Return the value of a row or a cell in this table.  If
        ``index`` is an integer, then the row value for the ``index``th
        row.  This row value consists of a tuple of cell values, one
        for each column in the row.  If ``index`` is a tuple of two
        integers, ``(i,j)``, then return the value of the cell in the
        ``i``th row and the ``j``th column.
        """
        if isinstance(index, slice):
            raise ValueError("Slicing not supported")
        elif isinstance(index, tuple) and len(index) == 2:
            return self._rows[index[0]][self.column_index(index[1])]
        else:
            return tuple(self._rows[index])

    def __setitem__(self, index, val):
        """
        Replace the value of a row or a cell in this table with
        ``val``.

        If ``index`` is an integer, then ``val`` should be a row value
        (i.e., a tuple of cell values, one for each column).  In this
        case, the values of the ``index``th row of the table will be
        replaced with the values in ``val``.

        If ``index`` is a tuple of integers, ``(i,j)``, then replace the
        value of the cell in the ``i``th row and ``j``th column with
        ``val``.
        """
        if isinstance(index, slice):
            raise ValueError("Slicing not supported")

        # table[i,j] = val
        elif isinstance(index, tuple) and len(index) == 2:
            i, j = index[0], self.column_index(index[1])
            config_cookie = self._save_config_info([i])
            self._rows[i][j] = val
            if self._reprfunc is not None:
                val = self._reprfunc(i, j, val)
            self._mlb.listboxes[j].insert(i, val)
            self._mlb.listboxes[j].delete(i + 1)
            self._restore_config_info(config_cookie)

        # table[i] = val
        else:
            config_cookie = self._save_config_info([index])
            self._checkrow(val)
            self._rows[index] = list(val)
            if self._reprfunc is not None:
                val = [
                    self._reprfunc(index, j, v) for (j, v) in enumerate(val)
                ]
            self._mlb.insert(index, val)
            self._mlb.delete(index + 1)
            self._restore_config_info(config_cookie)

    def __delitem__(self, row_index):
        """
        Delete the ``row_index``th row from this table.
        """
        if isinstance(row_index, slice):
            raise ValueError("Slicing not supported")
        if isinstance(row_index, tuple) and len(row_index) == 2:
            raise ValueError("Cannot delete a single cell!")
        del self._rows[row_index]
        self._mlb.delete(row_index)
        if self._DEBUG:
            self._check_table_vs_mlb()

    def __len__(self):
        """
        :return: the number of rows in this table.
        """
        return len(self._rows)

    def _checkrow(self, rowvalue):
        """
        Helper function: check that a given row value has the correct
        number of elements; and if not, raise an exception.
        """
        if len(rowvalue) != self._num_columns:
            raise ValueError("Row %r has %d columns; expected %d" %
                             (rowvalue, len(rowvalue), self._num_columns))

    # /////////////////////////////////////////////////////////////////
    # Columns
    # /////////////////////////////////////////////////////////////////

    @property
    def column_names(self):
        """A list of the names of the columns in this table."""
        return self._mlb.column_names

    def column_index(self, i):
        """
        If ``i`` is a valid column index integer, then return it as is.
        Otherwise, check if ``i`` is used as the name for any column;
        if so, return that column's index.  Otherwise, raise a
        ``KeyError`` exception.
        """
        if isinstance(i, int) and 0 <= i < self._num_columns:
            return i
        else:
            # This raises a key error if the column is not found.
            return self._column_name_to_index[i]

    def hide_column(self, column_index):
        """:see: ``MultiListbox.hide_column()``"""
        self._mlb.hide_column(self.column_index(column_index))

    def show_column(self, column_index):
        """:see: ``MultiListbox.show_column()``"""
        self._mlb.show_column(self.column_index(column_index))

    # /////////////////////////////////////////////////////////////////
    # Selection
    # /////////////////////////////////////////////////////////////////

    def selected_row(self):
        """
        Return the index of the currently selected row, or None if
        no row is selected.  To get the row value itself, use
        ``table[table.selected_row()]``.
        """
        sel = self._mlb.curselection()
        if sel:
            return int(sel[0])
        else:
            return None

    def select(self, index=None, delta=None, see=True):
        """:see: ``MultiListbox.select()``"""
        self._mlb.select(index, delta, see)

    # /////////////////////////////////////////////////////////////////
    # Sorting
    # /////////////////////////////////////////////////////////////////

    def sort_by(self, column_index, order="toggle"):
        """
        Sort the rows in this table, using the specified column's
        values as a sort key.

        :param column_index: Specifies which column to sort, using
            either a column index (int) or a column's label name
            (str).

        :param order: Specifies whether to sort the values in
            ascending or descending order:

              - ``'ascending'``: Sort from least to greatest.
              - ``'descending'``: Sort from greatest to least.
              - ``'toggle'``: If the most recent call to ``sort_by()``
                sorted the table by the same column (``column_index``),
                then reverse the rows; otherwise sort in ascending
                order.
        """
        if order not in ("ascending", "descending", "toggle"):
            raise ValueError('sort_by(): order should be "ascending", '
                             '"descending", or "toggle".')
        column_index = self.column_index(column_index)
        config_cookie = self._save_config_info(index_by_id=True)

        # Sort the rows.
        if order == "toggle" and column_index == self._sortkey:
            self._rows.reverse()
        else:
            self._rows.sort(key=operator.itemgetter(column_index),
                            reverse=(order == "descending"))
            self._sortkey = column_index

        # Redraw the table.
        self._fill_table()
        self._restore_config_info(config_cookie, index_by_id=True, see=True)
        if self._DEBUG:
            self._check_table_vs_mlb()

    def _sort(self, event):
        """Event handler for clicking on a column label -- sort by
        that column."""
        column_index = event.widget.column_index

        # If they click on the far-left of far-right of a column's
        # label, then resize rather than sorting.
        if self._mlb._resize_column(event):
            return "continue"

        # Otherwise, sort.
        else:
            self.sort_by(column_index)
            return "continue"

    # /////////////////////////////////////////////////////////////////
    # { Table Drawing Helpers
    # /////////////////////////////////////////////////////////////////

    def _fill_table(self, save_config=True):
        """
        Re-draw the table from scratch, by clearing out the table's
        multi-column listbox; and then filling it in with values from
        ``self._rows``.  Note that any cell-, row-, or column-specific
        color configuration that has been done will be lost.  The
        selection will also be lost -- i.e., no row will be selected
        after this call completes.
        """
        self._mlb.delete(0, "end")
        for i, row in enumerate(self._rows):
            if self._reprfunc is not None:
                row = [self._reprfunc(i, j, v) for (j, v) in enumerate(row)]
            self._mlb.insert("end", row)

    def _get_itemconfig(self, r, c):
        return dict((k, self._mlb.itemconfig(r, c, k)[-1]) for k in (
            "foreground",
            "selectforeground",
            "background",
            "selectbackground",
        ))

    def _save_config_info(self, row_indices=None, index_by_id=False):
        """
        Return a 'cookie' containing information about which row is
        selected, and what color configurations have been applied.
        this information can the be re-applied to the table (after
        making modifications) using ``_restore_config_info()``.  Color
        configuration information will be saved for any rows in
        ``row_indices``, or in the entire table, if
        ``row_indices=None``.  If ``index_by_id=True``, the the cookie
        will associate rows with their configuration information based
        on the rows' python id.  This is useful when performing
        operations that re-arrange the rows (e.g. ``sort``).  If
        ``index_by_id=False``, then it is assumed that all rows will be
        in the same order when ``_restore_config_info()`` is called.
        """
        # Default value for row_indices is all rows.
        if row_indices is None:
            row_indices = list(range(len(self._rows)))

        # Look up our current selection.
        selection = self.selected_row()
        if index_by_id and selection is not None:
            selection = id(self._rows[selection])

        # Look up the color configuration info for each row.
        if index_by_id:
            config = dict((
                id(self._rows[r]),
                [self._get_itemconfig(r, c) for c in range(self._num_columns)],
            ) for r in row_indices)
        else:
            config = dict((
                r,
                [self._get_itemconfig(r, c) for c in range(self._num_columns)])
                          for r in row_indices)

        return selection, config

    def _restore_config_info(self, cookie, index_by_id=False, see=False):
        """
        Restore selection & color configuration information that was
        saved using ``_save_config_info``.
        """
        selection, config = cookie

        # Clear the selection.
        if selection is None:
            self._mlb.selection_clear(0, "end")

        # Restore selection & color config
        if index_by_id:
            for r, row in enumerate(self._rows):
                if id(row) in config:
                    for c in range(self._num_columns):
                        self._mlb.itemconfigure(r, c, config[id(row)][c])
                if id(row) == selection:
                    self._mlb.select(r, see=see)
        else:
            if selection is not None:
                self._mlb.select(selection, see=see)
            for r in config:
                for c in range(self._num_columns):
                    self._mlb.itemconfigure(r, c, config[r][c])

    # /////////////////////////////////////////////////////////////////
    # Debugging (Invariant Checker)
    # /////////////////////////////////////////////////////////////////

    _DEBUG = False
    """If true, then run ``_check_table_vs_mlb()`` after any operation
       that modifies the table."""

    def _check_table_vs_mlb(self):
        """
        Verify that the contents of the table's ``_rows`` variable match
        the contents of its multi-listbox (``_mlb``).  This is just
        included for debugging purposes, to make sure that the
        list-modifying operations are working correctly.
        """
        for col in self._mlb.listboxes:
            assert len(self) == col.size()
        for row in self:
            assert len(row) == self._num_columns
        assert self._num_columns == len(self._mlb.column_names)
        # assert self._column_names == self._mlb.column_names
        for i, row in enumerate(self):
            for j, cell in enumerate(row):
                if self._reprfunc is not None:
                    cell = self._reprfunc(i, j, cell)
                assert self._mlb.get(i)[j] == cell
示例#55
0
class Grid():
    def __init__(self, master):
        # Top menu
        self.menu = Frame(master)
        self.menu.pack(fill='both', expand=True)

        self.save_button = Button(master, text='Save', command=self.save_grid)
        self.save_button.pack(in_=self.menu, side='right')

        self.load_button = Button(master, text='Load', command=self.load_grid)
        self.load_button.pack(in_=self.menu, side='right')

        # Place the canvas
        self.canvas = Canvas(master,
                             width=MAP_CELL_SIZE * MAP_SIZE,
                             height=MAP_CELL_SIZE * MAP_SIZE)

        self.grid = [[Cell(self.canvas, row, col) for col in range(MAP_SIZE)]
                     for row in range(MAP_SIZE)]

        self.canvas.bind("<Button-1>", self.event_set_cell)
        self.canvas.bind("<B1-Motion>", self.event_set_cell)

        self.canvas.pack()

        # Tools
        self.tools = Frame(master)
        self.tools.pack(fill='both', expand=True)

        self.fill_button = Button(self.tools,
                                  text="Fill",
                                  command=self.fill_grid)
        self.fill_button.pack(side='left')

        types = list(list_draw_types())
        self.draw_type = StringVar(master)
        self.draw_type.set(DEFAULT_CELL_TYPE)
        self.dd_draw_type = OptionMenu(self.tools, self.draw_type,
                                       DEFAULT_CELL_TYPE, *types)
        self.dd_draw_type.pack(side='left')

        self.symetry = StringVar(master)
        self.symetry.set(SYMETRY[0])
        self.dd_symetry = OptionMenu(self.tools, self.symetry, SYMETRY[0],
                                     *SYMETRY)
        self.dd_symetry.pack(side='right')

        self.draw()

    def draw(self):
        for row in self.grid:
            for cell in row:
                cell.draw()

    #    ____     _ _
    #   / ___|___| | |___
    #  | |   / _ \ | / __|
    #  | |__|  __/ | \__ \
    #   \____\___|_|_|___/
    #

    @staticmethod
    def inside_grid(row, col):
        return 0 <= row < MAP_SIZE and 0 <= col < MAP_SIZE

    def set_cell(self, row, col):
        self.grid[row][col].set(self.draw_type.get())

        opp = get_opp((row, col), self.symetry.get())
        if opp is not None:
            self.grid[opp[0]][opp[1]].set(self.draw_type.get())

    def fill_grid(self):
        for row in self.grid:
            for cell in row:
                cell.set(self.draw_type.get())

    #   _____                 _     _   _                 _ _ _
    #  | ____|_   _____ _ __ | |_  | | | | __ _ _ __   __| | (_)_ __   __ _
    #  |  _| \ \ / / _ \ '_ \| __| | |_| |/ _` | '_ \ / _` | | | '_ \ / _` |
    #  | |___ \ V /  __/ | | | |_  |  _  | (_| | | | | (_| | | | | | | (_| |
    #  |_____| \_/ \___|_| |_|\__| |_| |_|\__,_|_| |_|\__,_|_|_|_| |_|\__, |
    #                                                                 |___/

    def event_set_cell(self, event):
        row = int(event.y / MAP_CELL_SIZE)
        col = int(event.x / MAP_CELL_SIZE)

        if self.inside_grid(row, col):
            self.set_cell(row, col)

    #   ____            _       _ _          _   _
    #  / ___|  ___ _ __(_) __ _| (_)______ _| |_(_) ___  _ __
    #  \___ \ / _ \ '__| |/ _` | | |_  / _` | __| |/ _ \| '_ \
    #   ___) |  __/ |  | | (_| | | |/ / (_| | |_| | (_) | | | |
    #  |____/ \___|_|  |_|\__,_|_|_/___\__,_|\__|_|\___/|_| |_|
    #

    def save_grid(self):
        filename = asksaveasfilename()
        if not filename:
            return

        with open(filename, 'w+') as f:
            # Init raw and list outputs datas
            raw_output = dict()
            list_output = dict()

            for name, conf in CELL_TYPES.items():
                if conf['serialize']['method'] == 'raw':
                    default_data = [0, 0] + ([0] * len(conf['extra'])
                                             if 'extra' in conf else [])
                    raw_output[conf['serialize']['order']] = default_data
                elif conf['serialize']['method'] == 'list':
                    list_output[conf['serialize']['order']] = []

            # Serialize the grid and catch raw and list outputs
            for row, row_data in enumerate(self.grid):
                for col, cell in enumerate(row_data):
                    conf = get_type_conf(cell.cell_type)
                    data = [row, col]

                    # Add extra infos if necessary
                    if 'extra' in conf:
                        data += [
                            conf['default'][field] for field in conf['extra']
                        ]

                    # Serialization of the grid
                    if 'ascii' in conf['serialize']:
                        f.write(conf['serialize']['ascii'])
                    else:
                        f.write(CELL_TYPES[DEFAULT_CELL_TYPE]['serialize']
                                ['ascii'])

                    # Register for raw and list outputs
                    if conf['serialize']['method'] == 'raw':
                        raw_output[conf['serialize']['order']] = data
                    elif conf['serialize']['method'] == 'list':
                        list_output[conf['serialize']['order']].append(data)

                f.write('\n')

            # Serialize raw and list outputs
            order_keys = sorted(
                list(raw_output.keys()) + list(list_output.keys()))

            for order in order_keys:
                if order in raw_output:
                    f.write('{}\n'.format(' '.join(map(str,
                                                       raw_output[order]))))
                else:
                    f.write('{}\n'.format(len(list_output[order])))
                    for item in list_output[order]:
                        f.write('{}\n'.format(' '.join(map(str, item))))

    def load_grid(self, filename=None):
        if filename is None:
            filename = askopenfilename()

        # Index of symbols to consider in the grid
        from_ascii = {
            conf['serialize']['ascii']: name
            for name, conf in CELL_TYPES.items()
            if conf['serialize']['method'] == 'ascii'
        }

        # Ordered list of items to catch after reading the grid
        from_raw_or_list = [(name, conf['serialize']['order'])
                            for name, conf in CELL_TYPES.items()
                            if conf['serialize']['method'] in ['raw', 'list']]
        from_raw_or_list.sort(key=lambda x: x[1])
        from_raw_or_list = map(lambda x: x[0], from_raw_or_list)

        # Need to match exactly a preset when 'extra' is specified, create
        # an index to get which preset is used
        fullname_index = dict()

        for full_name in list_draw_types():
            if ':' in full_name:
                conf = get_type_conf(full_name)
                parent_name, preset_name = full_name.split(':')

                key = tuple(
                    [parent_name] +
                    [conf['default'][field] for field in conf['extra']])
                fullname_index[key] = full_name
            else:
                fullname_index[(full_name, )] = full_name

        with open(filename, 'r') as f:
            # Read the grid
            for row in range(MAP_SIZE):
                for col, char in enumerate(f.readline()):
                    if self.inside_grid(row, col) and char in from_ascii:
                        self.grid[row][col].set(from_ascii[char])

            # Read raw and list infos
            for name in from_raw_or_list:
                conf = CELL_TYPES[name]

                if conf['serialize']['method'] == 'raw':
                    row, col, *extra = map(int, f.readline().split(' '))
                    self.grid[row][col].set(name)
                elif conf['serialize']['method'] == 'list':
                    n = int(f.readline())
                    for _ in range(n):
                        row, col, *extra = map(int, f.readline().split(' '))

                        identifier = (name, ) + tuple(extra)
                        if identifier in fullname_index:
                            self.grid[row][col].set(fullname_index[identifier])

        self.draw()
示例#56
0
    def __init__(self):
        # root is the Tkinter root widget
        self.root = Tk()
        self.root.title("Input Device Utility")

        # self.root.configure(background='grey')

        self.root.resizable(False, False)

        # define response to main window closing
        self.root.protocol("WM_DELETE_WINDOW", self.app_exit)

        self.my_device = ''
        self.my_device_display = StringVar()
        self.device_list = []
        self.matches = 0

        # overall display
        root_frame = Frame(self.root)
        root_frame.pack(side=LEFT)

        devices_frame = Frame(root_frame, padx=5, pady=10)
        devices_frame.pack(side=LEFT)

        devices_label = Label(devices_frame, text="Devices in dev/input")
        devices_label.pack(side=TOP)

        devices_list_frame = Frame(devices_frame, padx=5, pady=10)
        devices_list_frame.pack(side=TOP)

        selected_device_title = Label(devices_frame, text='Selected device')
        selected_device_title.pack(side=TOP)
        self.selected_device_var = StringVar()
        selected_device = Label(devices_frame,
                                textvariable=self.selected_device_var,
                                fg="red")
        selected_device.pack(side=TOP)

        events_frame = Frame(root_frame, padx=5, pady=10)
        events_frame.pack(side=LEFT)
        events_title = Label(events_frame, text='Received Events')
        events_title.pack(side=TOP)
        events_list_frame = Frame(events_frame, padx=5, pady=10)
        events_list_frame.pack(side=TOP)

        # list of devices
        scrollbar = Scrollbar(devices_list_frame, orient=VERTICAL)
        self.devices_display = Listbox(devices_list_frame,
                                       selectmode=SINGLE,
                                       height=20,
                                       width=60,
                                       bg="white",
                                       activestyle=NONE,
                                       fg="black",
                                       yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.devices_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.devices_display.pack(side=LEFT, fill=BOTH, expand=1)
        self.devices_display.bind("<ButtonRelease-1>", self.e_select_device)

        # events display
        scrollbar = Scrollbar(events_list_frame, orient=VERTICAL)
        self.events_display = Text(events_list_frame,
                                   width=40,
                                   height=20,
                                   wrap='word',
                                   font="arial 11",
                                   padx=5,
                                   yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.events_display.yview)
        scrollbar.pack(side=RIGHT, fill=Y)
        self.events_display.pack(side=LEFT, fill=BOTH, expand=1)
        self.events_display.config(state=NORMAL)
        self.events_display.delete(1.0, END)
        self.events_display.config(state=DISABLED)

        self.selected_device_index = -1
        self.matches = 0

        self.get_all_devices()
        self.refresh_devices_display()

        self.root.after(10, self.event_loop)

        # and enter Tkinter event loop
        self.root.mainloop()
示例#57
0
def askAjouterHeure(heureMin, heureMax, totalHeure):
    nbHeure = None
    position = None

    def onClose(bouton):
        # Permet de modifier les valeurs des variables
        nonlocal nbHeure, position
        if bouton == 'Ok':
            position = varRadioBouton.get()
            nbHeure = int(sb.get())
            if varRadioGestion.get() == "Retirer":
                nbHeure = nbHeure * -1
        fen.destroy()

    # Pour adapter le nombre d'heure max du spinBoc
    def adapteSpinbox():
        newVar = 0
        if varRadioGestion.get() == "Retirer":
            newVar = totalHeure
        elif varRadioGestion.get() == "Ajouter":
            if varRadioBouton.get() == "Apres":
                newVar = heureMax.total_seconds() // 3600
            elif varRadioBouton.get() == "Avant":
                newVar = heureMin.hour
        # On config
        sb.config(to=newVar)
        # Si on dépasse, on reset au max
        if int(sb.get()) > newVar:
            sb.set(int(newVar))

    fen = Dialog(title="Nombre d'heure à ajouter",
                 buttons=("Ok", "Annuler"),
                 command=onClose,
                 exitButton=('Ok', 'Annuler', "WM_DELETE_WINDOW"))
    # Binding des touches
    fen.bind_all("<Return>", lambda e: fen.execute("Ok"))
    fen.bind_all("<Escape>", lambda e: fen.execute("Annuler"))

    # Mettre les widgets
    frameGestion = Frame(fen)
    varRadioGestion = StringVar()
    rG1 = Radiobutton(frameGestion,
                      text="Ajouter les heures",
                      variable=varRadioGestion,
                      value="Ajouter",
                      command=adapteSpinbox)
    rG2 = Radiobutton(frameGestion,
                      text="Retirer les heures",
                      variable=varRadioGestion,
                      value="Retirer",
                      command=adapteSpinbox)
    rG1.grid(row=0, sticky="w")
    rG2.grid(row=1, sticky="w")

    frameHeure = Labelframe(fen, text="Combien d'heure ajouter ?")
    lb = Label(frameHeure, text="Nombre d'heure :")
    sb = Spinbox(frameHeure, from_=0, to=heureMax.total_seconds() // 3600)
    sb.set(0)
    lb.pack(side=LEFT, fill=BOTH)
    sb.pack(side=LEFT, fill=X, expand=YES)

    framePos = Labelframe(fen, text="Où rajouter les heures ?")
    varRadioBouton = StringVar()
    r1 = Radiobutton(framePos,
                     text="Au début de la journée",
                     variable=varRadioBouton,
                     value="Avant",
                     command=adapteSpinbox)
    r2 = Radiobutton(framePos,
                     text="À la fin de la journée",
                     variable=varRadioBouton,
                     value="Apres",
                     command=adapteSpinbox)
    r1.grid(row=0, sticky="w")
    r2.grid(row=1, sticky="w")

    frameGestion.pack(side=TOP, expand=YES, fill=BOTH)
    frameHeure.pack(side=TOP, expand=YES, fill=BOTH)
    framePos.pack(side=TOP, expand=YES, fill=BOTH)

    varRadioGestion.set("Ajouter")
    varRadioBouton.set("Apres")

    # Active et attend (un peu comme une mainloop)
    fen.activateandwait()
    return nbHeure, position
示例#58
0
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

window = Tk()
window.title("title")
window.resizable(0, 0)
window.geometry("1500x800+20+20")

# 웹캠 구간
lmain = Label(window)
lmain.pack(side="left")

# 오른쪽 구간
sub_frame = Frame(window)
sub_frame.pack(side="left")

# 등록 버튼
register_btn = Button(sub_frame,
                      text="Register",
                      width=10,
                      height=5,
                      command=register_btn_click)
register_btn.grid(row=0, column=0, rowspan=3, columnspan=3, padx=5, pady=5)

# 레이블과 이름 입력 엔트리
register_label = Label(sub_frame, text="Input Name :")
register_label.grid(row=4, column=0, padx=5, pady=5)
register_name = Entry(sub_frame, width=10)
register_name.grid(row=4, column=1, padx=5, pady=5)
示例#59
0
        sleep(0.5)


if __name__ == '__main__':

    root = Tk()
    root.title('cliptrans')
    root.geometry('300x100')
    root.resizable(0, 0)
    root.iconbitmap('.\\icon.ico')
    root.attributes('-topmost', True)
    frame = Frame(root)
    scrollbar = Scrollbar(frame, orient=VERTICAL)
    text = Text(frame,
                state='disable',
                font=(
                    '宋体',
                    12,
                ),
                yscrollcommand=scrollbar.set)
    scrollbar.pack(side=RIGHT, fill=Y)
    scrollbar.config(command=text.yview)
    text.pack()
    frame.pack(expand=True, fill='both')

    thread = Thread(target=translate)
    thread.daemon = True
    thread.start()

    root.mainloop()
示例#60
-1
 def initUI(self):
     #top frame using all the remaining space
     innerTopFrame = Frame(self, background="black")
     innerTopFrame.pack(fill=BOTH, expand=1)
     #CLOSE Label
     innerBottomLeftFrame = Frame(self, background="black")
     innerBottomLeftFrame.place(x=0, width=self.wRoot/2, 
         y=self.hRoot-200, height=200)
     closeLabel = Label(innerBottomLeftFrame, bg="black", fg="black",
         text="CLOSE", font=("Comic Sans MS", 48, "bold"))
     innerBottomLeftFrame.bind("<Enter>", lambda f: closeLabel.config(fg="white"))
     innerBottomLeftFrame.bind("<Leave>", lambda f: closeLabel.config(fg="black"))
     innerBottomLeftFrame.bind("<Button-1>", lambda f: self.root.quit())
     closeLabel.bind("<Button-1>", lambda f: self.root.quit())
     closeLabel.pack(fill=BOTH)
     #SHUT DOWN Label
     innerBottomRightFrame = Frame(self, background="black")
     innerBottomRightFrame.place(x=self.wRoot/2, width=self.wRoot/2, 
         y=self.hRoot-200, height=200)
     shutdownLabel = Label(innerBottomRightFrame, bg="black", fg="black",
         text="SHUT DOWN", font=("Comic Sans MS", 48, "bold"))
     innerBottomRightFrame.bind("<Enter>", lambda f: shutdownLabel.config(fg="white"))
     innerBottomRightFrame.bind("<Leave>", lambda f: shutdownLabel.config(fg="black"))
     innerBottomRightFrame.bind("<Button-1>", self.shutdown)
     shutdownLabel.bind("<Button-1>", self.shutdown)
     shutdownLabel.pack(fill=BOTH)
     #design the FullScreenApp
     self.pack(fill=BOTH, expand=1)