def instruction():
    global rootB

    rootB = Tk()
    rootB.geometry('480x300+400+100')
    rootB.overrideredirect(True)

    def instruction_back():
        rootB.destroy()

    w = Listbox(rootB, height=30, width=80)
    s = '''
    CROSSWORD v2.0 game consists of a 15x15 matrix consisting of words.
    The player has to found out the words one by one. Here name of fruit,
    sports,movies,animals has been used. Checkbuttons sends the desired choice
    Check button check for its validity. Build button stsrts new game.

    This is a beta version so user might face bugs in the game.
    Developments are still going on.
    Recommendations is gladly accepted.

    Tamojit Das
    IEM CSE
    '''
    s = s.split('\n')
    for c in range(len(s)):
        w.insert(c + 1, s[c])
    #w.pack(expand='yes',fill='both')
    w.place(x=0, y=25)

    Button(rootB, text='<= Back', command=instruction_back).place(x=0, y=0)

    rootB.mainloop()
示例#2
0
文件: gui.py 项目: OzTamir/oZip
 def initUI(self):
     ''' Create the UI '''
     # Name the window
     self.parent.title("oZip")
     self.pack(fill=BOTH, expand=1)
     
     # 'Add File' button
     addFileButton = Button(self, text="Add File",
         command=self.onOpen)
     addFileButton.place(x=225, y=30)
     
     # 'Go' button
     goButton = Button(self, text="Go",
         command=self.onClick)
     goButton.place(x=225, y=100)
     
     # 'Quit' button
     quitButton = Button(self, text="Quit",
         command=self.quit)
     quitButton.place(x=225, y=160)
     
     # Decompression checkbox
     self.cb = Checkbutton(self, text="Should decompress",
         command=self.checkboxClick)
     self.cb.place(x=20, y=195)
     
     # Selected files list
     lb = Listbox(self)
     self.lb = lb   
     lb.place(x=20, y=20)
示例#3
0
    def initUI(self):

        self.parent.title("Listbox + Scale + ChkBtn")
        self.pack(fill=BOTH, expand=1)
        acts = ['Scarlett Johansson', 'Rachel Weiss',
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)

        lb.bind("<<ListboxSelect>>", self.onSelect)
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        self.label.place(x=20, y=190)

        scale = Scale(self, from_=0, to=100, command=self.onScale)
        scale.place(x=20, y=220)

        self.var_scale = IntVar()
        self.label_scale = Label(self, text=0, textvariable=self.var_scale)
        self.label_scale.place(x=180, y=220)

        self.var_chk = IntVar()
        cb = Checkbutton(self, text="Test", variable=self.var_chk,
                command=self.onClick)
        cb.select()
        cb.place(x=220, y=60)
示例#4
0
    def initUI(self):
      
        self.parent.title("Listbox") 
        
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss', 
            'Natalie Portman', 'Jessica Alba']
        #This is a list of actresses to be shown in the listbox.

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)
        #We create an instance of the Listbox and insert all the items from the above mentioned list.
            
        lb.bind("<<ListboxSelect>>", self.onSelect)
        #When we select an item in the listbox, the <<ListboxSelect>> event is generated. 
        #We bind the onSelect() method to this event.
        
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)
        #A label and its value holder is created. 
        #In this label we will display the currently selected item.
        self.label.place(x=20, y=210)
    def addListBox(self, ax=600, ay=52, x=0, y=0, bg="#B4045F"):

        scrolly = Scrollbar(self,
                            activebackground="#171212",
                            bg="#171212",
                            orient=VERTICAL,
                            troughcolor="#171212")

        listbox = Listbox(self,
                          height=ay,
                          width=ax,
                          background=bg,
                          borderwidth=0,
                          highlightcolor="#4d86a1",
                          selectbackground="#4d86a1",
                          activestyle=NONE,
                          highlightbackground="#4a4a4a",
                          yscrollcommand=scrolly.set)
        listbox.config(font=("", 10), fg="#FFFFFF")
        listbox.place(x=0, y=0)
        scrolly.place(x=651, y=0, height=387)
        self.__list_listbox.append(listbox)
        self.__list_scrollbar.append(scrolly)
        for x in self.__list_listbox:
            x.configure(yscrollcommand=scrolly.set)
        scrolly.configure(command=self.__yview)
示例#6
0
    def initUI(self):
      
        self.parent.title("Listbox") 
        
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss', 
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)
            
        lb.bind("<<ListboxSelect>>", self.onSelect)    
            
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)        
        self.label.place(x=20, y=210)
示例#7
0
    def initUI(self):
      
        self.parent.title("Listbox") 
        
        self.pack(fill=BOTH, expand=1)

        acts = ['Scarlett Johansson', 'Rachel Weiss', 
            'Natalie Portman', 'Jessica Alba']

        lb = Listbox(self)
        for i in acts:
            lb.insert(END, i)
            
        lb.bind("<<ListboxSelect>>", self.onSelect)    
            
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)        
        self.label.place(x=20, y=210)
示例#8
0
    def initUI(self):

        self.parent.title("Captura de datos")
        self.style = Style()
        self.pack(fill=BOTH, expand=1)

        BotonIncX = Button(self, text="+", command=IncX)
        BotonIncX.place(x=300, y=150)
        label1 = Label(self, text="Incrementar X:")
        label1.place(x=150, y=150)
        global texto1, texto2, x, y
        x = 0
        y = 0
        texto1 = StringVar()
        texto1.set(x)
        label10 = Label(self, textvariable=texto1, width=5, relief="solid")
        label10.place(x=250, y=175)
        BotonDecX = Button(self, text="-", command=DecX)
        BotonDecX.place(x=300, y=200)
        label2 = Label(self, text="Decrementar X:")
        label2.place(x=150, y=200)
        BotonIncY = Button(self, text="+", command=IncY)
        BotonIncY.place(x=300, y=250)
        label3 = Label(self, text="Incrementar Y:")
        label3.place(x=150, y=250)
        texto2 = StringVar()
        texto2.set(y)
        label101 = Label(self, textvariable=texto2, width=5, relief="solid")
        label101.place(x=250, y=275)
        BotonDecY = Button(self, text="-", command=DecY)
        BotonDecY.place(x=300, y=300)
        label4 = Label(self, text="Decrementar Y:")
        label4.place(x=150, y=300)
        Grabar = Button(self, text="Grabar Registro", command=GrabarRegistro)
        Grabar.place(x=150, y=340)
        global ListaMACs
        ListaMACs = Listbox(self, bd=2, relief="solid", height=4, width=82)
        ListaMACs.place(x=50, y=50)

        Scan = Button(self, text="Escanear RSSI en MAC", command=ScanMAC)
        Scan.place(x=350, y=340)
示例#9
0
    def initUI(self):

        self.parent.title("Captura de datos")
        self.style = Style()
        self.pack(fill=BOTH, expand=1)

        BotonIncX = Button(self, text="+", command=IncX)
        BotonIncX.place(x=300, y=150)
        label1 = Label(self, text = "Incrementar X:")
        label1.place(x=150, y=150)
        global texto1, texto2, x, y
        x = 0
        y = 0
        texto1 = StringVar()
        texto1.set(x)
        label10 = Label(self, textvariable=texto1, width=5, relief="solid")
        label10.place(x=250, y=175)
        BotonDecX = Button(self, text="-", command=DecX)
        BotonDecX.place(x=300, y=200)
        label2 = Label(self, text = "Decrementar X:")
        label2.place(x=150, y=200)
        BotonIncY = Button(self, text="+", command=IncY)
        BotonIncY.place(x=300, y=250)
        label3 = Label(self, text = "Incrementar Y:")
        label3.place(x=150, y=250)
        texto2 = StringVar()
        texto2.set(y)
        label101 = Label(self, textvariable=texto2, width=5, relief="solid")
        label101.place(x=250, y=275)
        BotonDecY = Button(self, text="-", command=DecY)
        BotonDecY.place(x=300, y=300)
        label4 = Label(self, text = "Decrementar Y:")
        label4.place(x=150, y=300)
        Grabar = Button(self, text="Grabar Registro", command=GrabarRegistro)
        Grabar.place(x=150, y=340)
        global ListaMACs
        ListaMACs = Listbox(self,bd=2,relief="solid",height=4,width=82)
        ListaMACs.place(x=50,y=50)

        Scan = Button(self, text="Escanear RSSI en MAC", command=ScanMAC)
        Scan.place(x=350, y=340)
示例#10
0
    def initUI(self):
      
        self.parent.title("Listbox") 
        
        self.pack(fill=BOTH, expand=1)

        # put our data in from our global data object
        lb = Listbox(self)
        for i in data:
            lb.insert(END, i)
            
        # add event listener with call back to show
        # when the list object is selected, show visual feedback
        lb.bind("<<ListboxSelect>>", self.onSelect)    
            
        # absolute positioning
        lb.place(x=20, y=20)

        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)        
        self.label.place(x=20, y=210)
示例#11
0
class Participant(object):
    """
    Creates the input frame and stores the information regarding the
    participant
    """
    def __init__(self, parent, *args, **kwargs):
        """
        Initialize the input frame and call to inititialize the user
        interface
        """
        # Set the Tk as the parent
        self.parent = parent
        # Initialize the user interface
        self.initUI()

    def initUI(self):
        """
        Initializes the user interface

        Setting up the entry widgets for:
        - Experiment_ID
        - Participant Name
        - Session Day
        - Pupil Size
        - Practice
        - Stereo
        """
        # Set the title
        self.parent.title(EXP_NAME)

        # Create the label for Experiment_ID and set location
        label_id = Label(text='Participant ID:')
        label_id.place(x=20, y=20)

        # Check the DATA_DIR directory for previous participants
        # and choose the next Experiment_ID in line
        self.folders = listdir(DATA_DIR)
        # Initiate Tkinter's StringVar
        self.value_id = StringVar()
        # Set the default value
        self.value_id.set('001')
        # Going in reverse order of the participants' directories in
        # DATA_DIR, find the last participant's Experiment_ID and opt
        # for the next one in line
        for folder in reversed(self.folders):
            try:
                # Check if the value of the first 3 digits of the
                # directory name is greater than the default value
                if int(folder[:3]) >= int(self.value_id.get()):
                    # Get the next Experiment_ID in integer form and
                    # convert to string format
                    num = str(int(folder[:3]) + 1)
                    # Actions to perform in case scenarios for each
                    # of the possibilites of num_length
                    num_length = {
                                  3: num,
                                  2: '0%s' % num,
                                  1: '00%s' % num
                    }
                    # Set the value accordingly to the StringVar,
                    # replacing the default
                    self.value_id.set(num_length[len(num)])
            # In case there are other folders in DATA_DIR, for which
            # the first 3 characters are not digits, we must cater
            # for when an exception is thrown up
            except ValueError:
                pass
        # Create the entry widget for Experiment_ID with the preset
        # value and state disabled
        self.input_id = Entry(self.parent, width=5, state=DISABLED,
                              textvariable=self.value_id)
        self.input_id.place(x=150, y=20)

        # Create the label for Participant Name and set location
        label_name = Label(text='Participant Name:')
        label_name.place(x=20, y=50)

        # Initiate Tkinter's StringVar
        self.value_name = StringVar()
        # Set the default value
        self.value_name.set('')
        # Create the entry for Participant Name and set location
        self.input_name = Entry(self.parent, width=35,
                                textvariable=self.value_name)
        self.input_name.place(x=150, y=50)
        self.input_name.focus()

        # Create the label for Session Day and set location
        label_day = Label(text='Session Day:')
        label_day.place(x=20, y=80)

        # Create value holder for Session Day as IntVar and set default
        # value to 1
        self.value_day = IntVar()
        self.value_day.set(1)
        # Create the radiobuttons as required
        for day in range(1, TOTAL_SESSIONS + 1):
            input_day = Radiobutton(self.parent, text=str(day),
                                    variable=self.value_day, value=day)
            # Anchor them to the West (W)
            input_day.pack(anchor=W)
            # Choose location for the radiobuttons
            input_day.place(x=150, y=(50 + (day * 25)))

        # Create the label for Pupil Size and set location
        label_pupilsize = Label(text='Pupil Size:')
        label_pupilsize.place(x=20, y=140)

        self.value_pupilsize = StringVar()
        self.value_pupilsize.set('')
        # Create the MaxLengthEntry for Pupil Size and set location
        # The maximum length is set to 3 characters and a float must be
        # provided
        self.input_pupilsize = MaxLengthEntry(self.parent, width=5,
                                              maxlength=3,
                                              required_type=float)
        self.input_pupilsize.config(textvariable=self.value_pupilsize)
        self.input_pupilsize.place(x=150, y=140)

        # Create value folder for Practice as IntVar
        self.value_practice = IntVar()
        # Create the checkbutton for Practice and set location
        input_practice = Checkbutton(self.parent, text='Practice',
                                     variable=self.value_practice, onvalue=1,
                                     offvalue=0)
        input_practice.place(x=150, y=170)

        # Create value holder for Stereo as IntVar
        self.value_stereo = IntVar()
        # Create the checkbutton for Stereo and set location
        input_stereo = Checkbutton(self.parent, text='Stereo',
                                   variable=self.value_stereo, onvalue=1,
                                   offvalue=0)
        input_stereo.place(x=150, y=200)

        # Create the label for Previous Subjects and set location
        label_previous = Label(text='Previous Subjects:')
        label_previous.place(x=20, y=250)

        # Create the Listboc containing all the previous participants
        self.input_previous = Listbox(self.parent, width=35, height=10)
        for identifier in self.folders:
            self.input_previous.insert(END, identifier)
        self.input_previous.place(x=150, y=250)
        self.input_previous.bind('<<ListboxSelect>>', self.__select_previous)

        # Create the submit button, give command upon pressing and set
        # location
        submit = Button(text='Submit', width=47, command=self.gather_input)
        submit.pack(padx=8, pady=8)
        submit.place(x=20, y=425)

    def __select_previous(self, event):
        """
        Handle scenario where user selects one of the previous participants
        """
        # Collect from previous subjects, if it was chosen
        self.previous = self.input_previous.curselection()
        if self.previous:
            self.previous = self.folders[int(self.previous[0])]
            with open(join(DATA_DIR, self.previous, 'data.json')) as f:
                data = load(f)
                # Set the value for participant ID
                self.value_id.set(data['ID'])
                # Set the value for name and disable the user from making
                # any more changes
                self.value_name.set(data['Name'])
                self.input_name.config(state=DISABLED)
                # Set the value for pupilsize and disable the user from
                # making any more changes
                self.value_pupilsize.set(data['Pupil Size'])
                self.input_pupilsize.config(state=DISABLED)

    def gather_input(self):
        """
        Gather the input from the Tkinter window and store it as class
        variables of the Participant class

        This module will also create a folder for the participant if
        it does not exist already in DATA_DIR
        NOTE: DATA_DIR is set in settings.py
        """
        # Collect all the values input and convert to their appropriate
        # types
        self.subject_id = self.input_id.get()
        self.name = self.input_name.get().title()
        self.day = int(self.value_day.get())
        try:
            self.pupilsize = float(self.input_pupilsize.get())
        except ValueError:
            pass
        self.practice = bool(self.value_practice.get())
        self.stereo = bool(self.value_stereo.get())

        # Destroy the Tkinter window
        self.parent.destroy()

        # Put together the directory name and path
        self.subject_dir = '%s_%s' % (self.subject_id,
                                      self.name.replace(' ', ''))
        self.subject_dir = join(DATA_DIR, self.subject_dir)
        # If the directory for the participant does not exist, create it
        if not exists(self.subject_dir):
            makedirs(self.subject_dir)
示例#12
0
class Participant(object):
    """
    Creates the input frame and stores the information regarding the
    participant
    """
    def __init__(self, parent, *args, **kwargs):
        """
        Initialize the input frame and call to inititialize the user
        interface
        """
        # Set the Tk as the parent
        self.parent = parent
        # Initialize the user interface
        self.initUI()

    def initUI(self):
        """
        Initializes the user interface

        Setting up the entry widgets for:
        - Experiment_ID
        - Participant Name
        - Session Day
        - Pupil Size
        - Practice
        - Stereo
        """
        # Set the title
        self.parent.title(EXP_NAME)

        # Create the label for Experiment_ID and set location
        label_id = Label(text='Participant ID:')
        label_id.place(x=20, y=20)

        # Check the DATA_DIR directory for previous participants
        # and choose the next Experiment_ID in line
        self.folders = listdir(DATA_DIR)
        # Initiate Tkinter's StringVar
        self.value_id = StringVar()
        # Set the default value
        self.value_id.set('001')
        # Going in reverse order of the participants' directories in
        # DATA_DIR, find the last participant's Experiment_ID and opt
        # for the next one in line
        for folder in reversed(self.folders):
            try:
                # Check if the value of the first 3 digits of the
                # directory name is greater than the default value
                if int(folder[:3]) >= int(self.value_id.get()):
                    # Get the next Experiment_ID in integer form and
                    # convert to string format
                    num = str(int(folder[:3]) + 1)
                    # Actions to perform in case scenarios for each
                    # of the possibilites of num_length
                    num_length = {3: num, 2: '0%s' % num, 1: '00%s' % num}
                    # Set the value accordingly to the StringVar,
                    # replacing the default
                    self.value_id.set(num_length[len(num)])
            # In case there are other folders in DATA_DIR, for which
            # the first 3 characters are not digits, we must cater
            # for when an exception is thrown up
            except ValueError:
                pass
        # Create the entry widget for Experiment_ID with the preset
        # value and state disabled
        self.input_id = Entry(self.parent,
                              width=5,
                              state=DISABLED,
                              textvariable=self.value_id)
        self.input_id.place(x=150, y=20)

        # Create the label for Participant Name and set location
        label_name = Label(text='Participant Name:')
        label_name.place(x=20, y=50)

        # Initiate Tkinter's StringVar
        self.value_name = StringVar()
        # Set the default value
        self.value_name.set('')
        # Create the entry for Participant Name and set location
        self.input_name = Entry(self.parent,
                                width=35,
                                textvariable=self.value_name)
        self.input_name.place(x=150, y=50)
        self.input_name.focus()

        # Create the label for Session Day and set location
        label_day = Label(text='Session Day:')
        label_day.place(x=20, y=80)

        # Create value holder for Session Day as IntVar and set default
        # value to 1
        self.value_day = IntVar()
        self.value_day.set(1)
        # Create the radiobuttons as required
        for day in range(1, TOTAL_SESSIONS + 1):
            input_day = Radiobutton(self.parent,
                                    text=str(day),
                                    variable=self.value_day,
                                    value=day)
            # Anchor them to the West (W)
            input_day.pack(anchor=W)
            # Choose location for the radiobuttons
            input_day.place(x=150, y=(50 + (day * 25)))

        # Create the label for Pupil Size and set location
        label_pupilsize = Label(text='Pupil Size:')
        label_pupilsize.place(x=20, y=140)

        self.value_pupilsize = StringVar()
        self.value_pupilsize.set('')
        # Create the MaxLengthEntry for Pupil Size and set location
        # The maximum length is set to 3 characters and a float must be
        # provided
        self.input_pupilsize = MaxLengthEntry(self.parent,
                                              width=5,
                                              maxlength=3,
                                              required_type=float)
        self.input_pupilsize.config(textvariable=self.value_pupilsize)
        self.input_pupilsize.place(x=150, y=140)

        # Create value folder for Practice as IntVar
        self.value_practice = IntVar()
        # Create the checkbutton for Practice and set location
        input_practice = Checkbutton(self.parent,
                                     text='Practice',
                                     variable=self.value_practice,
                                     onvalue=1,
                                     offvalue=0)
        input_practice.place(x=150, y=170)

        # Create value holder for Stereo as IntVar
        self.value_stereo = IntVar()
        # Create the checkbutton for Stereo and set location
        input_stereo = Checkbutton(self.parent,
                                   text='Stereo',
                                   variable=self.value_stereo,
                                   onvalue=1,
                                   offvalue=0)
        input_stereo.place(x=150, y=200)

        # Create the label for Previous Subjects and set location
        label_previous = Label(text='Previous Subjects:')
        label_previous.place(x=20, y=250)

        # Create the Listboc containing all the previous participants
        self.input_previous = Listbox(self.parent, width=35, height=10)
        for identifier in self.folders:
            self.input_previous.insert(END, identifier)
        self.input_previous.place(x=150, y=250)
        self.input_previous.bind('<<ListboxSelect>>', self.__select_previous)

        # Create the submit button, give command upon pressing and set
        # location
        submit = Button(text='Submit', width=47, command=self.gather_input)
        submit.pack(padx=8, pady=8)
        submit.place(x=20, y=425)

    def __select_previous(self, event):
        """
        Handle scenario where user selects one of the previous participants
        """
        # Collect from previous subjects, if it was chosen
        self.previous = self.input_previous.curselection()
        if self.previous:
            self.previous = self.folders[int(self.previous[0])]
            with open(join(DATA_DIR, self.previous, 'data.json')) as f:
                data = load(f)
                # Set the value for participant ID
                self.value_id.set(data['ID'])
                # Set the value for name and disable the user from making
                # any more changes
                self.value_name.set(data['Name'])
                self.input_name.config(state=DISABLED)
                # Set the value for pupilsize and disable the user from
                # making any more changes
                self.value_pupilsize.set(data['Pupil Size'])
                self.input_pupilsize.config(state=DISABLED)

    def gather_input(self):
        """
        Gather the input from the Tkinter window and store it as class
        variables of the Participant class

        This module will also create a folder for the participant if
        it does not exist already in DATA_DIR
        NOTE: DATA_DIR is set in settings.py
        """
        # Collect all the values input and convert to their appropriate
        # types
        self.subject_id = self.input_id.get()
        self.name = self.input_name.get().title()
        self.day = int(self.value_day.get())
        try:
            self.pupilsize = float(self.input_pupilsize.get())
        except ValueError:
            pass
        self.practice = bool(self.value_practice.get())
        self.stereo = bool(self.value_stereo.get())

        # Destroy the Tkinter window
        self.parent.destroy()

        # Put together the directory name and path
        self.subject_dir = '%s_%s' % (self.subject_id,
                                      self.name.replace(' ', ''))
        self.subject_dir = join(DATA_DIR, self.subject_dir)
        # If the directory for the participant does not exist, create it
        if not exists(self.subject_dir):
            makedirs(self.subject_dir)
class ChooseNameUI(Frame):
    def __init__(self, parent,names=["1","2","3"]):
        Frame.__init__(self, parent)   
        self.parent = parent       
        self.names = names 
        self.initUI()
        self.centerWindow()
        
    def initUI(self):
        self.parent.title("选择角色名字") 
        self.pack(fill=BOTH, expand=1)
        "source list"
        self.lb = Listbox(self)
        for i in self.names:
            self.lb.insert(END, i)
        self.lb.bind("<<ListboxSelect>>", self.onSelect)    
        self.lb.place(x=80, y=20)
        "right list"
        self.lbRight = Listbox(self)
        #self.lbRight.bind("<<ListboxSelect>>", self.onSelect)    
        self.lbRight.place(x=150, y=240)
        "left list"
        self.lbLeft = Listbox(self)
        #self.lbLeft.bind("<<ListboxSelect>>", self.onSelect)    
        self.lbLeft.place(x=20, y=240)
        "label"
        self.var = StringVar()
        self.label = Label(self, text=0, textvariable=self.var)        
        self.label.place(x=120, y=400)
        "left button"
        leftButton = Button(self, text="增加到自己的名字", command=self.leftClick)
        leftButton.place(x=20,y=180)
        "left add all button"
        leftAddAllBtn = Button(self, text="添加剩下的名字到自己", command=self.leftAddAllClick)
        leftAddAllBtn.place(x=20,y=210)
        "right button"
        rightButton = Button(self, text="增加到对方的名字", command=self.rightClick)
        rightButton.place(x = 150, y = 180)
        "right add all button"
        rightAddAllBtn = Button(self, text="添加剩下的名字到对方", command=self.rightAddAllClick)
        rightAddAllBtn.place(x=150,y=210)
        "move to right button"
        left2RightBtn = Button(self, text="移动到自己", command=self.move2Left)
        left2RightBtn.place(x=150,y=380)
        "move to left button"
        left2RightBtn = Button(self, text="移动到对方", command=self.move2Right)
        left2RightBtn.place(x=20,y=380)
        "finish button"
        self.finishBtn = Button(self, text="选择完毕", command = self.finishClick)
        self.finishBtn.place(x = 120 , y = 420)

    def onSelect(self, val):
        sender = val.widget
        idx = sender.curselection()
        if idx:
            value = sender.get(idx)   
            self.var.set(value)
    
    def leftClick(self):
        str = self.var.get()
        if str is not None and str != "":
            self.lbLeft.insert(END,str)
            self.removeSelection()
            
    def rightClick(self):
        str = self.var.get()
        if str is not None and str != "":
            self.lbRight.insert(END,str)
            self.removeSelection()
            
    def removeSelection(self):
        index = self.lb.curselection()
        self.lb.delete(index,index)
        self.var.set("")
        "if select all data finish"
        if not self.lb.get(0):
            self.finishClick()
    
    def finishClick(self):
        if self.lb.get(0):
            box.showerror("错误", "还有名字没加入")
        else:
            if not self.lbLeft.get(0):
                box.showerror("错误", "没有自己的名字,请选择")
            elif not self.lbRight.get(0):
                box.showerror("错误", "没有对方的名字,请选择")
            else:
                "get the two list and generate json"
                myList = [self.lbLeft.get(i) for i in xrange(self.lbLeft.size())]
                herList = [self.lbRight.get(i) for i in xrange(self.lbRight.size())]
                #conversationtool.generateJSON(myList,herList)
                t = conversationtool.generateThread(myList,herList)
                t.start()
                t.join()
            
    def rightAddAllClick(self):
        while self.lb.get(0):
            value = self.lb.get(0)
            self.lb.delete(0)
            self.lbRight.insert(END , value)
        self.var.set("")
    
    def leftAddAllClick(self):
        while self.lb.get(0):
            value = self.lb.get(0)
            self.lb.delete(0)
            self.lbLeft.insert(END,value)
        self.var.set("")
    
    def move2Right(self):
        index = self.lbLeft.curselection()
        if index:
            value = self.lbLeft.get(index)
            self.lbLeft.delete(index)
            self.lbRight.insert(END, value)
        else:
            box.showerror("错误", "请选择自己的名字")
        
    def move2Left(self):
        index = self.lbRight.curselection()
        if index:
            value = self.lbRight.get(index)
            self.lbRight.delete(index)
            self.lbLeft.insert(END , value)
        else:
            box.showerror("错误", "请选择对方的名字")
    
    def centerWindow(self):
        w = 300
        h = 450
        sw = self.parent.winfo_screenwidth()
        sh = self.parent.winfo_screenheight()
        x = (sw - w)/2
        y = (sh - h)/2
        self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
示例#14
0
class App(object):
    def __init__(self):

        self.w_window = Tk()

        self.w_listbox_tracks = Listbox(self.w_window)
        self.w_label_base_path = Label(
            self.w_window,
            highlightbackground='red',
            highlightthickness=1,
        )
        self.w_btn_next = Button(
            self.w_window,
            text=u'Следующая',
            command=self.btn_next,
        )
        self.w_btn_pause = Button(
            self.w_window,
            text=u'Пауза/Играть',
            command=self.btn_pause,
        )
        self.w_btn_stop = Button(
            self.w_window,
            text=u'Стоп',
            command=self.btn_stop,
        )
        self.w_btn_plus = Button(
            self.w_window,
            text=u'+',
            command=self.btn_plus,
        )
        self.w_btn_minus = Button(
            self.w_window,
            text=u'-',
            command=self.btn_minus,
        )
        self.buttons = (
            self.w_btn_next,
            self.w_btn_pause,
            self.w_btn_stop,
            self.w_btn_plus,
            self.w_btn_minus,
        )

        self.music_path = ''
        self.musics = getattr(settings, 'musics', {})

        self.musics_map = {}

        self.media_instance = vlc.get_default_instance()
        self.player = self.media_instance.media_player_new()

        self.media = self.media_instance.media_new(u'')
        self.mediaManager = self.media.event_manager()

        self.mark5 = self.mark4 = self.mark3 = self.mark2 = 0
        self.current_play_path = u''

        # для исключения ошибки, get_position не всегда равен 1
        self._last_pos = 2

        self.worked = False

    def _nur_configure(self):
        self.w_window.protocol('WM_DELETE_WINDOW', self.end)
        self.w_label_base_path.bind('<Double-Button-1>', self.set_new_path)
        self.w_listbox_tracks.bind('<Double-Button-1>', self.select_music)

        self.w_window.minsize(width=settings.MAIN_WINDOW_MIN_WIDTH,
                              height=settings.MAIN_WINDOW_MIN_HEIGHT)
        self.w_window.geometry(u'{0}x{1}+{2}+{3}'.format(
            settings.MAIN_WINDOW_WIDTH, settings.MAIN_WINDOW_HEIGHT,
            settings.MAIN_WINDOW_X, settings.MAIN_WINDOW_Y))

    def _nur_layout(self):
        rel_label_height = 0.1
        rel_btns_height = 0.1
        rel_btns_width = 1.0 / len(self.buttons)
        rel_btns_y = 1 - rel_btns_height
        rel_listbox_heigth = 1 - rel_label_height - rel_btns_height

        self.w_label_base_path.place(
            relx=0,
            rely=0,
            relwidth=1,
            relheight=rel_label_height,
        )
        self.w_listbox_tracks.place(
            relx=0,
            rely=rel_label_height,
            relwidth=1,
            relheight=rel_listbox_heigth,
        )
        x = 0
        for btn in self.buttons:

            btn.place(
                relx=x,
                rely=rel_btns_y,
                relwidth=rel_btns_width,
                relheight=rel_btns_height,
            )
            x += rel_btns_width

    def start(self):
        self._nur_configure()
        self._nur_layout()
        self.set_new_path()
        self.w_window.mainloop()

    def end(self):
        self.write_settings()
        self.w_window.destroy()

    def write_settings(self):
        with open(settings.CONFIG_FILE_PATH, 'w') as f:
            json.dump(
                {
                    'MUSIC_PATH': self.music_path,
                    'musics': self.musics,
                    'VOLUME': self.player.audio_get_volume()
                },
                f,
                indent=4)

    def set_new_path(self, event=None):
        if event:
            self.music_path = askdirectory(
                title=u'Выберите папку с музыкой',
                initialdir=self.music_path) or self.music_path
        else:
            self.music_path = settings.MUSIC_PATH

        self.w_label_base_path['text'] = self.music_path
        self._load_musics()

    def _get_musics(self):
        _musics = {}
        for root, dirs, files in os.walk(self.music_path):
            for fil in files:
                if fil.endswith('.mp3'):
                    file_path = os.path.join(root, fil)
                    _musics[file_path] = {
                        'file_name':
                        fil,
                        'album': (file_path.replace(self.music_path,
                                                    '').replace(fil, '')),
                    }
        return _musics

    def _load_musics(self):
        for mus_path, meta in self._get_musics().iteritems():
            if mus_path not in self.musics:
                self.musics[mus_path] = meta
                meta['last_positions'] = [1.0]

        self.__load_musics()

    def __load_musics(self):
        self.musics_map = [(mus_path, u'{album}{file_name}'.format(**mus_meta))
                           for mus_path, mus_meta in self.musics.iteritems()]
        self.musics_map.sort(key=lambda x: x[1])

        self.musics_map = [(item[0], u'{0} - {2} - {1}'.format(
            index, item[1], (sum(self.musics[item[0]]['last_positions']) /
                             len(self.musics[item[0]]['last_positions']))))
                           for index, item in enumerate(self.musics_map)]
        self.w_listbox_tracks.delete(0, END)

        self.w_listbox_tracks.insert(
            END, *(title for mus_path, title in self.musics_map))

    def select_music(self, event=None):
        self.calculate_mark()
        try:
            index = self.w_listbox_tracks.curselection()[0]
            self.current_play_path, music_title = self.musics_map[index]
        except IndexError:
            return
        else:
            self.player.stop()

            self.media = self.media_instance.media_new(self.current_play_path)
            self.mediaManager = self.media.event_manager()

            self.player.set_media(self.media)
            self.player.play()
            self.player.audio_set_volume(settings.VOLUME)
            if not self.worked:
                self.worked = True
                self.w_window.after(3000, self.after)
            # self.player.set_position(0.9)

    def btn_pause(self):
        self.player.pause()
        self.worked = not self.worked
        print self.worked
        if self.worked:
            self.w_window.after(3000, self.after)

    def btn_stop(self):
        self.player.stop()
        self.worked = False

    def btn_plus(self):
        volume = self.player.audio_get_volume()
        if volume < 100:
            self.player.audio_set_volume(volume + 10)

    def btn_minus(self):
        volume = self.player.audio_get_volume()
        if volume > 0:
            self.player.audio_set_volume(volume - 10)

    def btn_next(self):
        if not self.musics:
            return

        self.calculate_mark()

        if self.mark5 < 10:
            mark = 0.8
            self.mark5 += 1
        elif self.mark4 < 8:
            mark = 0.6
            self.mark4 += 1
        elif self.mark3 < 6:
            mark = 0.4
            self.mark3 += 1
        elif self.mark2 < 4:
            mark = 0.2
            self.mark2 += 1
        else:
            mark = 0
            self.mark5 = self.mark4 = self.mark3 = self.mark2 = 0
            self.write_settings()
            self.__load_musics()

        music_path = random.choice([
            path for path, meta in self.musics.iteritems()
            if sum(meta['last_positions']) / len(meta['last_positions']) > mark
        ])
        for index, music in enumerate(self.musics_map):
            if music[0] == music_path:
                break
        self.w_listbox_tracks.selection_clear(0, END)
        self.w_listbox_tracks.activate(index)
        self.w_listbox_tracks.selection_set(index)
        self.w_listbox_tracks.see(index)
        self.select_music()

    def calculate_mark(self):
        try:
            self.musics[self.current_play_path]['last_positions'].append(
                self.player.get_position())
        except KeyError:
            pass
        else:
            self.musics[self.current_play_path]['last_positions'] = (
                self.musics[self.current_play_path]['last_positions'][-10:])

    def after(self):
        pos = self.player.get_position()
        if pos in (1.0, self._last_pos):
            self.btn_next()

        self._last_pos = pos
        if self.worked:
            self.w_window.after(3000, self.after)
示例#15
0
class AutocompleteEntry(Entry):

    def __init__(self, *args, **kwargs):
        Entry.__init__(self, width=100, *args, **kwargs)

        self.focus_set()
        self.pack()

        self.var = self["textvariable"]
        if self.var == '':
            self.var = self["textvariable"] = StringVar()

        self.var.trace('w', self.changed)
        self.bind("<Right>", self.selection)
        self.bind("<Up>", self.up)
        self.bind("<Down>", self.down)
        self.bind("<Return>", self.enter)
        self.lb_up = False
        self.lb = None

    def enter(self, event):
        print event

    def changed(self, name, index, mode):

        if self.var.get() == '':
            if self.lb:
                self.lb.destroy()
            self.lb_up = False
        else:
            words = self.comparison()
            if words:
                if not self.lb_up:
                    self.lb = Listbox(master=root, width=100)

                    self.lb.bind("<Double-Button-1>", self.selection)
                    self.lb.bind("<Right>", self.selection)
                    self.lb.place(x=self.winfo_x(), y=self.winfo_y()+self.winfo_height())
                    self.lb_up = True

                self.lb.delete(0, END)
                for w in words:
                    self.lb.insert(END,w)
            else:
                if self.lb_up:
                    self.lb.destroy()
                    self.lb_up = False

    def selection(self, _):

        if self.lb_up:
            self.var.set(self.lb.get(ACTIVE))
            self.lb.destroy()
            self.lb_up = False
            self.icursor(END)

    def up(self, _):

        if self.lb_up:
            if self.lb.curselection() == ():
                index = '0'
            else:
                index = self.lb.curselection()[0]
            if index != '0':
                self.lb.selection_clear(first=index)
                index = str(int(index)-1)
                self.lb.selection_set(first=index)
                self.lb.activate(index)

    def down(self, _):

        if self.lb_up:
            if self.lb.curselection() == ():
                index = '0'
            else:
                index = self.lb.curselection()[0]
            if index != END:
                self.lb.selection_clear(first=index)
                index = str(int(index)+1)
                self.lb.selection_set(first=index)
                self.lb.activate(index)

    def comparison(self):
        q = self.var.get()
        q = unicode(q.decode('utf8'))
        for hit in searcher.search(qp.parse(q), limit=50):
            if hit['author']:
                yield '%s. "%s"' % (hit['author'], hit['title'])
            else:
                yield hit['title']
示例#16
0
class AutocompleteEntry(Entry):
    def __init__(self, autocompleteList, *args, **kwargs):

        # Listbox length
        self.listboxLength = kwargs.pop('listboxLength', 12)
        self.listboxFontSize = tkFont.Font(size=18)

        # Custom matches function
        if 'matchesFunction' in kwargs:
            self.matchesFunction = kwargs['matchesFunction']
            del kwargs['matchesFunction']
        else:

            def matches(fieldValue, acListEntry):
                pattern = re.compile('.*' + re.escape(fieldValue) + '.*',
                                     re.IGNORECASE)
                return re.match(pattern, acListEntry)

            self.matchesFunction = matches

        Entry.__init__(self, *args, **kwargs)
        self.focus()

        self.autocompleteList = autocompleteList

        self.var = self["textvariable"]
        if self.var == '':
            self.var = self["textvariable"] = StringVar()

        self.var.trace('w', self.changed)
        self.bind("<Return>", self.selection)
        self.bind("<Up>", self.moveUp)
        self.bind("<Down>", self.moveDown)

        self.listboxUp = False

    def update_content_text(self, event):
        w = event.widget
        try:
            index = int(w.curselection()[0])
        except IndexError:
            return
        value = w.get(index)
        clipboard_content = autocompleteList.get(value)[0]
        content['text'] = clipboard_content

    def changed(self, name, index, mode):
        if self.var.get() == '':
            if self.listboxUp:
                content['text'] = ''
                self.listbox.destroy()
                self.listboxUp = False
        else:
            words = self.comparison()
            if words:
                if not self.listboxUp:
                    self.listbox = Listbox(width=self["width"],
                                           height=self.listboxLength,
                                           font=self.listboxFontSize)
                    self.listbox.bind('<<ListboxSelect>>',
                                      self.update_content_text)
                    self.listbox.bind("<Return>", self.selection)
                    self.listbox.place(x=self.winfo_x(),
                                       y=self.winfo_y() + self.winfo_height())
                    self.listboxUp = True

                self.listbox.delete(0, END)
                for w in words:
                    self.listbox.insert(END, w)
                    self.listbox.see(0)  # Scroll!
                    self.listbox.selection_set(first=0)
                    value = self.listbox.get(ACTIVE)

                    clipboard_content = autocompleteList.get(value)[0]
                    content['text'] = clipboard_content
            else:
                if self.listboxUp:
                    content['text'] = ''
                    self.listbox.destroy()
                    self.listboxUp = False

    def selection(self, event):
        if self.listboxUp:
            self.var.set(self.listbox.get(ACTIVE))
            value = self.listbox.get(ACTIVE)
            data = autocompleteList.get(value)
            content = data[0]
            is_command = data[1]
            is_website = data[2]

            if is_command == '1':
                self.execute(content)
            elif is_website == '1':
                self.open_website(content)

            self.listbox.destroy()
            self.listboxUp = False
            self.icursor(END)
            self.copy_value(content)
            self.quit()

    def open_website(self, url):
        webbrowser.open(url)

    def execute(self, command):
        p = subprocess.Popen(command,
                             bufsize=2048,
                             shell=True,
                             stdin=subprocess.PIPE)
        (output, err) = p.communicate()
        p_status = p.wait()

    def copy_value(self, value):
        clipboard.copy(value)

    def moveUp(self, event):
        if self.listboxUp:
            if self.listbox.curselection() == ():
                index = '0'
            else:
                index = self.listbox.curselection()[0]

            if index != '0':
                self.listbox.selection_clear(first=index)
                index = str(int(index) - 1)

                self.listbox.see(index)  # Scroll!
                self.listbox.selection_set(first=index)
                self.listbox.activate(index)
            self.listbox.event_generate("<<ListboxSelect>>", when="tail")

    def moveDown(self, event):
        if self.listboxUp:
            if self.listbox.curselection() == ():
                index = '0'
            else:
                index = self.listbox.curselection()[0]

            if index != END:
                self.listbox.selection_clear(first=index)
                index = str(int(index) + 1)

                self.listbox.see(index)
                self.listbox.selection_set(first=index)
                self.listbox.activate(index)
            self.listbox.event_generate("<<ListboxSelect>>", when="tail")

    def quit(self):
        root.quit()

    def comparison(self):
        return [
            w for w in self.autocompleteList
            if self.matchesFunction(self.var.get(), w)
        ]
示例#17
0
class TkView(object):
    def __init__(self, root):
        self.root = root
        self.columns = 26
        
        button_play = Button(self.root, 
                             text="Play", 
                             command=self.callback_play)
        
        button_stop = Button(self.root, 
                             text="Stop", 
                             command=self.callback_stop)

        button_shutdown = Button(self.root, 
                                 text="Shut down", 
                                 command=self.callback_shutdown)

        button_close = Button(self.root, 
                              text="Close", 
                              command=self.callback_close)

        self.text = Text(self.root, height=1)
        
        scrollbar = Scrollbar(self.root, width=30)
        font = tkFont.Font(size=15)
        self.listbox = Listbox(self.root, 
                               yscrollcommand=scrollbar.set,
                               selectmode=SINGLE,
                               font=font)
        self.listbox.bind("<<ListboxSelect>>", self.callback_stream_selected)
        
        scrollbar.config(command=self.listbox.yview)
        
        button_stop.place(relx=0, rely=0)
        button_play.place(relx=0.18, rely=0)
        button_close.place(relx=0.5, rely=0)
        button_shutdown.place(relx=0.7, rely=0)
        
        scrollbar.place(relx=0.9, rely=0.2, relheight=0.7)
        
        self.listbox.place(relx=0, rely=0.2, relwidth=0.9, relheight=0.7)
        self.text.place(relx=0, rely=0.9)
        self.root.protocol("WM_DELETE_WINDOW", self.callback_close)
    
    def trim_line(self, line):
        ret = line[:(self.columns-3)]
        if len(line.strip()) > self.columns:
            return  ret + '...'
        else:
            return ret

    def highlight_selected_stream(self):
        if self.selected_stream is not None:
            idx = self.stream_urls.index(self.selected_stream['url'])
            self.listbox.selection_set(idx)
            self.listbox.see(idx)
    
    def display_stream_names(self):
        def _insert_stream_name_txt(idx):
            txt = self.streams[idx]['name']
            if txt != '':
                dbg("insert_stream_name_txt: insert loop: idx: %i" %idx)
                self.listbox.delete(idx)
                self.listbox.insert(idx, self.trim_line(txt))
        for idx,stream in enumerate(self.streams):
            if self.streams[idx].has_key('name'):
                self.root.after_idle(_insert_stream_name_txt, idx)
        self.root.after_idle(self.highlight_selected_stream)
示例#18
0
class LeftFrame(BasePAFrame):
    """
    левый фрейм,
    в котором у нас находится список папок
    """

    def __init__(self, *args, **kwargs):
        self.w_frame_child = kwargs.pop('child_frame')

        BasePAFrame.__init__(self, *args, **kwargs)

        self.w_listbox_catalogs = Listbox(self)

        self.current_catalog = settings.BASE_CATALOG
        self.catalogs = []

        # текущий активный каталог, необходим для дабл клика,
        # т.к. переходит фокус
        self.current_catalog_clicked = None

    def _pa_configure(self):
        BasePAFrame._pa_configure(self)

        self.w_listbox_catalogs.bind(
            '<<ListboxSelect>>', self.select_listbox_catalog)

        self.w_listbox_catalogs.bind(
            '<Double-Button-1>', self.select_listbox_catalogs)

        # задаем размеры и положение фреймов
        self.w_listbox_catalogs_rel_x = 0
        self.w_listbox_catalogs_rel_y = 0
        self.w_listbox_catalogs_rel_width = 1
        self.w_listbox_catalogs_rel_height = 1 - self.w_listbox_catalogs_rel_y

    def _pa_layout(self):
        BasePAFrame._pa_layout(self)

        self.w_listbox_catalogs.place(
            relx=self.w_listbox_catalogs_rel_x,
            rely=self.w_listbox_catalogs_rel_y,
            relwidth=self.w_listbox_catalogs_rel_width,
            relheight=self.w_listbox_catalogs_rel_height)

    def set_catalog(self, catalog=None):
        """
        задаем новый корневой каталог
        :param catalog:
        :return:
        """

        catalog = catalog or self.current_catalog

        if not os.path.isdir(catalog):
            return

        if isinstance(catalog, str):
            catalog = catalog.decode('utf-8')

        self.current_catalog = catalog

        if catalog != settings.BASE_CATALOG:
            catalogs = [
                u'{0}{1}'.format(
                    BACK_DIR_PATH,
                    self.current_catalog.replace(settings.BASE_CATALOG, ''))]
        else:
            catalogs = []

        for _catalog in os.listdir(catalog):
            _path = os.path.join(catalog, _catalog)
            if (os.path.isdir(_path) and
                    u'system volume information' not in _path.lower()):
                if any(
                        i for i in os.listdir(_path)
                        if os.path.isdir(os.path.join(_path, i))):
                    prefix = u'+ {0}'
                else:
                    prefix = u'- {0}'
                catalogs.append(prefix.format(_catalog))

        catalogs.sort(key=lambda x: x[PREFIX_LEN:])

        if catalog == settings.BASE_CATALOG or len(catalogs) > 1:
            self.catalogs = catalogs
            self.w_listbox_catalogs.delete(0, END)
            self.w_listbox_catalogs.insert(
                END, *self.catalogs)

    def select_listbox_catalogs(self, event):
        """
        обработчик выбора каталога в списке каталогов, для проваливания внутрь

        :param event:
        :return:
        """
        if self.current_catalog_clicked == self.current_catalog:
            self.set_catalog(os.path.dirname(self.current_catalog))
        else:
            self.set_catalog(
                os.path.join(self.current_catalog_clicked))

    def select_listbox_catalog(self, event):
        """
        обработчик выбора каталога в списке каталогов, для просмотра картинок

        :param event:
        :return:
        """
        try:
            index = self.w_listbox_catalogs.curselection()[0]
            catalog = self.catalogs[index]
        except IndexError:
            return
        else:
            if catalog.startswith(BACK_DIR_PATH):
                self.w_frame_child.set_catalog(self.current_catalog)
                self.current_catalog_clicked = self.current_catalog
            else:
                path = os.path.join(self.current_catalog, catalog[PREFIX_LEN:])
                self.w_frame_child.set_catalog(path)
                self.current_catalog_clicked = path
示例#19
0
class FoodGUI(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent
        
        self.initUI()
        
    def initUI(self):
      
        self.parent.title("Food List Editor")
        self.style = Style()
        self.style.theme_use("default")
        self.pack(fill=BOTH, expand=1)

        self.columnconfigure(1, weight=1)
        self.columnconfigure(3, pad=7)
        self.rowconfigure(4, weight=1)
        self.rowconfigure(5, pad=7)
        
        lbl = Label(self, text="Food List")
        lbl.grid(sticky=W, pady=4, padx=5)
                
        abtn = Button(self, text="Add Food", command=self.sequence)
        abtn.grid(row=1, column=3)

        dbtn = Button(self, text="Delete Food", command=self.delete_food)
        dbtn.grid(row=2, column=3, pady=4)
		
        upbtn = Button(self, text="Refresh", command=self.update_list)
        upbtn.grid(row=3, column=3)

        cbtn = Button(self, text="Close", command=self.close_program)
        cbtn.grid(row=5, column=3)

        scrollbar = Scrollbar(self, orient="vertical")
        self.lb = Listbox(self, width=50, height=20,\
            yscrollcommand=scrollbar.set)
        scrollbar.config(command=self.lb.yview)

        self.make_list()

    def make_list(self):
        while self.lb.size():
            self.lb.delete(0)

        try:
            acts1 = open("food_list.txt")
            acts = acts1.readlines()
            acts1.close()

        except IOError:
            new_list = open("food_list.txt", 'w')
            new_list.close()
            acts1 = open("food_list.txt")
            acts = acts1.readlines()
            acts1.close()

        for i in acts:
            self.lb.insert(END, i)
            
        self.lb.bind("<<ListboxSelect>>")    
            
        self.lb.place(x=5, y=25)

    def sequence(self):
        self.add_food()
        self.update_list()

    def update_list(self):
        del_list = open('food_list.txt')
        del_list2 = del_list.readlines()
        del_list.close()

        new_food_list = open('food_list.txt', 'w')

        for line in del_list2:
            if line != "\n":
                new_food_list.writelines(line)
        new_food_list.close()

        self.make_list()


    def add_food(self):
        if __name__ == '__main__':
            root2 = Tk()
            root2.geometry("500x200+500+300")
            app2 = AddFood(root2, self)
            root2.mainloop()

    def delete_food(self):
        del_f = self.lb.get(ACTIVE)
        del_list = open('food_list.txt')
        del_list2 = del_list.readlines()
        del_list.close()

        new_food_list = open('food_list.txt', 'w')

        for line in del_list2:
            if line != del_f:
                new_food_list.writelines(line)
        new_food_list.close()

        self.update_list()

    def close_program(self):
	    exit(0)
示例#20
0
文件: Peer.py 项目: shanmbic/p2pshare
class Peer(Frame):

    def __init__(self, parent, ip='0.0.0.0', port=5228):
        #self._nick = nick
        Frame.__init__(self, parent) 
        self._addr = get_ip_address('eth0')
        self._port = port
        self._connection_ports = [5229,5230,5231,5232,5233,5234,5235]
        self._peers = []
        self._peers_joined = {}
        self._clients_running ={}
        self._pid = (self._addr , self._port)
        self._buf = 1024
        self._files = []
        self._socket = self.start_server(self._pid)
        self._running = False
        self._threads = []
        self.parent = parent
        self.download_dir = '/'
        self.showfiles = []
        self.initUI()
        self.run()


    def get_pid(self):
        return self._pid

    def start_server(self, pid):
        try:
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.bind(pid)
            sock.settimeout(30)
        except:
            sock=None
        #print "Server started at %s and %s" % pid
        return sock

    def start_pinging(self):
        while self._running:
            time.sleep(3)
            for peers in self._peers_joined.keys():
                conn = self._peers_joined[peers]
                try:
                    data={'type':"Ping"}
                    conn.send(str(data))
                except:
                    pass


    def quit(self):
        quit_flag = False
        for peer in self._peers_joined.keys():
            conn = self._peers_joined[peer]
            data = {'type' : 'Quit'}
            try:
                conn.send(str(data))
                conn.shutdown(2)
                conn.close()
            except:
                pass
        for peer in self._clients_running.keys():
            self._clients_running[peer] = False
        self._running=False
        sock = socket.socket(socket.AF_INET, 
                  socket.SOCK_STREAM)
        i=50000
        while not quit_flag:
            try:
                sock.bind((self._addr, i))
                quit_flag=True
            except:
                i+=1
        sock.connect((self._addr, self._port))
        sock.shutdown(2)
        sock.close()


    def get_peers(self):
        s=''
        for peer in self._peers_joined.keys():
            s+=str(peer[0]) + ':' + str(peer[1])
            s+=','
        return s

    def update_peers(self):
        for peer in self._peers_joined.keys():
            conn = self._peers_joined[peer]
            data = {}
            data['type'] = 'Update'
            data['payload'] = self.get_peers()
            conn.send(str(data).encode())
            time.sleep(5)
            data = {'type':'Filelist', 'payload':'|'.join(self._files)}
            conn.send(str(data).encode())

    def update_filelist(self):
        try:
            with open('filelist', 'r') as f:
                self._files = list(set(pickle.load(f)))
            for x in self._files:
                s=x.replace(os.path.dirname(x), '')
                s=s.replace("/","")
                self.lbfiles.insert(END, s)
                if s not in self.showfiles:
                    self.showfiles.append(s)
            self.lbfiles.update_idletasks()
        except:
            pass

    def read_showfiles(self):
        self.lbfiles.delete(0, END)
        for files in self.showfiles:
            self.lbfiles.insert(END,files)
        self.lbfiles.update_idletasks()
        self.parent.after(1000, self.read_showfiles)
        

    def add_peers(self, peers):
        peers = peers.split(",")
        for peer in peers:
            if peer != '':
                addr , port = peer.split(':')
                if (addr, int(port)) in self._peers:
                    pass
                else:
                    self._peers.append((addr, int(port)))

    def query_file(self):
        filename=str(self.fileSearchEntry.get())
        for peer in self._peers_joined.keys():
            conn = self._peers_joined[peer]
            data = {}
            data['type'] = 'Query'
            data['payload'] = filename
            data['ttl'] = 10
            conn.send(str(data))

    def connect(self):
        ip=str(self.addr_ip_entry.get())
        port=int(self.addr_port_entry.get())
        nick=str(self.addr_nick_entry.get())
        socket_found_flag=False
        if not (ip, port) in self._peers_joined.keys():
            while not socket_found_flag:
                sock_port = self._connection_ports.pop(0)
                conn_sock = self.start_server((self._addr, sock_port))
                if conn_sock != None:
                    socket_found_flag=True
            conn_sock.connect((ip, port))
            msg=conn_sock.recv(self._buf)
            conn_sock.shutdown(2)
            conn_sock.close()
            msg=ast.literal_eval(msg)
            if msg['type']=='Connect':
                conn_sock = self.start_server((self._addr, sock_port))
                addr = msg['payload'].split(":")
                conn_sock.connect((addr[0], int(addr[1])))
                self._peers_joined[(addr[0], addr[1] )]=conn_sock
                self.lbpeers.insert(END, nick+'@'+str(addr[0])+':'+str(addr[1]))
                self.lbpeers.update_idletasks()
                client_thread = threading.Thread(name='Client Thread'+str(addr), target=self.handle_client_connection, args=(conn_sock, (addr[0], int(addr[1]))))
                self._threads.append(client_thread)
                client_thread.start()
            #self.run()
        else:
            print "Already connected"

    def process_query(self, filename, ttl):
        resp = {}
        found_flag = False
        if ttl == 0 :
            resp['result'] = False
            resp['resource_name'] = filename
            resp['size'] = 0
            resp['ttl'] = ttl - 1
            return resp 
        for file_name in self._files:
            if file_name.find(filename)!=-1:
                resp['result'] = True
                resp['resource_name'] = file_name
                resp['size'] = os.path.getsize(file_name)
                found_flag = True
                resp['ttl'] = ttl - 1
                return resp
        resp['result'] = False
        resp['resource_name'] = filename
        resp['size'] = 0
        resp['ttl'] = ttl - 1
        return resp

    def send_file(self, filename, client_conn):
        with open(filename, 'rb') as f:
            chunk = f.read(1024)
            while chunk:
                client_conn.send(chunk)
                chunk = f.read(1024)
            print "File sent"

    def handle_client_connection(self, client_conn, client_pid):
        self._clients_running[client_pid] = True
        print threading.currentThread().getName() , 'Started'
        while self._running and self._clients_running[client_pid]:
            data=''
            while len(data) == 0 and self._clients_running[client_pid]:
                try:
                    data = client_conn.recv(self._buf)
                except:
                    self.statusLabel.config(text="Connection closed by %s" % client_pid)
            print data
            try:
                data=ast.literal_eval(data)
            except:
                data={'type':'corrupt'}
            if data['type'] == 'Update':
                self.statusLabel.config(text="Peer list recieved from %s and %s" % client_pid)
                print data['payload']
                self.add_peers(data['payload'])

            elif data['type'] == 'Filelist':
                for files in data['payload'].split('|'):
                    s=files.replace(os.path.dirname(files), '')
                    s=s.replace("/","")
                    if s not in self.showfiles:
                        self.showfiles.append(s)

            elif data['type'] == 'List':
                payload = self.get_peers()
                data = { 'type' : 'ListREPL', 'payload' : payload}
                client_conn.send(data.encode())

            elif data['type'] == 'ListREPL':
                self.add_peers(data['payload'])

            elif data['type'] == 'Query':
                resp = self.process_query(data['payload'], data['ttl'])
                if resp['result'] == True:
                    payload = resp
                    data = { 'type' : 'QueryREPL', 'payload': payload}
                    client_conn.send(str(data))
                if resp['result'] == False:
                    payload = resp
                    data = { 'type' : 'QueryREPL', 'payload': payload}
                    client_conn.send(str(data))

            elif data['type'] == 'QueryREPL':
                if not data['payload'] == None and data['payload']['result'] == True :
                    data = { 'type':'Fget', 'resource_name': data['payload']['resource_name']}
                    client_conn.send(str(data))

            elif data['type'] == 'Fget':
                data['type'] = 'FgetREPL'
                s=data['resource_name'].replace(os.path.dirname(data['resource_name']), '')
                s=s.replace("/","")
                x=data['resource_name']
                data['resource_name'] = s
                data['size'] = os.path.getsize(x)
                client_conn.send(str(data))
                self.send_file(x, client_conn)

            elif data['type'] == 'FgetREPL':
                with open(self.download_dir + '/' + data['resource_name'], 'w') as f:
                    size=data['size']
                    chunk = 'NonNone'
                    q, rem = divmod(size, self._buf)
                    i=1
                    while chunk and i <= q:
                        chunk = client_conn.recv(self._buf) 
                        f.write(chunk)
                        i+=1
                    chunk = client_conn.recv(rem)
                    f.write(chunk)
                    self.statusLabel.config(text="File download completed %s" % (data['resource_name'],))
                    self._files.append(self.download_dir + '/' + data['resource_name'])

            elif data['type'] == 'Quit':
                print "Client %s quitting" % (client_pid,)
                self._clients_running[client_pid]=False

        self.statusLabel.config( text="%s Exiting" % (threading.currentThread().getName(),))

    def add_files(self, filename):
        if os.path.isfile(filename):
            self._files.append(filename)
            print "File added %s" % (filename,)
            s=filename.replace(os.path.dirname(filename), '')
            self.lbfiles.insert(END, s)
            self.lbfiles.update_idletasks()
        elif not os.path.isfile(filename):
            filename = str(os.cwd()) + filename
            if os.path.isfile(filename):
                self._files.append(filename)
                print "File added %s" % (filename,)
                self.lbfiles.insert(END, filename)
                self.lbfiles.update_idletasks()
            else:
                print "File does not exist"

    def start_listening(self, conn_sock):
        flag=False
        connec , addr = None, None
        while not flag:
            conn_sock.listen(0)
            connec, addr = conn_sock.accept()
            if not addr in self._peers_joined:
                self._peers_joined[addr]=connec
            print self._peers_joined
            self.lbpeers.insert(END, addr)
            self.lbpeers.update_idletasks()
            self.statusLabel.config( text="Connected to %s and %s" % addr)
            self.update_peers()
            flag=True
        return (connec, addr)
    
    def listen_peers(self):
        self._socket.settimeout(None)
        while self._running:
            try:
                connection, addr=self._socket.accept()
            except:
                pass
            if (int(addr[1]) /10)%5000==0:
                break
            else:
                self.statusLabel.config(text="connection recieved from %s and %s" % addr)
                if len(self._connection_ports) != 0:
                    socket_found_flag=False
                    while not socket_found_flag:
                        port=int(self._connection_ports.pop(0))
                        conn_sock = self.start_server((self._addr, port))
                        if conn_sock != None:
                            socket_found_flag=True
                    msg={'type':'Connect', 'payload':str(self._addr)+':'+str(port)}
                    connection.send(str(msg))
                    connection.shutdown(2)
                    connection.close()
                    self.statusLabel.config(text="Started listening on port %s" % (port,))
                    resp = self.start_listening(conn_sock)
                    client_thread = threading.Thread(name='Client Thread'+str(addr), target=self.handle_client_connection, args=(resp[0], resp[1]))
                    self._threads.append(client_thread)
                    client_thread.start()
                #thread.start_new_thread(self.handle_client_connection, (resp[0], resp[1]))
        self._socket.shutdown(2)
        self._socket.close()
        with open('filelist','wb') as f:
            pickle.dump(self._files, f)
        self.statusLabel.config(text='Server shutting down')

    def run(self):
        if self._running == False :
            self._running = True 
        self.statusLabel.config(text="Server started , Waiting for peers")
        self._socket.listen(5)
        listen_thread = threading.Thread(name='Main_listen_thread', target=self.listen_peers)
        self._threads.append(listen_thread)
        listen_thread.start()
        ping_thread = threading.Thread(name='Pinging thread', target=self.start_pinging)
        self._threads.append(ping_thread)
        ping_thread.start()
        self.update_filelist()
        #thread.start_new_thread(self.listen_peers,())


    def initUI(self):
        self.parent.title("P2P Client")
        self.style = Style()
        self.style.theme_use("default")

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

        quitButton = Button(self, text="Quit Server",
            command=self.quit)
        quitButton.place(x=540, y=247)

        labelPeers = Label(self.parent, text="Peers in Network")
        labelPeers.pack()
        labelPeers.place(x=20, y=10)


        self.lbpeers = Listbox(self)   
        self.lbpeers.place(x=20, y=30)


        labelFiles = Label(self.parent, text="Files")
        labelFiles.pack()
        labelFiles.place(x=205, y=10)

        self.lbfiles = Listbox(self)    
        self.lbfiles.place(x=205, y=30)


        labelMessages = Label(self.parent, text="Messages")
        labelMessages.pack()
        labelMessages.place(x=410, y=10)

        self.connectPeerLabel = Label(self.parent, text='Connect to a peer on the P2P Network')
        self.connectPeerLabel.pack()
        self.connectPeerLabel.place(x=395, y=10)
        self.addr_ip_entry = Entry(self.parent, bd=2)
        self.addr_ip_entry_Label = Label(self.parent, text='Enter IP')
        self.addr_port_entry = Entry(self.parent, bd=2)
        self.addr_port_entry_Label = Label(self.parent, text='Enter Port')
        self.addr_nick_entry = Entry(self.parent, bd=2)
        self.addr_nick_entry_Label = Label(self.parent, text='Enter Nick')
        self.addr_ip_entry.pack()
        self.addr_ip_entry_Label.pack()
        self.addr_nick_entry.pack()
        self.addr_nick_entry_Label.pack()
        self.addr_port_entry.pack()
        self.addr_port_entry_Label.pack()
        self.addr_ip_entry_Label.place(x=395,y=30)
        self.addr_ip_entry.place(x=395, y=50)
        self.addr_port_entry_Label.place(x=395, y=75)
        self.addr_port_entry.place(x=395, y=95)
        self.addr_nick_entry_Label.place(x=395, y=120)
        self.addr_nick_entry.place(x=395,y=140)

        connectButton = Button(self, text="Connect Peer",
            command=self.connect)
        connectButton.place(x=395, y=170)

        self.fileSearchLabel = Label(self.parent, text='Enter File name to search')
        self.fileSearchEntry = Entry(self.parent, bd=2)
        self.fileSearchButton = Button(self, text="Search", command=self.query_file)
        self.fileSearchLabel.pack()
        self.fileSearchEntry.pack()
        self.fileSearchLabel.place(x=20, y=230)
        self.fileSearchEntry.place(x=20, y=250)
        self.fileSearchButton.place(x=205, y=247)

        fileOpenButton = Button(self, text="Add File", command=self.onOpen)
        fileOpenButton.place(x=205, y=200)

        serverInfoLabel = Label(self.parent, text='Server running at IP:%s , Port:%s' % (self._pid))
        serverInfoLabel.pack()
        serverInfoLabel.place(x=330, y=205)

        self.statusLabel = Label(self.parent)
        self.statusLabel.pack()
        self.statusLabel.place(x=10, y=300)

        dirselectButton = Button(self, text='Download location', command=self.setDir)
        dirselectButton.place(x=300, y=247)
        self.parent.after(1000, self.read_showfiles)


    def setDir(self):
        self.download_dir = tkFileDialog.askdirectory()
        self.statusLabel.config(text="Download directory set to:%s" % (self.download_dir,))

    def onOpen(self):
        ftypes = [('All files', '*')]
        dlg = tkFileDialog.Open(self, filetypes = ftypes)
        fl = dlg.show()
        self.add_files(fl)
示例#21
0
class ChatMainForm(Template):
    '''
    Class for graphic presentation of chat client.
    Main form with chat, list of created games, button for creating game.
    If you created game button becomes start game.
    ChatMainForm form with textbox, entry, listbox and button.
    '''
  
    def __init__(self, parent,name):
        '''
        Initialize all gui components...
        
        parent represents root of tk window
        name is  name that client entered
        
        Creates instance of client class and starts thread for receiving messages
        '''
        Template.__init__(self, parent)  
        
        self.client = ChatClient.ChatClient()
        #where to put try block here or in connect method
        self.client.connect_to_server()
          
        self.end = False #for stopping receiving thread 
        self.name = name
      
        #start new thread
        self.thread=thread.start_new_thread( self.receive_server_messages, (1,) )#!!!doesn't work without second argument
        
        #send first message with name
        self.client.send_message(self.name)
        
        self.parent = parent  
        
        
             
        self.initUI()
        
    def initUI(self):
        '''
        Initialize all gui components
        '''
        
        self.nameText = Label(self, text="Chat")
        self.nameText.place(x=270, y=10)
        self.nameText3 = Label(self, text="Players in game")
        self.nameText3.place(x=50,y=10)
        self.nameText2 = Label(self, text="Game list            ")# **********Popravi ovo!!!!!!********
        self.nameText2.place(x=50,y=10)
       
        
        #display chat messages
        self.messageDispley = Text(self,font=tkFont.Font(family="Calibri",size=10),width=28,height=13)
        self.messageDispley.place(x=270, y=40)
        self.messageDispley.insert(END,"Welcome...\n")
        
        #write text messages
        self.message = StringVar()
        self.messageText =Entry(self, textvariable=self.message, width=28)
        self.messageText.place(x=270, y=275)
        
        #send chat massage
        self.nameButton = Button(self, text="Send", width=26, command=self.send_chat_message)
        self.nameButton.place(x=270, y=300)
        
        #lists players in specific game
        self.playersList = Listbox(self)
        self.playersList.place(x=50, y=30)
        
        #lists all games
        self.gameList = Listbox(self)
        self.gameList.place(x=50, y=30)

        #join created game
        self.joinGameButton = Button(self,text="Join game",width=15, command=self.send_join_message)
        self.joinGameButton.place(x=50, y=230)
        
        #start created game
        self.startGameButton = Button(self,text="Start game",width=15, command=self.send_game_start_message)
        self.startGameButton.place(x=50, y=270)
        
        #create new game
        self.createGameButton = Button(self,text="Create new game",width=15, command=self.create_new_game)
        self.createGameButton.place(x=50, y=270)
        
     
    def send_game_start_message(self):
        '''
        Sends signal to server that game is starting
        '''        
        self.startGameButton.config(state=DISABLED)
        self.client.send_message("Start game")
        
    def send_join_message(self):
        '''
        Hides 'create new game' and 'Join game'  buttons and 
        shows 'Players list' listbox.
        Send message with selected game to server
        '''
        #first we think you can join
        self.canJoin = True
        
        items = self.gameList.curselection()  
        #if nothing is selected
        if items == tuple():
            return
        # creating xml document to be send
        root2 = etree.Element("JoinGame")
        ge = etree.SubElement(root2, "game").text =  self.gameList.get(items[0])  
        
        self.client.send_message(etree.tostring(root2))
        #join massage send 
        self.joinEvent.clear()
        #first receive_server_messages thread needs to finish processing message from server        
        self.joinEvent.wait()
        print "BUHA"
        #if we don't receive message from server we hide fields 
        if self.canJoin:
            self.joinGameButton.place_forget()
            self.createGameButton.place_forget()
            self.gameList.place_forget()
            self.nameText2.place_forget()
            self.startGameButton.place_forget()
                 
    def create_new_game(self):
        '''
        Hides 'create new game' and 'Join game'  buttons and 
        shows 'Start game' button and 'Players list' listbox.
        '''
        self.joinGameButton.place_forget()
        self.createGameButton.place_forget()
        self.gameList.place_forget()
        self.nameText2.place_forget()
        self.startGameButton.place(x=50, y=270)
        #can't start until somebody joins
        self.startGameButton.config(state=DISABLED)
        self.client.send_message("Create game")
        
         
    def send_chat_message(self):
        '''
        sends chat message to server
        if message is 'Bye' ends program**to be changed**
         
        '''
        
        # creating xml document to be send
        root2 = etree.Element("ChatMessage")
        etree.SubElement(root2, "message").text = self.message.get()
        
        self.client.send_message(etree.tostring(root2))
        
        if self.message.get() =='Bye':
            print 'sss'
            self.client.comSocket.close
            self.end = True
            self.parent.destroy()   
                     
        self.message.set('')   
        
    
    def find_next_player_index(self,currentPlayerIndex):
        '''
        finds index of next player on turn in playersList
        '''
        index = currentPlayerIndex + 1
        if index == len(self.game.playersList):
            index = 0
        
        while index != currentPlayerIndex:
            #print self.game.playersList[index].isOut
            #print type(self.game.playersList[index].isOut)
            if index ==  len(self.game.playersList):
                index = 0
            if str(self.game.playersList[index].isOut) == 'false':
                #print 'aaaaaaaaa'
                break
            else:
                index += 1;
        #print index
        return index
            
   
    def start_game(self,id):
        
        try:
            white = (255, 255, 255)
            # Call this function so the Pygame library can initialize itself
            pygame.init()
            # Create an 800x600 sized screen
            self.screen = pygame.display.set_mode([800, 600])
            # This sets the name of the window
            pygame.display.set_caption('Fingers game')
            clock = pygame.time.Clock()
            done = False
            firstClick = True
            secondClick = False
            # waits until process_message finish with game object   
            self.gameStateEvent.wait()
                     
            currentPlayer = self.game.playersList[self.game.ourIndex];
            ourField = currentPlayer.field
            nextField = None
                         
            
            hitting = None
            hitted  = None
          
            print "AAAAAAAAAAA"
            while done == False:
              
                clock.tick(10)
                nextIndex = self.find_next_player_index(self.game.ourIndex)
                nextPlayer = self.game.playersList[nextIndex]
                nextField = nextPlayer.field
                for event in pygame.event.get():
                    if event.type == pygame.QUIT:
                        #enable all filed for choosing game
                      
                        self.createGameButton.place(x=50, y=270)
                        self.joinGameButton.place(x=50, y=230)
                        self.nameText2.place(x=50,y=10)
                        self.gameList.place(x=50, y=30)
                        self.initialGameState = True
                        self.game = None
                        
                        self.client.send_message("QUIT")
                        pygame.quit()
                    
                    if event.type == pygame.MOUSEBUTTONDOWN:
                        x, y = event.pos
                        # if game is over we can't play
                       
                        if self.game.gameOver == 'false':
                        
                            if self.client.comSocket.getsockname()[1] == self.game.playerTurn:
                                if firstClick:
                                    # check if left hand picture is clicked
                                    if ourField.image1.get_rect(center=ourField.get_centers()[0]).collidepoint(x, y):
                                        hitting = 'left'
                                        firstClick = False
                                        secondClick = True
                                    # check if right hand picture is clicked
                                    elif ourField.image2.get_rect(center=ourField.get_centers()[1]).collidepoint(x, y):
                                        hitting = 'right'
                                        firstClick = False
                                        secondClick = True
                                elif secondClick:
                                    # check if left hand picture is clicked
                                    if nextField.image1.get_rect(center=nextField.get_centers()[0]).collidepoint(x, y) and nextPlayer.fingersLeft != 0:
                                        hitted = 'left'
                                        secondClick = False
                                        #this turn over reset firstClick and secondClick
                                        firstClick = True
                                        secondClick = False
                                        
                                        self.send_move_message(hitting, hitted)
                                    # check if right hand picture is clicked
                                    elif nextField.image2.get_rect(center=nextField.get_centers()[1]).collidepoint(x, y) and nextPlayer.fingersRight != 0:
                                        
                                        hitted = 'right'
                                        secondClick = False
                                        #this turn over reset firstClick and secondClick
                                        firstClick = True
                                        secondClick = False
                                        self.send_move_message(hitting, hitted)
                                    #check if second hand is from same player and if separation is possible
                                    elif ourField.image1.get_rect(center=ourField.get_centers()[0]).collidepoint(x, y):
                                                                            
                                        if currentPlayer.fingersRight == 0 and (currentPlayer.fingersLeft == 2 or currentPlayer.fingersLeft == 4):                                       
                                            hitted = 'separation'
                                            secondClick = False 
                                            print "SANJA"
                                            #this turn over reset firstClick and secondClick
                                            firstClick = True
                                            secondClick = False
                                            self.send_move_message(hitting, hitted)
                                        else:
                                            firstClick = True
                                    elif ourField.image2.get_rect(center=ourField.get_centers()[1]).collidepoint(x, y):
                                        print "BUHA1"
                                        print currentPlayer.fingersLeft
                                        
                                        if currentPlayer.fingersLeft == 0 and (currentPlayer.fingersRight== 2 or currentPlayer.fingersRight == 4):                                       
                                            print "SANJA"
                                            hitted = 'separation'
                                            secondClick = False 
                                            #this turn over reset firstClick and secondClick
                                            firstClick = True
                                            secondClick = False
                                            self.send_move_message(hitting, hitted)
                                        else:
                                            firstClick = True
                                    
                                    
                                                                
                       
                #write text on screen
                myfont = pygame.font.SysFont("Comic Sans MS", 20)
                winnerFont = pygame.font.SysFont("Comic Sans MS", 36)
                #refresh screen
                self.screen.fill((0, 0, 0))
                
                if self.game.gameOver == 'true':
                    if not self.all_out():
                        labelWinner = winnerFont.render("**** Game over ****", 1, white)
                        labelWinner2 = winnerFont.render("**** somebody left :( *****", 1, white)
                    else:
                        labelWinner = winnerFont.render("*****Winner is " + self.return_winner_name() + " *****", 1, white)
                        labelWinner2 = winnerFont.render(" ", 1, white)
                    self.screen.blit(labelWinner, (180, 220))
                    self.screen.blit(labelWinner2, (180, 250))
                label1 = myfont.render("You: " + self.game.playersList[self.game.ourIndex].playerName, 1, white)
                label2 = myfont.render("Players turn: " + self.game.playersList[self.game.find_index(self.game.playerTurn)].playerName, 1, white)
                
                #add text
                self.screen.blit(label1, (40, 450))
                self.screen.blit(label2, (40, 480))       
                #draw hands         
                self.game.draw_state(self.screen)
                pygame.display.flip()
                
        except:
            traceback.print_exc()
            
    
    def all_out(self):
        '''
        checks if only one player
        is left in game
        '''
        return len([x for x in self.game.playersList if x.isOut == 'false']) == 1
    
    def return_winner_name(self):
        '''
        returns winers name
        '''
        return next(x.playerName for x in self.game.playersList if x.isOut == 'false')
    
    def send_move_message(self,hitting,hitted):
        '''
        creates and sends move message
        based on hitting and hitted hands
        '''
        xmlroot = etree.Element("Move")
        etree.SubElement(xmlroot, "playerPlayed").text = str(self.game.playerTurn)
        etree.SubElement(xmlroot, "hittingHand").text = hitting
        etree.SubElement(xmlroot, "hittedHand").text = hitted
        print etree.tostring(xmlroot)
        self.client.send_message(etree.tostring(xmlroot))
        
    def process_message(self):
        '''
        
        Recieve xml data as parameter and calls appropriate methods 
        for specific type of messges
        '''
                
        messageType = self.root.tag
        
        if messageType == "ChatMessage":
            self.messageDispley.insert(END,self.root[0].text+'\n')
            # if game is full we receive message and set shared object canJoin to false 
            if self.root[0].text.startswith('Unable to join'):
                print "SANJA"
                self.canJoin = False
                #unable to join massage processed so enable joinEvent, 
                self.joinEvent.set()
                
            #trying to start game ****TO BE CHANGED***
            if self.root[0].text.startswith('Start game'):
                self.game = None
                self.gameThread = thread.start_new_thread(self.start_game, (2,))
                
        elif messageType == "ListOfGames":
            #****Mora posebna metoda koja nema parametre jedino tako radi***
            self.list_all_games(self.gameList)
        elif messageType == "ListOfPlayers":
            
            self.list_all_games(self.playersList)
            #if there is more then tow players in game enable startGameButton
            if len(self.playersList.get(0, END)) > 1:
                self.startGameButton.config(state=NORMAL)
         
        elif messageType == "GameState":
            if self.initialGameState:
                self.gameStateEvent.clear()
                self.game = GameState(self.root,self.client.comSocket.getsockname()[1])
                self.gameStateEvent.set()
                self.initialGameState = False
            else:
               
                self.game.changeGameState(self.root)
                print str(self.game.playersList[self.game.ourIndex].fingersRight) + '->' + self.game.playersList[self.game.ourIndex].playerName
                
            
        else:
            print "Error while processing massages"
        
    def list_all_games(self,listBox):
        '''
        Reads all <game> elements from xml
        and shows them in gameList listbox
        '''
        #******Ovov nekad radi nekad ne*********
        lis = []
        print self.root[0]
        for el in iter(self.root[0]):
            lis.append(el.text)
        
        listBox.delete(0, END)
        for e in lis:
            #t = e.text
            listBox.insert(END,e)
        
    
    def receive_server_messages(self,id):
        '''
        receives messages while main thread is running
        
        '''
        
        #event must be defined here because in process_message we 
        # create another event for every message, no good.
        self.gameStateEvent = threading.Event()
        #creating event for disabling thread while event is not set
        self.joinEvent = threading.Event()
        
        self.initialGameState = True
        
        while not self.end:
            try:
                mes = self.client.comSocket.recv(1024)
                # http://lxml.de/tutorial.html
                print mes + '*****'
                self.root = etree.fromstring(mes) 
                
                self.gameStateEvent.clear()
                self.process_message()
                #massage processed so enable joinEvent,
                self.joinEvent.set()
              
                
            except:
                
                traceback.print_exc()
示例#22
0
class CenterFrame(BasePAFrame):
    """
    фрейм со списком файлов
    """

    def __init__(self, *args, **kwargs):
        self.w_frame_child = kwargs.pop('child_frame')

        BasePAFrame.__init__(self, *args, **kwargs)

        self.w_listbox_files = Listbox(self)
        self.w_scrollbar_files = Scrollbar(self)

        self.catalog = None
        self.catalog_files = []

    def _pa_configure(self):
        BasePAFrame._pa_configure(self)

        self.w_listbox_files.config(yscrollcommand=self.w_scrollbar_files.set)
        self.w_scrollbar_files.config(command=self.w_listbox_files.yview)

        self.w_listbox_files.bind(
            '<<ListboxSelect>>', self.select_listbox_file)

    def _pa_layout(self):
        BasePAFrame._pa_layout(self)

        w_listbox_files_width = 0.95
        self.w_listbox_files.place(
            relx=0,
            rely=0,
            relwidth=w_listbox_files_width,
            relheight=1)
        self.w_scrollbar_files.place(
            relx=w_listbox_files_width,
            rely=0,
            relwidth=1-w_listbox_files_width,
            relheight=1)

    def set_catalog(self, catalog=None):
        """
        задаем новый каталог для отображения

        :param catalog: словарь
            {
                'path': путь к каталогу
            }
        :return:
        """

        try:
            current_index = self.w_listbox_files.curselection()[0]
        except IndexError:
            current_index = 0

        if 0 < current_index < len(self.catalog_files):
            set_index = current_index + 1
        else:
            set_index = current_index

        self.catalog = catalog
        self.catalog_files = []
        self.w_listbox_files.delete(0, END)
        self.w_frame_child.set_file(None)

        if self.catalog is not None:
            catalog_path = self.catalog

            for file_name in os.listdir(catalog_path):
                file_path = os.path.join(catalog_path, file_name)
                if os.path.isfile(file_path):
                    self.catalog_files.append({
                        'name': file_name,
                        'path': file_path})
            self.catalog_files.sort(key=lambda x: x['name'])
            catalog_files = [catalog['name'] for catalog in self.catalog_files]
            self.w_listbox_files.insert(END, *catalog_files)

            self.w_listbox_files.selection_set(set_index)
            self.w_listbox_files.see(set_index)
            self.w_listbox_files.event_generate("<<ListboxSelect>>")

    def update_catalog(self):
        self.set_catalog(self.catalog)

    def select_listbox_file(self, event):
        """
        обработчик выбора файла в списке файлов

        :param event:
        :return:
        """
        try:
            index = self.w_listbox_files.curselection()[0]
            file_ = self.catalog_files[index]
        except IndexError:
            return
        else:
            self.w_frame_child.set_file(file_)
示例#23
0
class Example(Frame):
  
    def __init__(self, parent):
        Frame.__init__(self, parent)   
         
        self.parent = parent        
        
      
        self.parent.title("Jo Ion Picker") 
        
        self.pack(fill=BOTH, expand=1)

        self.compounds = deisotope(filename=input_file)
        
        self.error_label = Label(self, text="Error in ppm")     
        self.error_label.place(x=20, y=730)

        self.entry = Entry(self, text='error in ppm')
        self.entry.place(x=20, y=750)
        self.entry.insert(10,'5')
        self.b = Button(self, text="ReCalc Error", width=15, \
                        command=self.callback)
        self.b.place(x=20, y=770)

        self.b_output = Button(self, text="Export", width=10, command=self.write_output)
        self.b_output.place(x=20, y=800)

        #self.b_output = Button(self, text="Allowed", width=10, command=self.only_allowed_ions)
        #self.b_output.place(x=20, y=830)


        self.gaps=IntVar()
        self.check_gaps = Checkbutton(self, text='Remove Gaps', variable=self.gaps,onvalue=1, offvalue=0, command=self.remove_gaps_call)
        #self.check.pack()
        self.check_gaps.place(x=20, y=830)


        self.scrollbar = Scrollbar(self, orient=VERTICAL)
        self.lb = Listbox(self, height=46, yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.lb.yview)
        self.scrollbar.pack(side=LEFT, fill=Y)

        
        for compound in self.compounds:
            print "found", compound.get_base_peak()
            mzs = compound.get_mz_list()
            num_mzs = len(mzs)
            entry = str(mzs[0]) + "    " + str(num_mzs)
            self.lb.insert(END, entry)
            
            
        self.lb.bind("<<ListboxSelect>>", self.onSelect)    
            
        self.lb.place(x=20, y=20)
        

        self.var = StringVar()
        #self.label = Label(self, text=0, textvariable=self.var)        
        #self.label.place(x=20, y=710)

        self.mz_label = Label(self, text="M/Z        Num Ions")
        self.mz_label.place(x=20, y=0)

        f = Figure(figsize=(8,11), dpi=100)
        self.ax = f.add_subplot(111)
        mass_list = self.compounds[0].get_mz_list()
        print mass_list
        intensity_list = self.compounds[0].get_intensity_list()
        mass_spec_plot = self.ax.bar(mass_list, intensity_list,\
        width=0.05)
        min_mz = mass_list[0]
        max_mz = mass_list[-1]
        self.ax.set_xlim([min_mz-1, max_mz+1])
        self.ax.set_ylim([0, 1.1*max(intensity_list)])
        self.ax.set_xticks(mass_list)
        self.ax.set_xticklabels(mass_list, rotation=45)
        self.ax.set_title("Base Ion:" + str(mass_list[0]))

        self.canvas = FigureCanvasTkAgg(f, master=self)
        self.canvas.show()
        self.canvas.get_tk_widget().pack(side=RIGHT)

    def onSelect(self, val):
      
        sender = val.widget
        idx = sender.curselection()
        value = sender.get(idx)   

        self.var.set(value)

        mz_to_search = value.split()[0]

        self.ax.clear()
        for i, compound in enumerate(self.compounds):
            if float(mz_to_search) == compound.get_base_peak():
                index = i
        mass_list = self.compounds[index].get_mz_list()
        print mass_list
        intensity_list = self.compounds[index].get_intensity_list()
        mass_spec_plot = self.ax.bar(mass_list, intensity_list,\
        width=0.05)
        min_mz = mass_list[0]
        max_mz = mass_list[-1]
        self.ax.set_xlim([min_mz-1, max_mz+1])
        self.ax.set_ylim([0, 1.1*max(intensity_list)])
        self.ax.set_xticks(mass_list)
        self.ax.set_xticklabels([str(mass) for mass in mass_list], rotation=45)
        self.ax.set_title("Base Ion:" + str(mass_list[0]))
        
        self.canvas.draw()

    def only_allowed_ions(self):

        ion_list = []

        fp = open('ions.csv', 'r')
        lines = fp.readlines()
        for line in lines:
            ion_list.append(float(line))
        #print ion_list
            
        self.compounds = deisotope(filename=input_file,max_error = float(self.entry.get()))

        new_compound_list = []
        

        for compound in self.compounds:
            for ion in ion_list:
                error_Da = float(self.entry.get())*compound.get_base_peak()/1e6
                if compound.get_base_peak() > ion-error_Da \
                   and compound.get_base_peak() < ion + error_Da:
                    new_compound_list.append(compound)

        for compound in new_compound_list:
            print "compound:",compound.get_base_peak()
        
        self.lb.delete(0, END)
        for compound in new_compound_list:
            mzs = compound.get_mz_list()
            num_mzs = len(mzs)
            entry = str(mzs[0]) + "    " + str(num_mzs)
            self.lb.insert(END, entry)
        
        

    def callback(self):
        self.compounds = deisotope(filename=input_file, max_error = float(self.entry.get()))
        self.lb.delete(0, END)
        for compound in self.compounds:
            mzs = compound.get_mz_list()
            num_mzs = len(mzs)
            entry = str(mzs[0]) + "    " + str(num_mzs)
            self.lb.insert(END, entry)
        print self.entry.get()


    def remove_gaps_call(self):
        self.compounds = deisotope(filename=input_file,max_error = float(self.entry.get()))
        check_for_gaps(self.compounds)
        self.lb.delete(0, END)
        for compound in self.compounds:
            mzs = compound.get_mz_list()
            num_mzs = len(mzs)
            entry = str(mzs[0]) + "    " + str(num_mzs)
            self.lb.insert(END, entry)
        print self.entry.get()


    def do_list_update(self):
        l_multi = self.multi.get()
        l_missing = self.missing.get()
        l_m1gtm2 = self.m1gtm2.get()
        #  possible situations: 000, 001,010,100, 011,101, 110, 111
        if l_multi == 0 and l_missing == 0 and l_m1gtm2 ==0:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                num_mzs = len(mzs)
                entry = str(mzs[0]) + "    " + str(num_mzs)
                self.lb.insert(END, entry)
                
        elif l_multi == 0 and l_missing == 0 and l_m1gtm2 ==1:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                num_mzs = len(mzs)
                intensities = compound.get_intensity_list()
                if intensities[-1] <= intensities[0]:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                    
        elif l_multi == 0 and l_missing == 1 and l_m1gtm2 ==0:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                num_mzs = len(mzs)
                if mzs[-1] - mzs[0] <1.75: # margin of error allowed here
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                    
        elif l_multi == 1 and l_missing == 0 and l_m1gtm2 ==0:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                num_mzs = len(mzs)
                if num_mzs >1:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                    
        elif l_multi == 0 and l_missing == 1 and l_m1gtm2 ==1:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                intensities = compound.get_intensity_list()
                num_mzs = len(mzs)
                if mzs[-1] - mzs[0] <1.75 and intensities[-1] <= intensities[0]:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                
        elif l_multi == 1 and l_missing == 0 and l_m1gtm2 ==1:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                intensities = compound.get_intensity_list()
                num_mzs = len(mzs)
                if num_mzs >1 and intensities[-1] <= intensities[0]:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                
        elif l_multi == 1 and l_missing == 1 and l_m1gtm2 ==0:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                num_mzs = len(mzs)
                if num_mzs >1 and mzs[-1] - mzs[0] <1.75:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
                
        elif l_multi == 1 and l_missing == 1 and l_m1gtm2 ==1:
            self.lb.delete(0, END)
            for compound in self.compounds:
                mzs = compound.get_mz_list()
                intensities = compound.get_intensity_list()
                num_mzs = len(mzs)
                if num_mzs >1 and mzs[-1] - mzs[0] <1.75 and \
                    intensities[1] <= intensities[0]:
                    entry = str(mzs[0]) + "    " + str(num_mzs)
                    self.lb.insert(END, entry)
        else:
            pass # error!
            

    def write_output(self):
        op = open('edited_output.csv', 'w')

        op.write('mz, intensity, mz, intensity, mz, intensity\n')
        items = self.lb.get(0,END)
        output_list = []
        for item in items:
            mz_val = item.split(' ')[0]
            for compound in self.compounds:
                if float(mz_val) == compound.get_base_peak():
                    mzs = compound.get_mz_list()
                    intensities = compound.get_intensity_list()
                    for i, mz in enumerate(mzs):
                        op.write(str(mz) + ',' + str(intensities[i]) + ',')
                    op.write('\n')
        op.close()