def __initUi(self): self.master.title('Shine Production') self.pack(fill=BOTH, expand=1) Style().configure("TFrame", background="#333") #Status frame self.status_frame = LabelFrame(self, text='Status', relief=RIDGE, width=800, height=500) self.status_frame.place(x=20, y=20) #QRFrame self.path_frame = LabelFrame(self, text='QR Serial Code', relief=RIDGE, height=60, width=225) self.path_frame.place(x=400, y=550) entry = Entry(self.path_frame, bd=5, textvariable=self.serial_num) entry.place(x=50, y=5) #START self.start_button = Button(self, text="Start", command=self.start, height=4, width=20) self.start_button.place(x=100, y=550)
def search_user_window(): root.geometry('250x185') global userlabel, ranklabel, promlabel, skine, skinl, skinb, lastpromo, currerank, namelabel, promoterl, oldrankla, promotera, oldrankal userlabel = Label(root, text="") ranklabel = Label(root, text="") promlabel = Label(root, text="") promotera = Label(root, text="") oldrankal = Label(root, text="") namelabel = Label(root, text="Username:"******"Arial 9 bold") lastpromo = Label(root, text="Last Promo:", font="Arial 9 bold") currerank = Label(root, text="Current Rank:", font="Arial 9 bold") promoterl = Label(root, text="Promoter:", font="Arial 9 bold") oldrankla = Label(root, text="Old Rank:", font="Arial 9 bold") namelabel.grid(row=0, sticky=W) userlabel.grid(row=0, sticky=E) currerank.grid(row=1, sticky=W) ranklabel.grid(row=1, sticky=E) lastpromo.grid(row=2, sticky=W) promlabel.grid(row=2, sticky=E) promoterl.grid(row=3, sticky=W) promotera.grid(row=3, sticky=E) oldrankla.grid(row=4, sticky=W) oldrankal.grid(row=4, sticky=E) skine = Entry(root) skinl = Label(root, text="Type a username") skinb = Button(root, text="Search", command=search_user) skinl.place(relx=0.72, x=1, y=105, anchor=NE) skine.place(relx=0.76, x=1, y=130, anchor=NE) skinb.place(relx=0.6, x=1, y=155, anchor=NE) skine.focus_set()
def __initUi(self): self.master.title('Shine Production') self.pack(fill=BOTH, expand=1) Style().configure("TFrame", background="#333") #Status of Test frame self.status_frame = LabelFrame(self, text='Status', relief=RIDGE, width=800, height=500) self.status_frame.place(x=20, y=20) #QR SERIAL # Frame self.path_frame = LabelFrame(self, text='QR Serial Code', relief=RIDGE, height=60, width=235) self.path_frame.place(x=400, y=550) entry = Entry(self.path_frame, bd=5, textvariable=self.serial_num_internal) entry.place(x=50, y=5) #TEST RESULTS LABEL w = Label(self.status_frame, textvariable=self.results) w.place(x=50, y=50) #START Button self.start_button = Button(self, text="Start", command=self.start, height=4, width=20) self.start_button.place(x=100, y=550) # Initialize the DUT initDUT()
def displayDailyDouble(self,question,player_name,player_score): self.canvas.pack_forget() dd_screen = [True] dd_canvas = utils.JCanvas(self.frame,bg=utils.bg_blue) dd_canvas.pack(fill=BOTH, expand=True) dd_canvas.writeText(50,50,"daily_double_font",fill="red",text="DAILY DOUBLE: "+player_name+" ($"+str(player_score)+")", anchor=W) dd_canvas.writeText(50,200,"daily_double_category_font",fill="white",text=question.category, anchor=W) def revert(): dd_canvas.destroy() self.canvas.pack(fill=BOTH, expand=True) if player_name not in self.player_names: self.canvas.after(5000,revert) return e = Entry(dd_canvas) e.place(x=600,y=400) def temp_controller(event): if event.char == 's': bool = dd_screen[0] forget_canvas = dd_canvas if bool else self.canvas paint_canvas = dd_canvas if not bool else self.canvas forget_canvas.pack_forget() paint_canvas.pack(fill=BOTH, expand=True) dd_screen[0] = not bool self.parent.bind_all("<Key>", temp_controller) def daily_double_key_controller(event): char = event.char if char == 'n': state.awardQuestion(self.player_names.index(player_name),wrong=True) if char == 'y': state.awardQuestion(self.player_names.index(player_name),wrong=False) if char == 'n' or char == 'y': self.parent.bind_all("<Key>", key_controller) dd_canvas.destroy() self.canvas.pack(fill=BOTH, expand=True) state.switchWindows() state.showQuestion() if char == 'a': state.showQuestion(toggle=True) def placeBet(): try: bet = int(e.get()) except ValueError: e.insert(0,"not a number") return if bet < 0 or (bet > 2000 and bet > player_score): e.insert(0,"invalid bet") return question.value = bet self.parent.bind_all("<Key>", daily_double_key_controller) e['state'] = DISABLED state.switchWindows() b = Button(dd_canvas, text="Place Bet", width=10, command=placeBet) b.place(x=600,y=450)
def can_I(): global canla, canie, canil, canib root.geometry('200x125') canla = Label(root, text="", font="Arial 28 bold ") canie = Entry(root) canil = Label(root, text="Type a username") canib = Button(root, text="Can I promote them?", command=can_I_prom) canla.pack() canie.place(relx=0.8, x=1, y=75, anchor=NE) canib.place(relx=0.792, x=1, y=96, anchor=NE) canil.place(relx=0.73, x=1, y=53, anchor=NE)
def initUI(self): self.parent.title("Calendar Entry") self.style = Style() self.style.theme_use("alt") self.pack(fill = BOTH, expand = 1) quitButton = Button(self, text = "Quit", command = self.quit) quitButton.place(x = 425, y = 475) # def googleLogin(self): entry = Entry(self) entry.place(x = 200, y = 70) username = entry.get()
def class_create(): def add_class(): try: curser.execute("use CS350deneme") curser.execute("select * from courses") recourses = curser.fetchall() for i in recourses: if e1.get() == str(i[0]): raise NameError value = e1.get() curser.execute("INSERT INTO courses(cid) VALUES ('%s')" % (value)) database.commit() added.config(text="Class Created", fg="black", font=("bold", 20)) except: added.config(text="Class already exist", fg="black", font=("bold", 20)) R2.destroy() global R7 R7 = Toplevel(main_screen) R7.resizable(width=FALSE, height=FALSE) R7.geometry("385x650") R7.title('MAKE NEW CLASS') lb1 = Label(R7, text="Class Name", font=("bold", 15)) lb1.place(x=50, y=200) global e1 e1 = Entry(R7, width=15, font=("bold", 15), highlightthickness=2) e1.place(x=180, y=200) b1 = Button(R7, text="ADD", width=32, height=2, bg="turquoise4", fg="white", font="5", relief=RAISED, overrelief=RIDGE, command=add_class) b1.place(x=50, y=300) def back(): R7.destroy() home() back = Button(R7, text="HOME", bg="turquoise4", fg="white", command=back) back.place(x=300, y=30) added = Label(R7, font=("bold", 15)) added.place(x=50, y=400)
class ChatMainForm(Template): ''' Class for graphic presentation of chat client. ChatMainForm form with textbox and entry. ''' def __init__(self, parent,name): Template.__init__(self, parent) self.client = ChatClient.ChatClient() #where to put try block here or in connect method self.client.connect_to_server() self.name = name self.client.send_message(self.name+'\n') 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.messageDispley = Text(self,font=tkFont.Font(family="Calibri",size=10),width=30,height=15) self.messageDispley.place(x=270, y=40) self.messageDispley.insert(END,self.name) self.message = StringVar() self.messageText =Entry(self, textvariable=self.message, width=35) self.messageText.place(x=270, y=275) self.nameButton = Button(self, text="Continue", width=30, command=self.send_message) self.nameButton.place(x=270, y=300) def send_message(self): self.client.send_message(self.message) self.message.set('')
def get_City(): Get_city_window = tk.Toplevel() Get_city_window.title('查询接口支持的国内外城市或地区信息') Get_city_window.geometry('300x600') Get_city_window.resizable(False, False) input_Lable = tk.Label(Get_city_window,text='请输入一个城市:').place(x=0,y=0) input_City = Entry(Get_city_window) input_City.place(x=100,y=0) a = input_City.get() City_B = tk.Button(Get_city_window,text='查询',command=CityAre).place(x=0,y=20) input_Text = Text(Get_city_window,height=60).place(x=0,y=45) Get_city_window.mainloop()
def readcataloguename(self): Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing # show an "Open" dialog box and return the path to the selected file filename = askopenfilename(initialdir=os.path.abspath(os.curdir), title='Select RADEC file', filetypes=(('RADEC files', '*.radec'), ('all files', '*.*'))) #print(filename) self.catVar.set(filename) catvalue = Entry(self.master, textvariable=self.catVar, width=28, justify='right') catvalue.place(relx=0.02, rely=0.295, anchor="w")
def get_weather_info(): Get_weather_window = tk.Toplevel() Get_weather_window.title('查询指定城市未来3天的天气情况') Get_weather_window.geometry('350x600') #Get_weather_window.resizable(False, False) input_Lable = tk.Label(Get_weather_window,text='请输入一个城市:').place(x=0,y=0) input_City = Entry(Get_weather_window) input_City.place(x=100,y=0) e = input_City.get() City_B = tk.Button(Get_weather_window,text='查询',command=e).place(x=0,y=20) input_Text = Text(Get_weather_window,height=600,width=50) input_Text.insert(END,WeatherInfo_BJ()) input_Text.place(x=0,y=45) Get_weather_window.mainloop()
def manage_admin(): root.geometry('175x150') global manentry, manlabel, susbutto, rembutto, edpbutto, edubutto, addbutto manentry = Entry(root) manlabel = Label(root, text="Type a username") susbutto = Button(root, text="Restrict", command=restrict_admin) rembutto = Button(root, text="Remove", command=remove_admin) edpbutto = Button(root, text="Edit Password", command=edit_admin_password) edubutto = Button(root, text="Edit Username", command=edit_admin_username) addbutto = Button(root, text="Add Admin", command=add_admin) susbutto.place(relx=0.64, x=1, y=50, anchor=NE) rembutto.place(relx=0.82, x=1, y=78, anchor=NE) edpbutto.place(relx=0.50, x=1, y=78, anchor=NE) addbutto.place(relx=0.92, x=1, y=106, anchor=NE) edubutto.place(relx=0.50, x=1, y=106, anchor=NE) manlabel.place(relx=0.76, x=1, y=3, anchor=NE) manentry.place(relx=0.84, x=1, y=25, anchor=NE)
def initUI(self): self.parent.title("Proyecto Guardian del Bosque") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) self.check_var1 = IntVar() self.check_var2 = IntVar() self.check_var3 = IntVar() self.path_video = StringVar() self.path_video1 = StringVar() lbl_title = Label(self, text="Proyecto Guardian del bosque") lbl_title.place(x=280, y=10) image = Image.open("images/img.png") photo = ImageTk.PhotoImage(image) lbl_image = Label(image=photo) lbl_image.image = photo lbl_image.place(x=550, y=50) image1 = Image.open("images/img1.png") photo1 = ImageTk.PhotoImage(image1) lbl_image1 = Label(image=photo1) lbl_image1.image = photo1 lbl_image1.place(x=50, y=300) lbl_path1 = Label( self, text="Ingrese la direccion de la primera imagen(actual): ") lbl_path1.place(x=20, y=50) entry_path1 = Entry(self, textvariable=self.path_video, width=60) entry_path1.place(x=20, y=80) lbl_path2 = Label( self, text="Ingrese la direccion de la segunda imagen(anterior): ") lbl_path2.place(x=20, y=110) entry_path2 = Entry(self, textvariable=self.path_video1, width=60) entry_path2.place(x=20, y=140) button_detect = Button(self, text="Detectar", command=self.detect, width=20) button_detect.place(x=60, y=180) button_quit = Button(self, text="Salir", command=self.quit, width=20) button_quit.place(x=280, y=180)
def readfitsfilename(self): #readfitsimage =True # set variable to read new image Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing # show an "Open" dialog box and return the path to the selected file filename = askopenfilename(initialdir=os.path.abspath(os.curdir), title='Select FITS file', filetypes=(('FITS files', '*.fits'), ('all files', '*.*'))) #print(filename) self.fileVar.set(filename) filevalue = Entry(self.master, textvariable=self.fileVar, width=40, justify='right') filevalue.place(relx=0.02, rely=0.15, anchor="w")
def show_word(word): t = time() select = [0] root = Tk() root.title('CrazyEnglish') try: root.call('wm', 'iconphoto', root._w, PhotoImage(file='english.png')) except Exception: print 'Error loading icon' root.geometry( str(root.winfo_screenwidth()) + 'x' + str(root.winfo_screenheight()) + '+0+0') #root.winfo_screenheight() root.resizable(False, False) root.protocol('WM_DELETE_WINDOW', lambda: exit(root, select)) canvas = Canvas(root) #,bg='green') canvas.place(x=100, y=100, width=800, height=50) canvas.create_text(0, 0, text=word[0], anchor='nw', font=('', 14), fill='red') canvas.create_text(0, 30, text='(' + word[1] + ')', anchor='nw') entry = Entry(root, font=('', 10)) entry.place(x=100, y=200, width=800, height=30) Button(root, text='OK', command=lambda: press_btn(root, entry, word[0])).place(x=100, y=250, height=30, width=80) root.after(0, lambda: close_window(root, t)) entry.focus_force() root.mainloop() return select[0]
def dly(): top = Tk() top.geometry("300x200") def sit(): top.destroy() def sbt(): if ce.get() == '': global crdelay crdelay = 5.0 else: global crdelay crdelay = float(ce.get()) if we.get() == '': global writedelay writedelay = 4.0 else: global writedelay writedelay = float(we.get()) if ne.get() == '': global nextdelay nextdelay = 2.0 else: global nextdelay nextdelay = float(ne.get()) print crdelay print writedelay print nextdelay top.destroy() cl = Label(top, text="Enter Chrome Launch Delay(sec): ") ce = Entry(top, width=3) wl = Label(top, text="Enter Data writing Delay(sec): ") we = Entry(top, width=3) nl = Label(top, text="Enter Next Result Delay(sec): ") ne = Entry(top, width=3) sa = Button(top, text="Apply", command=sbt) xt = Button(top, text="Exit", command=sit) cl.place(x=20, y=40) ce.place(x=230, y=40) wl.place(x=20, y=80) we.place(x=230, y=80) nl.place(x=20, y=120) ne.place(x=230, y=120) sa.place(x=110, y=160) xt.place(x=170, y=160)
def new_student(): def clear1(x): Student_no.delete(0, END) First_name.delete(0, END) Last_name.delete(0, END) Password.delete(0, END) def add_student(): curser.execute("use CS350deneme") print "here" try: getuser() if Student_no.get() in users_dict.keys(): added.config(text="This Student already added", fg="black") else: sid = Student_no.get() fname = First_name.get() lname = Last_name.get() password = Password.get() curser.execute( """insert into users(sid,snameuser,slastnameuser,password) values(%s,%s,%s,%s)""", (sid, fname, lname, password)) database.commit() added.config(text="Added", fg="black") except: added.config(text="something went wrong", fg="red") R2.destroy() global R6 R6 = Toplevel(main_screen) R6.resizable(width=FALSE, height=FALSE) R6.geometry("385x650") R6.title('MAKE ATTENDENCE ENTRY') lb1 = Label(R6, text="Student_NO :", font=("bold", 15)) lb1.place(x=50, y=206) lb2 = Label(R6, text="FirstName :", font=("bold", 15)) lb2.place(x=50, y=280) lb3 = Label(R6, text="LastName :", font=("bold", 15)) lb3.place(x=50, y=350) lb4 = Label(R6, text="Password :"******"bold", 15)) lb4.place(x=50, y=420) global Student_no global First_name global Last_name global Password Student_no = Entry(R6, width=15, font=("bold", 15), highlightthickness=2) Student_no.place(x=180, y=206) Student_no.bind('<Button-1>', clear1) First_name = Entry(R6, width=15, font=("bold", 15), highlightthickness=2) First_name.place(x=180, y=280) Last_name = Entry(R6, width=15, font=("bold", 15), highlightthickness=2) Last_name.place(x=180, y=350) Password = Entry(R6, width=15, font=("bold", 15), highlightthickness=2) Password.place(x=180, y=420) Addbutton = Button(R6, text="ADD", width=32, height=2, bg="turquoise4", fg="white", font="5", relief=RAISED, overrelief=RIDGE, command=add_student) Addbutton.place(x=50, y=500) def back(): R6.destroy() home() back = Button(R6, text="HOME", bg="turquoise4", fg="white", command=back) back.place(x=300, y=30) added = Label(R6, font=("bold", 15)) added.place(x=50, y=600)
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()
def xit(): root.destroy() exit(0) root = Tk() root.geometry("320x240") root.title("RESULTS GENERATOR V2 -- KAILASH RAMESH") dl = Label(root, text="Enter DOB: ") de = Entry(root) ll = Label(root, text="Enter the Lower Limit: ") le = Entry(root) ul = Label(root, text="Enter the Upper Limit: ") ue = Entry(root) sub = Button(root, text="GENERATE!", command=operation) xyt = Button(root, text="EXIT", command=xit) mod = Button(root, text="Adjust Delays", command=dly) dl.place(x=20, y=40) de.place(x=160, y=40) ll.place(x=20, y=80) le.place(x=160, y=80) ul.place(x=20, y=120) ue.place(x=160, y=120) sub.place(x=80, y=170) xyt.place(x=165, y=170) mod.place(x=210, y=170) root.mainloop()
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)
def readFile(self, filename,wel): #lblFile= Label(self, text=filename+" has successfully added", width=6) #lblFile.pack(side=LEFT, anchor=N, padx=5, pady=5) wel.pack_forget() f = open(filename, "r") text = f.read() L1 = Label(self, text="Size of property") L1.place( x=20,y=30) E1 = Entry(self, bd =5) E1.place( x=150,y=30) L2 = Label(self, text="Swimming pool") L2.place( x=20,y=60) E2 = Entry(self, bd =5) E2.place( x=150,y=60) L3 = Label(self, text="type") L3.place( x=20,y=90) E3 = Entry(self, bd =5) E3.place( x=150,y=90) L4 = Label(self, text="Interior") L4.place( x=20,y=120) E4 = Entry(self, bd =5) E4.place( x=150,y=120) L5 = Label(self, text="Lawn") L5.place( x=20,y=150) E5 = Entry(self, bd =5) E5.place( x=150,y=150) L6 = Label(self, text="View") L6.place( x=20,y=180) E6 = Entry(self, bd =5) E6.place( x=150,y=180) L7 = Label(self, text="Locality") L7.place( x=20,y=210) E7 = Entry(self, bd =5) E7.place( x=150,y=210) L8 = Label(self, text="Bathrooms") L8.place( x=20,y=240) E8 = Entry(self, bd =5) E8.place( x=150,y=240) L9 = Label(self, text="Parking") L9.place( x=20,y=270) E9 = Entry(self, bd =5) E9.place( x=150,y=270) cal=Button(self, text="Calculate", command=lambda:self.cal(filename,E1.get(),E2.get(),E3.get(),E4.get(),E5.get(),E6.get(),E7.get(),E8.get(),E9.get())) cal.place( x=100,y=300)
class Window(Frame): def __init__(self, parent): Frame.__init__(self, parent, background = "beige") self.parent = parent self.interface() def interface(self): self.parent.title("Probing Delay Transmitter Application") self.pack(fill=BOTH, expand = 1) self.setLabels() self.setButtons() self.setTextFields() def setButtons(self): ''' This function will set buttons on the window. ''' # exit button # exitbutton = Button(self, text = "Exit", foreground= "red", command = self.quit) # exitbutton.place(x= 150, y = 120) # start UDP Client button # only one start button self.startButton = Button(self, text = "Start", foreground = "Black", command = self.callStartByThread) self.startButton.place(x = 30, y = 220) # stop button stopButton = Button(self, text = "Stop", foreground = "Black", command = self.callTerminateProcesses) stopButton.place(x = 90, y = 220) #startTcpButton = Button(self, text = "Start TCP Server", foreground = "Black", command = self.launchTCPServer) #startTcpButton.place(x = 340, y = 190) def callTerminateProcesses(self): ''' This function will change the state of the start button and also stop the processes. ''' self.startButton.config(state = NORMAL) terminateProcesses() def callStartByThread(self): ''' This function will call start function by a thread. ''' self.startButton.config(state = DISABLED) start_new_thread(self.start, ()) def setLabels(self): ''' This function will set the labels on the window. ''' #UDP Server udp_label = Label(self, text = "UDP Server", foreground = "Black") udp_label.place(x = 40, y = 10) udp_hostLabel= Label(self, text = "Host Name", foreground = "Black") udp_hostLabel.place(x = 10, y = 40) udp_portLabel = Label(self, text = "Port Number", foreground = "Black") udp_portLabel.place(x = 10, y = 70) udp_packetSizeLabel = Label(self, text = "Packet Size", foreground = "Black") udp_packetSizeLabel.place(x = 10, y = 100) udp_packetScaleLabel = Label(self, text = "Byte", foreground = "Black") udp_packetScaleLabel.place(x = 220, y = 100) udp_timeBetweenEachWindowLabel = Label(self, text = "Time Between each Window", foreground = "Black") udp_timeBetweenEachWindowLabel.place(x = 10, y = 130) udp_windowSizeLabel = Label(self, text = "Window Size", foreground = "Black") udp_windowSizeLabel.place(x = 10, y = 160) udp_durationSendingPackets = Label(self, text = "Duration sending packets", foreground = "Black") udp_durationSendingPackets.place(x = 10, y = 190) # TCP Server tcp_label = Label(self, text = "TCP Server", foreground = "Black") tcp_label.place(x = 360, y = 10) tcp_hostEntry = Label(self, text = "Host Name", foreground = "Black") tcp_hostEntry.place( x= 340, y = 40) tcp_portNumber = Label(self, text = "Port Number", foreground = "Black") tcp_portNumber.place(x = 340, y = 70) #global notification_period = Label(self, text = "Notification Period", foreground = "Black") notification_period.place(x = 310, y = 100) def setTextFields(self): ''' This function will set the text fields. ''' #UDP Client # host self.udp_hostEntry = Entry(self) self.udp_hostEntry.insert(0, "127.0.0.1") self.udp_hostEntry.place(x = 90, y = 40) # port self.udp_portEntry = Entry(self) self.udp_portEntry.insert(0, "4001") self.udp_portEntry.place(x = 90, y = 70) # packetSize self.udp_packetSizeEntry = Entry(self) self.udp_packetSizeEntry.insert(0, "1000") self.udp_packetSizeEntry.place(x = 90, y = 100) # Time Between Each Window self.udp_timeBetweenEachWindow = Entry(self) self.udp_timeBetweenEachWindow.insert(0, "0") self.udp_timeBetweenEachWindow.place(x = 170, y = 130) # Window Size self.udp_windowSizeEntry = Entry(self) self.udp_windowSizeEntry.insert(0, "5") self.udp_windowSizeEntry.place(x = 170, y = 160) # Duration self.udp_durationEntry = Entry(self) self.udp_durationEntry.insert(0, "60") self.udp_durationEntry.place(x = 170, y = 190) #TCP Server # Host Name self.tcp_hostEntry = Entry(self) self.tcp_hostEntry.insert(0, "127.0.0.1") self.tcp_hostEntry.place(x = 420, y = 40) # Port self.tcp_portEntry = Entry(self) self.tcp_portEntry.insert(0, "5005") self.tcp_portEntry.place(x = 420, y = 70) # Notification period self.notificationEntry = Entry(self) self.notificationEntry.insert(0, "5") self.notificationEntry.place(x = 420, y = 100) def launchTCPServer(self, pipeArg): ''' This function will open a sub-process to launch TCP server. ''' global P1 print 'Starting TCP server' args = ["python", "TCPServer.py", "-l", str(self.tcp_hostEntry.get()) ,"-p", str(self.tcp_portEntry.get()), "-n", str(self.notificationEntry.get()), "-a", pipeArg] P1 = Popen(args, shell=False) def launchUdpClient(self): ''' This function will open a sub-process and launch UDP Client. ''' global P2 print 'Starting UDP Server' args = ["python", "UDPServer.py", "-l", str(self.udp_hostEntry.get()), "-p", str(self.udp_portEntry.get()), "-s", str(self.udp_packetSizeEntry.get()), "-t" , str(self.udp_timeBetweenEachWindow.get()), "-w", str(self.udp_windowSizeEntry.get()), "-n", str(self.notificationEntry.get()), "-d", str(self.udp_durationEntry.get())] P2 = Popen(args, shell=False) def start(self): ''' This function will start 1. Tcp Server, 2. Udp Client. ''' # Create pipe for communication pipeOut, pipeIn = pipe() pipeInDup = getHandleDuplicate(pipeIn) self.launchTCPServer(str(int(pipeInDup))) # Close write end of pipe in parent closePipe(pipeIn, pipeInDup) pipefh = fdopen(pipeOut, 'r') message = pipefh.read() # a message to start udp server if(message == "startUdpClient"): self.launchUdpClient() pipefh.close()
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 MusicGUI(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.centerWindow() self.initUI() def centerWindow(self): w = 500 h = 500 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w) / 2 y = (sh - h) / 2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y)) def initUI(self): self.parent.title("Python-Kullita") self.pack(fill=BOTH, expand=True) # self.var = BooleanVar() L1 = Label(self, text="Midi File Name:") L1.place(x = 30, y = 450) self.fileEntry = Entry(self) self.fileEntry.place(x = 150, y = 450) genButton = Button(self, text="Genrate Music!", command=self.onClick) genButton.place(x=350, y=450) self.initLog() self.init3Voices() def init3Voices(self): # [(47, 67), (52, 76), (60, 81)]) # (B,2) - 20 # (E,3) - 24 # (C,4) - 25 self.note_name = ['C','Cs','D','Ds','E','F','Fs','G','Gs','A','As','B'] self.pitchC1 = StringVar() self.pitchC2 = StringVar() self.pitchC3 = StringVar() self.octave1 = IntVar() self.octave2 = IntVar() self.octave3 = IntVar() self.range1 = IntVar() self.range2 = IntVar() self.range3 = IntVar() v1Label =Label(self, text="Voice 1 start:") v1Label.place(x = 30, y = 25) self.w1 = OptionMenu(self, self.pitchC1, *self.note_name) self.w1.place(x = 135, y = 25) self.pitchC1.set(self.note_name[11]) self.oc1 = OptionMenu(self, self.octave1, *range(1, 9)) self.oc1.place(x=200, y=25) self.octave1.set(2) v1_rangeLabel = Label(self, text="Range:") v1_rangeLabel.place(x=300, y=25) self.rangeoption1 = OptionMenu(self, self.range1, *range(18, 26)) self.rangeoption1.place(x=360, y=25) self.range1.set(20) v2Label = Label(self, text="Voice 2 start:") v2Label.place(x=30, y=50) self.w2 = OptionMenu(self, self.pitchC2, *self.note_name) self.w2.place(x=135, y=50) self.pitchC2.set(self.note_name[4]) self.oc2 = OptionMenu(self, self.octave2, *range(1, 9)) self.oc2.place(x=200, y=25 * 2) self.octave2.set(3) v2_rangeLabel = Label(self, text="Range:") v2_rangeLabel.place(x=300, y=25 * 2) self.rangeoption2 = OptionMenu(self, self.range2, *range(18, 26)) self.rangeoption2.place(x=360, y=25 * 2) self.range2.set(24) v3Label = Label(self, text="Voice 3 start:") v3Label.place(x=30, y=75) self.w3 = OptionMenu(self, self.pitchC3, *self.note_name) self.w3.place(x=135, y=75) self.pitchC3.set(self.note_name[0]) self.oc3 = OptionMenu(self, self.octave3, *range(1, 9)) self.oc3.place(x=200, y=25 * 3) self.octave3.set(4) v3_rangeLabel = Label(self, text="Range:") v3_rangeLabel.place(x=300, y=25 * 3) self.rangeoption3 = OptionMenu(self, self.range3, *range(18, 26)) self.rangeoption3.place(x=360, y=25 * 3) self.range3.set(25) # def pitchClick(self, voiceStr, key): # print("hello!") # vMap = {'1': self.pitchC1, '2': self.pitchC2, '3': self.pitchC3} # txt = voiceStr + ": " + self.note_name[vMap[key].get()] # txt += "\n" # self.logText.insert(INSERT, txt) def initLog(self): self.logText = Text(self, width = 61, height =21) self.logText.insert(INSERT, "Hello.....") self.logText.insert(INSERT, "Midi Log:\n") self.logText.place(x = 30, y = 110) self.logText.config(highlightbackground='blue') def onClick(self): self.filename = self.fileEntry.get() if self.filename == "": mbox.showerror("Error", "No File Name!") return temp = sys.stdout sys.stdout = open('log.txt', 'w') startPitch = [eval("midi." + self.pitchC1.get() + "_" + str(self.octave1.get())), eval("midi." + self.pitchC2.get() + "_" + str(self.octave2.get())), eval("midi." + self.pitchC3.get() + "_" + str(self.octave3.get())), ] print("Start Pitch Value:") print(startPitch) voiceRange = [(startPitch[0], startPitch[0] + self.range1.get()), (startPitch[1], startPitch[1] + self.range2.get()), (startPitch[2], startPitch[2] + self.range3.get()), ] print("3 Voices Pitch Range:") print(voiceRange) genMusic(self.filename, voiceRange) sys.stdout.close() sys.stdout = temp with open("log.txt", "r") as myfile: data = myfile.readlines() content = "" for line in data: content += line self.logText.insert(INSERT, content) mbox.showinfo("Music Generation", self.filename + ".midi File completed")
class MyFirstGUI: def __init__(self, master): self.master = master master.title("listening window") self.label = Label(master, text="This is our first GUI!") self.label.pack() self.label.place(x=100, y=30) self.label_2 = Label(master, text="Enter the name if you see fit: ") self.label_2.pack() self.label_2.place(x=100, y=5) self.message = StringVar() self.entry = Entry(textvariable=self.message) self.entry.place(x=320, y=15, anchor="c") self.label_word = Label(master, text="Vocalize: a") self.label_word.pack() self.label_word.place(x=120, y=60) self.var = IntVar() self.var.set(0) self.checkRU = Radiobutton(master, value=0, variable=self.var, text="Russian") self.checkRU.pack() self.checkRU.place(x=310, y=30) self.checkEn = Radiobutton(master, value=1, variable=self.var, text="English") self.checkEn.pack() self.checkEn.place(x=310, y=60) self.start_button = Button(master, text="Start recording", width=11, command=self.greet) self.start_button.pack() self.start_button.place(x=210, y=30) self.close_button = Button(master, text="Close", width=11, command=master.quit) self.close_button.pack() self.close_button.place(x=210, y=60) self.alphabet_english = [x for x in 'abcdefghijklmnopqrstuvwxyz'] self.alphabet_russian = [x for x in unicode('абвгдежзийклмнопрстуфхцчшщыэюя', "utf-8")] self.x = voice_recording self.close_button = Button(master, text="Redirect", width=11, command=self.redirect) self.close_button.pack() self.close_button.place(x=210, y=90) def greet(self): if self.var.get() == 0: str_alphabet = "абвгдежзийклмнопрстуфхцчшщыэюя" else: str_alphabet = "abcdefghijklmnopqrstuvwxyz" if (self.var.get() == 1) and (not self.alphabet_english): print("List is empty") self.alphabet_english = [x for x in str_alphabet] elif (self.var.get() == 0) and (not self.alphabet_russian): self.alphabet_russian = [x for x in unicode(str_alphabet, "utf-8")] if self.var.get() == 0: number = self.alphabet_russian.pop(0) else: number = self.alphabet_english.pop(0) print (number) name = "default" if self.message.get(): name = self.message.get() self.x.my_record(name + "_" + number + ".wav") if self.alphabet_english and self.var.get() == 1: self.label_word['text'] = "Vocalize: " + self.alphabet_english[0] elif self.alphabet_english and self.var.get() == 0: self.label_word['text'] = "Vocalize: " + self.alphabet_russian[0] else: self.label_word['text'] = 'Vocalize: a' subprocess.call("python voice_acting.py combined.wav", shell=True) def redirect(self): subprocess.call("python read_GUI.py " + self.message.get())
class Tk_Table(Frame, object): def __init__(self, master, columns, data=None, command=None, editable=True, sort=True, select_mode=None, autoscroll=True, vscrollbar=True, hscrollbar=False, heading_anchor = CENTER, cell_anchor=W, style=None, scrollbar_background=None, scrollbar_troughcolor=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, cell_background=None, cell_foreground=None, cell_font=None, field_background=None, heading_font= None, heading_background=None, heading_foreground=None, cell_pady=2, column_header=True, row_numbers=True, entry_background="#d6d6d6", entry_foreground=None, entry_validatecommand=None, entry_selectbackground="#1BA1E2", entry_selectborderwidth=None, entry_selectforeground=None, entry_font = "TkDefaultFont", rowlabel_anchor=E, rowlabel_minwidth=0, rowlabel_hoverbackground="#FFFFFF",frame_relief=None, frame_borderwidth=None, frame_background=None): frame_kwargs = {} if frame_relief is not None: frame_kwargs["relief"] = frame_relief if frame_borderwidth is not None: frame_kwargs["borderwidth"] = frame_borderwidth if frame_background is not None: frame_kwargs["background"] = frame_background Frame.__init__(self, master, class_="Multicolumn_Listbox", **frame_kwargs) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(1, weight=1) self._multicolumn_listbox = Multicolumn_Listbox(self, columns, data=data, command=command, sort=sort, select_mode=select_mode, heading_anchor = heading_anchor, cell_anchor=cell_anchor, style=style, height=height, padding=padding, adjust_heading_to_content=adjust_heading_to_content, stripped_rows=stripped_rows, selection_background=selection_background, selection_foreground=selection_foreground, cell_background=cell_background, cell_foreground=cell_foreground, cell_font=cell_font, field_background=field_background, heading_font=heading_font, heading_background=heading_background, heading_foreground=heading_foreground, cell_pady=cell_pady, headers=column_header) self._multicolumn_listbox.interior.grid(row=0, column=1, sticky= N+E+W+S) self._mousewheel_detection = True if row_numbers: self._row_numbers = Row_Header(self, font=self._multicolumn_listbox.font, row_height=self._multicolumn_listbox.row_height, row_minwidth=rowlabel_minwidth, hover_background = rowlabel_hoverbackground, anchor=rowlabel_anchor, onclick=self._on_click_row_label) self._row_numbers.grid(row=0, column=0, sticky= N+S+E) self._multicolumn_listbox.interior.bind("<Map>", self._place_vertically_row_numbers) else: self._row_numbers = None if editable: self._selected_cell = None self._entry_popup = None self._multicolumn_listbox.interior.bind("<1>", self._edit_cell) def configure(event): """ if self._entry_popup: self._entry_popup.destroy() return """ self._multicolumn_listbox.interior.update_idletasks() self._update_position_of_entry() self._multicolumn_listbox.interior.bind("<Configure>", configure) self._entry_kwargs = entry_kwargs = {} if entry_background is not None: entry_kwargs["background"] = entry_background if entry_foreground is not None: entry_kwargs["foreground"] = entry_foreground if entry_validatecommand is not None: entry_kwargs["validatecommand"] = entry_validatecommand if entry_selectbackground is not None: entry_kwargs["selectbackground"] = entry_selectbackground if entry_selectforeground is not None: entry_kwargs["selectforeground"] = entry_selectforeground if entry_font is not None: entry_kwargs["font"] = entry_font if command is not None: self._command = command self._multicolumn_listbox.interior.bind("<<TreeviewSelect>>", self._on_select) scrollbar_kwargs = {} if scrollbar_background is not None: scrollbar_kwargs["background"] = scrollbar_background if scrollbar_troughcolor is not None: scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor if vscrollbar: if editable: if row_numbers: def yview_command(*args): self._multicolumn_listbox.interior.yview(*args) self._row_numbers.yview(*args) self._update_position_of_entry() else: def yview_command(*args): self._multicolumn_listbox.interior.yview(*args) self._update_position_of_entry() else: if row_numbers: def yview_command(*args): self._multicolumn_listbox.interior.yview(*args) self._row_numbers.yview(*args) else: yview_command = self._multicolumn_listbox.interior.yview self._vbar=Scrollbar(self,takefocus=0, command=yview_command, **scrollbar_kwargs) self._vbar.grid(row=0, column=2, sticky= N+S) def yscrollcommand(first,last): first, last = float(first), float(last) if first <= 0 and last >= 1: if self._mousewheel_detection: if autoscroll: self._vbar.grid_remove() if row_numbers: unbind_function_onMouseWheel(self._multicolumn_listbox.interior) self._mousewheel_detection = False else: if not self._mousewheel_detection: if autoscroll: self._vbar.grid() if row_numbers: bind_function_onMouseWheel(self._row_numbers, "y", binding_widget=self._multicolumn_listbox.interior, unit="pages") self._mousewheel_detection = True self._vbar.set(first, last) if editable: self._update_position_of_entry() self._multicolumn_listbox.interior.config(yscrollcommand=yscrollcommand) if hscrollbar: if editable: def xview_command(*args): self._multicolumn_listbox.interior.xview(*args) self._update_position_of_entry() else: xview_command = self._multicolumn_listbox.interior.xview self._hbar=Scrollbar(self,takefocus=0, command=xview_command, **scrollbar_kwargs) self._hbar.grid(row=1, column=1, sticky= E+W) if autoscroll: if editable: def xscrollcommand(f,l, self=self): make_autoscroll(self._hbar, f, l) self._update_position_of_entry() else: def xscrollcommand(f,l, hbar=self._hbar): make_autoscroll(hbar, f, l) self._multicolumn_listbox.interior.config(xscrollcommand=xscrollcommand) else: self._multicolumn_listbox.interior.config(xscrollcommand=self._hbar.set) def _place_vertically_row_numbers(self, event): self._multicolumn_listbox.interior.unbind("<Map>") item_ID = self._multicolumn_listbox.interior.insert('', 0, values=[""]*self._multicolumn_listbox.number_of_columns) self._multicolumn_listbox.interior.update() x,y,w,h = self._multicolumn_listbox.interior.bbox(item_ID) self._multicolumn_listbox.interior.delete(item_ID) self._row_numbers.grid_configure(pady=(y,0)) def _edit_cell(self, event): '''Executed, when a row is clicked. Opens an entry popup above the cell, so it is possible to select text ''' # close previous popups if self._entry_popup: self._destroy_entry() # what row and column was clicked on item_ID = self._multicolumn_listbox.interior.identify_row(event.y) if not item_ID: return column = self._multicolumn_listbox.interior.identify_column(event.x) if column == "": return # get column position info x,y,width,height = self._multicolumn_listbox.interior.bbox(item_ID, column) # place Entry popup properly column_number = int(column[1:])-1 cell_data = self._multicolumn_listbox.item_ID_to_row_data(item_ID)[column_number] self._entry_popup = Entry(self._multicolumn_listbox.interior, exportselection=True, borderwidth=0, **self._entry_kwargs) self._entry_popup.place(x=x, y=y, width=width, height=height) self._entry_popup.insert(0, cell_data) self._entry_popup.focus_force() self._entry_popup.bind("<Control-a>", lambda event: self._select_all_entry_data) self._entry_popup.bind("<Escape>", lambda event: self._destroy_entry()) self._entry_popup.bind("<FocusOut>", lambda event: self._destroy_entry()) bind_function_onMouseWheel(self._multicolumn_listbox.interior, "y", binding_widget=self._entry_popup, callback=self._update_position_of_entry, unit="pages") if self._row_numbers: bind_function_onMouseWheel(self._row_numbers, "y", binding_widget=self._entry_popup, unit="pages") self._entry_popup.bind("<Return>", self._on_update_cell) self._selected_cell = item_ID, column, column_number def _on_click_row_label(self, index): if self._selected_cell and self._multicolumn_listbox.item_ID(index) == self._selected_cell[0]: self._destroy_entry() self._multicolumn_listbox.toogle_selection(index) def _select_all_entry_data(self): ''' Set selection on the whole text ''' self._entry_popup.selection_range(0, 'end') # returns 'break' to interrupt default key-bindings return 'break' def _destroy_entry(self): self._entry_popup.destroy() self._entry_popup = None self._selected_cell = None def _on_update_cell(self, event): item_ID, column, column_number = self._selected_cell data = self._entry_popup.get() row_data = self._multicolumn_listbox.item_ID_to_row_data(item_ID) row_data[column_number] = data self._multicolumn_listbox.interior.item(item_ID, values=row_data) self._destroy_entry() def _update_position_of_entry(self): if self._selected_cell: bbox = self._multicolumn_listbox.interior.bbox(self._selected_cell[0], self._selected_cell[1]) if bbox == "": self._entry_popup.place_forget() else: x,y,width,height = bbox self._entry_popup.place(x=x, y=y, width=width, height=height) def configure_column(self, index, width=None, minwidth=None, anchor=None, stretch=None): self._multicolumn_listbox.configure_column(self, index, width=None, minwidth=None, anchor=None, stretch=None) def row_data(self, index): return self._multicolumn_listbox.row_data(index) def update_row(self, index, data): self._multicolumn_listbox.update_row(index,data) def delete_row(self, index): self._multicolumn_listbox.delete_row(index) if self._row_numbers: self._row_numbers.pop() def insert_row(self, data, index=None): self._multicolumn_listbox.insert_row(data, index) if self._row_numbers: self._row_numbers.new_label() def column_data(self, index): return self._multicolumn_listbox.column_data(index) def update_column(self, index, data): self._multicolumn_listbox.update_column(index, data) def clear(self): self._multicolumn_listbox.clear() if self._row_numbers: self._row_numbers.delete_labels() def update(self, data): current_number_of_rows = self._multicolumn_listbox.number_of_rows self._multicolumn_listbox.update(data) if self._row_numbers: number_of_rows = len(data) if current_number_of_rows < number_of_rows: for i in range(number_of_rows - current_number_of_rows): self._row_numbers.new_label() else: n_labels = current_number_of_rows - number_of_rows self._row_numbers.pop(n_labels =n_labels) def focus(self, index=None): self._multicolumn_listbox.focus(index) def state(self, state=None): self._multicolumn_listbox.state(state) @property def number_of_rows(self): return self._multicolumn_listbox.number_of_rows @property def number_of_columns(self): return self._multicolumn_listbox.number_of_columns def toogle_selection(self, index): self._multicolumn_listbox.toogle_selection(index) def select_row(self, index): self._multicolumn_listbox.select_row(index) def deselect_row(self, index): self._multicolumn_listbox.deselect_row(index) def deselect_all(self): self._multicolumn_listbox.deselect_all() def set_selection(self, indices): self._multicolumn_listbox.set_selection(indices) @property def selected_rows(self): return self._multicolumn_listbox.selected_rows @property def indices_of_selected_rows(self): return self._multicolumn_listbox.indices_of_selected_rows def delete_all_selected_rows(self): number_of_deleted_rows = self._multicolumn_listbox.delete_all_selected_rows() if self._row_numbers: self._row_numbers.pop(n_labels=number_of_deleted_rows) @property def table_data(self): return self._multicolumn_listbox.table_data @table_data.setter def table_data(self, data): self.update(data) def cell_data(self, row, column): return self._multicolumn_listbox.cell_data(row, column) def update_cell(self, row, column, value): self._multicolumn_listbox.update_cell(row, column, value) def __getitem__(self, index): return self._multicolumn_listbox[index] def __setitem__(self, index, value): self._multicolumn_listbox[index] = value def bind(self, event, handler): self._multicolumn_listbox.bind(event, handler) def sort_by(self, col, descending): self._multicolumn_listbox.sort_by(col, descending)
class NGA_Window_LED_Advanced(Frame): led = None led1amp = 100.0 led2amp = 100.0 led3amp = 100.0 led4amp = 100.0 sys = None wLED = None #window of pointer to main LED window def __init__(self, parent, sys): Frame.__init__(self, parent) #self.wLED = sys.wL #LED Window self.parent = parent self.sys = sys self.sys.c_led_advanced = self # get window configurations self.parent.geometry(self.sys.win_cfg.wLEDAdvanced) self.parent.title(self.sys.win_cfg.sLEDAdvanced) # draw window self.initUI() # window defaults self.update_led_on_off() def initUI(self): self.style = Style().configure("TFrame", background=self.sys.win_cfg.cBackground) self.pack(fill=BOTH, expand=1) # setup labels self.LED1 = Label(self, width=4, background=self.sys.win_cfg.cLEDOff, text="LED1") self.LED1.place(x=98, y=45) self.LED2 = Label(self, width=4, background=self.sys.win_cfg.cLEDOff, text="LED2") self.LED2.place(x=98, y=75) self.LED3 = Label(self, width=4, background=self.sys.win_cfg.cLEDOff, text="LED3") self.LED3.place(x=98, y=105) self.LED4 = Label(self, width=4, background=self.sys.win_cfg.cLEDOff, text="LED4") self.LED4.place(x=98, y=135) # setup entries titleLabel = Label(self, text=self.sys.win_cfg.sLEDAdvanced, background=self.sys.win_cfg.cBackground, width=12, height=1) titleLabel.place(x=5, y=5) percentLabel = Label(self, text="0-100 (%)", background=self.sys.win_cfg.cBackground, width=8, height=1) percentLabel.place(x=5, y=22) self.led1val = Entry(self, width=4, background=self.sys.win_cfg.cTextBackground) self.led1val.place(x=10, y=50-4) self.led2val = Entry(self, width=4, background=self.sys.win_cfg.cTextBackground) self.led2val.place(x=10, y=80-4) self.led3val = Entry(self, width=4, background=self.sys.win_cfg.cTextBackground) self.led3val.place(x=10, y=110-4) self.led4val = Entry(self, width=4, background=self.sys.win_cfg.cTextBackground) self.led4val.place(x=10, y=140) # setup buttons led1onButton = Button(self, text="LED1", command=self.led1_on, width=6) led1onButton.place(x=45, y=45) led2onButton = Button(self, text="LED2", command=self.led2_on, width=6) led2onButton.place(x=45, y=75) led3onButton = Button(self, text="LED3", command=self.led3_on, width=6) led3onButton.place(x=45, y=105) led4onButton = Button(self, text="LED4", command=self.led4_on, width=6) led4onButton.place(x=45, y=135) # close buttons closeButton = Button(self, text="Close", command=self.close_window) closeButton.place(x=30, y=180) self.update_duty() def update_duty(self): self.led1val.delete(0, END) self.led1val.insert(0, "{0:.1f}".format(self.led1amp)) self.led2val.delete(0, END) self.led2val.insert(0, "{0:.1f}".format(self.led2amp)) self.led3val.delete(0, END) self.led3val.insert(0, "{0:.1f}".format(self.led3amp)) self.led4val.delete(0, END) self.led4val.insert(0, "{0:.1f}".format(self.led4amp)) def getValues(self): self.led1amp = float(self.led1val.get()) self.led2amp = float(self.led2val.get()) self.led3amp = float(self.led3val.get()) self.led4amp = float(self.led4val.get()) def byteFromPer(self, val): return val*(255.0/100.0) #percent (0-100) to (0-255) def close_window(self): self.parent.destroy() def led1_on(self): self.sys.hw.led.command(NGA_Interface_LED.LED_OFF) self.getValues() self.sys.hw.led.duty_cycle(0,self.byteFromPer(self.led1amp)) self.update_regular_led() def led2_on(self): self.sys.hw.led.command(NGA_Interface_LED.LED_OFF) self.getValues() self.sys.hw.led.duty_cycle(1,self.byteFromPer(self.led2amp)) self.update_regular_led() def led3_on(self): self.sys.hw.led.command(NGA_Interface_LED.LED_OFF) self.getValues() self.sys.hw.led.duty_cycle(2,self.byteFromPer(self.led3amp)) self.update_regular_led() def led4_on(self): self.sys.hw.led.command(NGA_Interface_LED.LED_OFF) self.getValues() self.sys.hw.led.duty_cycle(3,self.byteFromPer(self.led4amp)) self.update_regular_led() def update_led_on_off(self): if self.sys.hw.led.led_on[0] == True: self.LED1.configure(background = self.sys.win_cfg.cLEDOn) if self.sys.hw.led.led_on[0] == False: self.LED1.configure(background = self.sys.win_cfg.cLEDOff) if self.sys.hw.led.led_on[1] == True: self.LED2.configure(background = self.sys.win_cfg.cLEDOn) if self.sys.hw.led.led_on[1] == False: self.LED2.configure(background = self.sys.win_cfg.cLEDOff) if self.sys.hw.led.led_on[2] == True: self.LED3.configure(background = self.sys.win_cfg.cLEDOn) if self.sys.hw.led.led_on[2] == False: self.LED3.configure(background = self.sys.win_cfg.cLEDOff) if self.sys.hw.led.led_on[3] == True: self.LED4.configure(background = self.sys.win_cfg.cLEDOn) if self.sys.hw.led.led_on[3] == False: self.LED4.configure(background = self.sys.win_cfg.cLEDOff) def update_regular_led(self): if (self.parent.winfo_exists() == 1): #window exists self.sys.c_led.update_led() # inform led window self.update_led_on_off() def update_led(self): self.update_led_on_off()
def student(): def deneme(): datelist = [] listbox1 = Listbox(report, width=60, height=10, font=("bold", 15)) listbox1.insert(END, ) scrollbar1 = Scrollbar( report, orient="vertical", ) scrollbar1.config(command=listbox1.yview) scrollbar1.place(x=950, y=450, height=242) listbox1.config(yscrollcommand=scrollbar1.set) listbox1.place( x=300, y=450, ) curser.execute("use cs350deneme") sql_select = """select * from attendance2 where sid=%s and start like %s""" value = e3.get() + "%" curser.execute(sql_select, (username1, value)) r = curser.fetchall() for i in r: cid = str(i[0]) start = str(i[1]) sid = str(i[2]) attended = str(i[3]) sign = str(i[4]) tolistbox = cid + " | " + start + " | " + sid + " | " + attended + " | " + sign datelist.append(tolistbox) # print attendcelist for i in datelist: listbox1.insert(END, i) curser.execute("use cs350deneme") sql_search = """select cid from enroll where sid =%s""" curser.execute(sql_search, (username1, )) results = curser.fetchall() course_list = [] for i in results: course_list.append(str(i[0])) lb2 = Label(report, text="Enrolled Classes", font=("bold", 15)) lb2.place(x=90, y=50) for x in range(len(course_list)): global compButton compButton = Button(report, text=course_list[x], width=10, height=1, bg="turquoise4", fg="white", font="5", relief=RAISED, overrelief=RIDGE, command=lambda z=course_list[x]: listbox(z)) compButton.place(x=x * 100 + 300, y=50) lb3 = Label(report, text="Absent At :", font=("bold", 15)) lb3.place(x=90, y=400) e3 = Entry(report, width=10, font=("bold", 15), highlightthickness=2) e3.place(x=200, y=400) searchbutton = Button(report, text="SEARCH", width=10, height=1, bg="turquoise4", fg="white", font="5", relief=RAISED, overrelief=RIDGE, command=deneme) searchbutton.place(x=350, y=400)
def add_text_field(self, label_text, field_text, y): self.add_label(label_text, y) text_field = Entry(self.root, text=field_text) text_field.place(x=PANEL_X + LABEL_W, y=y)
def login(): getuser() main_screen.withdraw() def getusername(sid): curser.execute("use CS350deneme") sql_select = """select sid,snameuser,password from users where sid = %s""" curser.execute(sql_select, (sid, )) record = curser.fetchall() return record[0] def login_verify(): global username1 username1 = username_verify.get() password1 = password_verify.get() if username1 == "admin" and password1 == "123": login_check("Welcome Admin", home) elif username1 in users_dict.keys( ) and password1 == users_dict[username1]: login_check("Welcome" + " " + getusername(username1)[1], studenthome) else: tkMessageBox.showerror("INVALID ENTRY", "Username or password is wrong") global login_screen login_screen = Toplevel(main_screen) login_screen.title("Login") login_screen.geometry("385x650") login_screen.resizable(width=FALSE, height=FALSE) login_screen.configure(background="white") global username_verify global password_verify username_verify = StringVar() password_verify = StringVar() global username_login_entry global password_login_entry path = "JPG_Formatinda_SEHIR_logo_1_Ingilizce.jpg" img = ImageTk.PhotoImage(Image.open(path)) panel = Label(login_screen, image=img) panel.photo = img panel.place(x=40, y=0) Label(login_screen, text="Username : "******"bold", 20), bg="white").place(x=50, y=490) def clear(x): username_login_entry.delete(0, END) password_login_entry.delete(0, END) username_login_entry = Entry(login_screen, textvariable=username_verify) username_login_entry.bind('<Button-1>', clear) username_login_entry.place(x=210, y=500, height=25, width=120) Label(login_screen, text="Password : "******"bold", 20), bg="white").place(x=50, y=540) password_login_entry = Entry(login_screen, textvariable=password_verify, show='*') password_login_entry.place(x=210, y=550, height=25, width=120) loginB = Button(login_screen, text="Login", width=15, height=1, bg="turquoise4", fg="white", font="5", relief=FLAT, overrelief=RIDGE, borderwidth='5', command=login_verify) loginB.place(x=190, y=600) ExitB = Button(login_screen, text="Exit", width=13, height=1, bg="turquoise4", fg="white", font="5", relief=FLAT, overrelief=RIDGE, borderwidth='5', command=exit) ExitB.place(x=40, y=600)
#-----------------------------------setup title--------------------------------------------------- title = ImageTk.PhotoImage(PIL.Image.open("../pic/title.png")) titlelabel = Label(topPanel, image = title) titlelabel.image = title titlelabel.place(x = 600, y = 0, anchor = "nw") #-----------------------------------setup user input--------------------------------------------------- v1 = StringVar() E1 = Entry(topPanel, bd =5, textvariable=v1) E1.place(x = 770, y = 450, anchor = "w") L1 = Label(topPanel, text="User1 Name") L1.place(x = 680, y = 450, anchor = "w") B1 = Button(topPanel, text = "enter", command = enterUserName1, bd = 3) B1.place(x = 970, y = 450, anchor = "w") v2 = StringVar() E2 = Entry(topPanel, bd =5, textvariable=v2) E2.place(x = 770, y = 500, anchor = "w") L2 = Label(topPanel, text="User2 Name") L2.place(x = 680, y = 500, anchor = "w") B2 = Button(topPanel, text = "enter", command = enterUserName2, bd = 3) B2.place(x = 970, y = 500, anchor = "w") #-----------------------------------user1 status---------------------------------------------------
def student_report(): def report(): curser.execute("use cs350deneme") sql_search = """select cid from enroll where sid =%s""" curser.execute(sql_search, (e1.get(), )) results = curser.fetchall() course_list = [] for i in results: course_list.append(str(i[0])) lb2 = Label(studentreport, text="Enrolled Classes", font=("bold", 15)) lb2.place(x=90, y=100) for x in range(len(course_list)): global compButton compButton = Button(studentreport, text=course_list[x], width=10, height=1, bg="turquoise4", fg="white", font="5", relief=RAISED, overrelief=RIDGE, command=lambda z=course_list[x]: listbox(z)) compButton.place(x=200, y=x * 100 + 150) def listbox(x): attendcelist = [] curser.execute("use cs350deneme") sql_select = """select cid,start,sid,attended,sign from attendance2 where cid=%s and sid =%s""" curser.execute(sql_select, ( x, e1.get(), )) r = curser.fetchall() for i in r: cid = str(i[0]) start = str(i[1]) sid = str(i[2]) attended = str(i[3]) sign = str(i[4]) tolistbox = cid + " | " + start + " | " + sid + " | " + attended + " | " + sign attendcelist.append(tolistbox) listbox = Listbox(studentreport, width=60, height=10, font=("bold", 15)) listbox.insert(END, ) scrollbar = Scrollbar( studentreport, orient="vertical", ) scrollbar.config(command=listbox.yview) scrollbar.place(x=1150, y=150, height=242) listbox.config(yscrollcommand=scrollbar.set) for item in attendcelist: listbox.insert(END, item) st = 0 for i in range(len(attendcelist)): print type(attendcelist[i][-1]) if attendcelist[i][-1] == "e": st = 0 else: st = int(attendcelist[i][-1]) print st print type(st) if st == 0: listbox.itemconfig(i, {'bg': 'red'}) else: listbox.itemconfig(i, {'bg': 'green'}) # this changes the font color of the 4th item listbox.place( x=500, y=150, ) R2.destroy() global studentreport studentreport = Toplevel(main_screen) studentreport.title("SEARCH AND REPORT") studentreport.geometry("1280x720") lb1 = Label(studentreport, text="Student No :", font=("bold", 15)) lb1.place(x=90, y=50) e1 = Entry(studentreport, width=10, font=("bold", 15), highlightthickness=2) e1.place(x=220, y=50) searchbutton = Button(studentreport, text="SEARCH", width=10, height=1, bg="turquoise4", fg="white", font="5", relief=RAISED, overrelief=RIDGE, command=report) searchbutton.place(x=350, y=50) def back(): studentreport.destroy() home() b1 = Button(studentreport, text="Back", bg="turquoise4", fg="white", command=back) b1.place(x=1210, y=20)
def __init__(self, mainWindow, mainWidth, mainHeight): frame_main = Frame(mainWindow, width=mainWidth, height=mainHeight) frame_main.grid(row=0, column=0) lblTitle = Label(mainWindow, text="Ingrese su número de cédula", font=(None, 45)) lblTitle.place(x=self.posElement(50, mainWidth), y=self.posElement(20, mainHeight), anchor="center") #Validación de solo números #reg = mainWindow.register(val.onlyDigits) #reg = mainWindow.register() #txtCedula = Entry(mainWindow, font="Helvetica 60 bold", width=15, justify="center", validate="all", validatecommand=(reg, '%P')) txtCedula = Entry(mainWindow, font="Helvetica 120 bold", width=15, justify="center") txtCedula.place(x=self.posElement(50, mainWidth), y=self.posElement(50, mainHeight), anchor="center") txtCedula.focus() lblTitle2 = Label(mainWindow, text="Presione Click en 'ENTER' para continuar.", font=(None, 45)) lblTitle2.place(x=self.posElement(50, mainWidth), y=self.posElement(80, mainHeight), anchor="center") # Setup Keypad KEYPAD = [["3", "2", "1", "A"], ["6", "5", "4", "B"], ["9", "8", "7", "C"], ["0", ".", "X", "D"]] # same as calling: factory.create_4_by_4_keypad, still we put here fyi: ROW_PINS = [ 16, 20, 21, 5 ] # BCM numbering; Board numbering is: 7,8,10,11 (see pinout.xyz/) COL_PINS = [ 6, 13, 19, 26 ] # BCM numbering; Board numbering is: 12,13,15,16 (see pinout.xyz/) factory = rpi_gpio.KeypadFactory() # Try keypad = factory.create_4_by_3_keypad() or # Try keypad = factory.create_4_by_4_keypad() #for reasonable defaults # or define your own: keypad = factory.create_keypad(keypad=KEYPAD, row_pins=ROW_PINS, col_pins=COL_PINS) def printkey(key): if self.estado == 0: if self.maxlong < 10: if (key == '1' or key == '2' or key == '3' or key == '4' or key == '5' or key == '6' or key == '7' or key == '8' or key == '9' or key == '0'): txtCedula.insert(END, key) elif key == 'D': #FIXME Validar número de cédula self.estado = 1 frame_menu.MenuForm(mainWindow, mainWidth, mainHeight) mainWindow.update() print "show" if key == 'X' or key == 'A': txtCedula.delete(0, 'end') self.maxlong = len(txtCedula.get()) elif self.estado == 1: if (key == '1'): self.print_certificado_notas() elif key == '2': self.print_certificado_matricula() print(key) keypad.registerKeyPressHandler(printkey)
def listbox(): attendcelist = [] curser.execute("use cs350deneme") sql_select = """select * from attendance2 where cid=%s""" curser.execute(sql_select, (e2.get(), )) r = curser.fetchall() for i in r: cid = str(i[0]) start = str(i[1]) sid = str(i[2]) attended = str(i[3]) sign = str(i[4]) tolistbox = cid + " | " + start + " | " + sid + " | " + attended + " | " + sign attendcelist.append(tolistbox) #print attendcelist def deneme(): datelist = [] curser.execute("use cs350deneme") sql_select = """select * from attendance2 where cid=%s and start like %s""" value = e3.get() + "%" curser.execute(sql_select, (e2.get(), value)) r = curser.fetchall() for i in r: cid = str(i[0]) start = str(i[1]) sid = str(i[2]) attended = str(i[3]) sign = str(i[4]) tolistbox = cid + " | " + start + " | " + sid + " | " + attended + " | " + sign datelist.append(tolistbox) # print attendcelist for i in datelist: listbox1.insert(END, i) listbox = Listbox(coursereport, width=60, height=10, font=("bold", 15)) listbox.insert(END, ) listbox1 = Listbox(coursereport, width=60, height=10, font=("bold", 15)) listbox1.insert(END, ) scrollbar = Scrollbar( coursereport, orient="vertical", ) scrollbar.config(command=listbox.yview) scrollbar.place(x=1150, y=150, height=242) scrollbar1 = Scrollbar( coursereport, orient="vertical", ) scrollbar1.config(command=listbox1.yview) scrollbar1.place(x=1150, y=400, height=242) listbox.config(yscrollcommand=scrollbar.set) listbox.place( x=500, y=150, ) listbox1.config(yscrollcommand=scrollbar1.set) listbox1.place( x=500, y=400, ) lb3 = Label(coursereport, text="Date :", font=("bold", 15)) lb3.place(x=90, y=400) e3 = Entry(coursereport, width=10, font=("bold", 15), highlightthickness=2) e3.place(x=220, y=400) searchbutton1 = Button(coursereport, text="SEARCH", width=10, height=1, bg="turquoise4", fg="white", font="5", relief=RAISED, overrelief=RIDGE, command=deneme) searchbutton1.place(x=350, y=400) for item in attendcelist: listbox.insert(END, item) for i in range(len(attendcelist)): st = int(attendcelist[i][-1]) if st == 0: listbox.itemconfig(i, {'bg': 'red'}) else: listbox.itemconfig(i, {'bg': 'green'})
class Tk_Table(Frame, object): def __init__(self, master, columns, data=None, command=None, editable=True, sort=True, select_mode=None, autoscroll=True, vscrollbar=True, hscrollbar=False, heading_anchor = CENTER, cell_anchor=W, style=None, scrollbar_background=None, scrollbar_troughcolor=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, cell_background=None, cell_foreground=None, cell_font=None, field_background=None, heading_font= None, heading_background=None, heading_foreground=None, cell_pady=2, column_header=True, row_numbers=True, entry_background="#d6d6d6", entry_foreground=None, entry_validatecommand=None, entry_selectbackground="#1BA1E2", entry_selectborderwidth=None, entry_selectforeground=None, entry_font = "TkDefaultFont", rowlabel_anchor=E, rowlabel_minwidth=0, rowlabel_hoverbackground="#FFFFFF",frame_relief=None, frame_borderwidth=None, frame_background=None): frame_kwargs = {} if frame_relief is not None: frame_kwargs["relief"] = frame_relief if frame_borderwidth is not None: frame_kwargs["borderwidth"] = frame_borderwidth if frame_background is not None: frame_kwargs["background"] = frame_background Frame.__init__(self, master, class_="Multicolumn_Listbox", **frame_kwargs) self.grid_rowconfigure(0, weight=1) self.grid_columnconfigure(1, weight=1) self._multicolumn_listbox = Multicolumn_Listbox(self, columns, data=data, command=command, sort=sort, select_mode=select_mode, heading_anchor = heading_anchor, cell_anchor=cell_anchor, style=style, height=height, padding=padding, adjust_heading_to_content=adjust_heading_to_content, stripped_rows=stripped_rows, selection_background=selection_background, selection_foreground=selection_foreground, cell_background=cell_background, cell_foreground=cell_foreground, cell_font=cell_font, field_background=field_background, heading_font=heading_font, heading_background=heading_background, heading_foreground=heading_foreground, cell_pady=cell_pady, headers=column_header) self._multicolumn_listbox.interior.grid(row=0, column=1, sticky= N+E+W+S) self._mousewheel_detection = True if row_numbers: self._row_numbers = Row_Header(self, font=self._multicolumn_listbox.font, row_height=self._multicolumn_listbox.row_height, row_minwidth=rowlabel_minwidth, hover_background = rowlabel_hoverbackground, anchor=rowlabel_anchor, onclick=self._on_click_row_label) self._row_numbers.grid(row=0, column=0, sticky= N+S+E) self._multicolumn_listbox.interior.bind("<Map>", self._place_vertically_row_numbers) else: self._row_numbers = None if editable: self._selected_cell = None self._entry_popup = None self._multicolumn_listbox.interior.bind("<1>", self._edit_cell) def configure(event): """ if self._entry_popup: self._entry_popup.destroy() return """ self._multicolumn_listbox.interior.update_idletasks() self._update_position_of_entry() self._multicolumn_listbox.interior.bind("<Configure>", configure) self._entry_kwargs = entry_kwargs = {} if entry_background is not None: entry_kwargs["background"] = entry_background if entry_foreground is not None: entry_kwargs["foreground"] = entry_foreground if entry_validatecommand is not None: entry_kwargs["validatecommand"] = entry_validatecommand if entry_selectbackground is not None: entry_kwargs["selectbackground"] = entry_selectbackground if entry_selectforeground is not None: entry_kwargs["selectforeground"] = entry_selectforeground if entry_font is not None: entry_kwargs["font"] = entry_font if command is not None: self._command = command self._multicolumn_listbox.interior.bind("<<TreeviewSelect>>", self._on_select) scrollbar_kwargs = {} if scrollbar_background is not None: scrollbar_kwargs["background"] = scrollbar_background if scrollbar_troughcolor is not None: scrollbar_kwargs["throughcolor"] = scrollbar_troughcolor if vscrollbar: if editable: if row_numbers: def yview_command(*args): self._multicolumn_listbox.interior.yview(*args) self._row_numbers.yview(*args) self._update_position_of_entry() else: def yview_command(*args): self._multicolumn_listbox.interior.yview(*args) self._update_position_of_entry() else: if row_numbers: def yview_command(*args): self._multicolumn_listbox.interior.yview(*args) self._row_numbers.yview(*args) else: yview_command = self._multicolumn_listbox.interior.yview self._vbar=Scrollbar(self,takefocus=0, command=yview_command, **scrollbar_kwargs) self._vbar.grid(row=0, column=2, sticky= N+S) def yscrollcommand(first,last): first, last = float(first), float(last) if first <= 0 and last >= 1: if self._mousewheel_detection: if autoscroll: self._vbar.grid_remove() if row_numbers: unbind_function_onMouseWheel(self._multicolumn_listbox.interior) self._mousewheel_detection = False else: if not self._mousewheel_detection: if autoscroll: self._vbar.grid() if row_numbers: bind_function_onMouseWheel(self._row_numbers, "y", binding_widget=self._multicolumn_listbox.interior, unit="pages") self._mousewheel_detection = True self._vbar.set(first, last) if editable: self._update_position_of_entry() self._multicolumn_listbox.interior.config(yscrollcommand=yscrollcommand) if hscrollbar: if editable: def xview_command(*args): self._multicolumn_listbox.interior.xview(*args) self._update_position_of_entry() else: xview_command = self._multicolumn_listbox.interior.xview self._hbar=Scrollbar(self,takefocus=0, command=xview_command, **scrollbar_kwargs) self._hbar.grid(row=1, column=1, sticky= E+W) if autoscroll: if editable: def xscrollcommand(f,l, self=self): make_autoscroll(self._hbar, f, l) self._update_position_of_entry() else: def xscrollcommand(f,l, hbar=self._hbar): make_autoscroll(hbar, f, l) self._multicolumn_listbox.interior.config(xscrollcommand=xscrollcommand) else: self._multicolumn_listbox.interior.config(xscrollcommand=self._hbar.set) def _place_vertically_row_numbers(self, event): self._multicolumn_listbox.interior.unbind("<Map>") item_ID = self._multicolumn_listbox.interior.insert('', 0, values=[""]*self._multicolumn_listbox.number_of_columns) self._multicolumn_listbox.interior.update() x,y,w,h = self._multicolumn_listbox.interior.bbox(item_ID) self._multicolumn_listbox.interior.delete(item_ID) self._row_numbers.grid_configure(pady=(y,0)) def _edit_cell(self, event): '''Executed, when a row is clicked. Opens an entry popup above the cell, so it is possible to select text ''' # close previous popups if self._entry_popup: self._destroy_entry() # what row and column was clicked on item_ID = self._multicolumn_listbox.interior.identify_row(event.y) if not item_ID: return column = self._multicolumn_listbox.interior.identify_column(event.x) if column == "": return # get column position info x,y,width,height = self._multicolumn_listbox.interior.bbox(item_ID, column) # place Entry popup properly column_number = int(column[1:])-1 cell_data = self._multicolumn_listbox.item_ID_to_row_data(item_ID)[column_number] self._entry_popup = Entry(self._multicolumn_listbox.interior, exportselection=True, borderwidth=0, **self._entry_kwargs) self._entry_popup.place(x=x, y=y, width=width, height=height) self._entry_popup.insert(0, cell_data) self._entry_popup.focus_force() self._entry_popup.bind("<Control-a>", lambda event: self._select_all_entry_data) self._entry_popup.bind("<Escape>", lambda event: self._destroy_entry()) self._entry_popup.bind("<FocusOut>", lambda event: self._destroy_entry()) bind_function_onMouseWheel(self._multicolumn_listbox.interior, "y", binding_widget=self._entry_popup, callback=self._update_position_of_entry, unit="pages") if self._row_numbers: bind_function_onMouseWheel(self._row_numbers, "y", binding_widget=self._entry_popup, unit="pages") self._entry_popup.bind("<Return>", self._on_update_cell) self._selected_cell = item_ID, column, column_number def _on_click_row_label(self, index): if self._selected_cell and self._multicolumn_listbox.item_ID(index) == self._selected_cell[0]: self._destroy_entry() self._multicolumn_listbox.toogle_selection(index) def _select_all_entry_data(self): ''' Set selection on the whole text ''' self._entry_popup.selection_range(0, 'end') # returns 'break' to interrupt default key-bindings return 'break' def _destroy_entry(self): self._entry_popup.destroy() self._entry_popup = None self._selected_cell = None def _on_update_cell(self, event): item_ID, column, column_number = self._selected_cell data = self._entry_popup.get() row_data = self._multicolumn_listbox.item_ID_to_row_data(item_ID) row_data[column_number] = data self._multicolumn_listbox.interior.item(item_ID, values=row_data) self._destroy_entry() def _update_position_of_entry(self): if self._selected_cell: bbox = self._multicolumn_listbox.interior.bbox(self._selected_cell[0], self._selected_cell[1]) if bbox == "": self._entry_popup.place_forget() else: x,y,width,height = bbox self._entry_popup.place(x=x, y=y, width=width, height=height) def configure_column(self, index, width=None, minwidth=None, anchor=None, stretch=None): self._multicolumn_listbox.configure_column(self, index, width=None, minwidth=None, anchor=None, stretch=None) def row_data(self, index): return self._multicolumn_listbox.row_data(index) def update_row(self, index, data): self._multicolumn_listbox.update_row(index,data) def delete_row(self, index): self._multicolumn_listbox.delete_row(index) if self._row_numbers: self._row_numbers.pop() def insert_row(self, data, index=None): self._multicolumn_listbox.insert_row(data, index) if self._row_numbers: self._row_numbers.new_label() def column_data(self, index): return self._multicolumn_listbox.column_data(index) def update_column(self, index, data): self._multicolumn_listbox.update_column(index, data) def clear(self): self._multicolumn_listbox.clear() if self._row_numbers: self._row_numbers.delete_labels() def update(self, data): current_number_of_rows = self._multicolumn_listbox.number_of_rows self._multicolumn_listbox.update(data) if self._row_numbers: number_of_rows = len(data) if current_number_of_rows < number_of_rows: for i in range(number_of_rows - current_number_of_rows): self._row_numbers.new_label() else: n_labels = current_number_of_rows - number_of_rows self._row_numbers.pop(n_labels =n_labels) def focus(self, index=None): self._multicolumn_listbox.focus(index) def state(self, state=None): self._multicolumn_listbox.state(state) @property def number_of_rows(self): return self._multicolumn_listbox.number_of_rows @property def number_of_columns(self): return self._multicolumn_listbox.number_of_columns def toogle_selection(self, index): self._multicolumn_listbox.toogle_selection(index) def select_row(self, index): self._multicolumn_listbox.select_row(index) def deselect_row(self, index): self._multicolumn_listbox.deselect_row(index) def deselect_all(self): self._multicolumn_listbox.deselect_all() def set_selection(self, indices): self._multicolumn_listbox.set_selection(indices) @property def selected_rows(self): return self._multicolumn_listbox.selected_rows @property def indices_of_selected_rows(self): return self._multicolumn_listbox.indices_of_selected_rows def delete_all_selected_rows(self): number_of_deleted_rows = self._multicolumn_listbox.delete_all_selected_rows() if self._row_numbers: self._row_numbers.pop(n_labels=number_of_deleted_rows) @property def table_data(self): return self._multicolumn_listbox.table_data @table_data.setter def table_data(self, data): self.update(data) def cell_data(self, row, column): return self._multicolumn_listbox.cell_data(row, column) def update_cell(self, row, column, value): self._multicolumn_listbox.update_cell(row, column, value) def __getitem__(self, index): return self._multicolumn_listbox[index] def __setitem__(self, index, value): self._multicolumn_listbox[index] = value def bind(self, event, handler): self._multicolumn_listbox.bind(event, handler) def sort_by(self, col, descending): self._multicolumn_listbox.sort_by(col, descending)
def showOne(self): Ventana2 = Toplevel(self.master) try: Ventana2.configure(height=210, width=428, bg="#FFFFFF") Ventana2.resizable(1, 1) Ventana2.title("Buscar") frameAux = Frame(Ventana2, height=210, width=428, bg="#4a4a4a") frameAux.place(x=0, y=0) if sys.platform.startswith('win32'): r = "image\\BuscarBosch.png" ruta = "image\\Back.png" ruta2 = "image\\SearchOne.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): r = "image/BuscarBosch.png" ruta = "image/Back.png" ruta2 = "image/SearchOne.png" l = Image.open(r) re = ImageTk.PhotoImage(l) labelFont = Label(frameAux, image=re, borderwidth=0) labelFont.image = re labelFont.place(x=0, y=0) labelText1 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Serie", fg="#FFFFFF", anchor=W) labelText1.config(font=("Tahoma", 11)) labelText1.place(x=15, y=25) labelText11 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText11.config(font=("Tahoma", 11)) labelText11.place(x=210, y=25) labelText2 = Label(frameAux, height=1, width=24, bg="#696969", text="Gravedad", fg="#FFFFFF", anchor=W) labelText2.config(font=("Tahoma", 11)) labelText2.place(x=15, y=50) labelText22 = Label(frameAux, height=1, width=24, bg="#696969", fg="#FFFFFF", anchor=W) labelText22.config(font=("Tahoma", 11)) labelText22.place(x=210, y=50) labelText3 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Fecha", fg="#FFFFFF", anchor=W) labelText3.config(font=("Tahoma", 11)) labelText3.place(x=15, y=75) labelText33 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText33.config(font=("Tahoma", 11)) labelText33.place(x=210, y=75) labell = Label(frameAux, height=1, width=25, bg="#4a4a4a", text="Ingresa el numero de serie", fg="#FFFFFF", anchor=W) #labell.place(x=15,y=135) labell.config(font=("Tahoma", 11)) listbox3 = Entry(frameAux, width=24, justify=RIGHT, bg="#696969", fg="#FFFFFF", borderwidth=0) listbox3.place(x=210, y=125) listbox3.config(font=("Tahoma", 11)) load = Image.open(ruta) render = ImageTk.PhotoImage(load) backbutton = Button( frameAux, image=render, bg="#8d8e8c", borderwidth=0, activebackground="#696969", command=lambda: self.Switch(self.master, Ventana2)) backbutton.image = render backbutton.place(x=245, y=155) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) searchButton = Button( frameAux, image=render2, bg="#8d8e8c", borderwidth=0, activebackground="#c4c4c4", command=lambda: self.load1(listbox3, labelText11, labelText22, labelText33)) searchButton.image = render2 searchButton.place(x=324, y=155) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar")
pop3.place(x=20,y=120) a=Canvas(r, bg="#5c8a8a", height=1, width=520,highlightthickness=0) a.place(x=20,y=160) b=Canvas(r, bg="#5c8a8a", height=1, width=520,highlightthickness=0) b.place(x=20,y=440) c=Canvas(r, bg="#5c8a8a", height=280, width=1,highlightthickness=0) c.place(x=20,y=160) d=Canvas(r, bg="#5c8a8a", height=280, width=1,highlightthickness=0) d.place(x=540,y=160) pop4=Label(r,text="Patient name",font='Helvetica 11 bold',bg="#ffffff") pop4.place(x=35,y=180) name=StringVar() pop5=Entry(r,bg="#ffffff",textvariable=name) pop5.place(x=270,y=180,width=250,height=22) pop6=Label(r,text="Email",font='Helvetica 11 bold',bg="#ffffff") pop6.place(x=35,y=220) email=StringVar() pop7=Entry(r,bg="#ffffff",textvariable=email) pop7.place(x=270,y=220,width=250,height=22) pop8=Label(r,text="Age",font='Helvetica 11 bold',bg="#ffffff") pop8.place(x=35,y=260) age=StringVar() pop9=Entry(r,bg="#ffffff",textvariable=age) pop9.place(x=270,y=260,width=250,height=22) pop10=Label(r,text="Gender",font='Helvetica 11 bold',bg="#ffffff") pop10.place(x=35,y=310) gender=StringVar() pop11=Radiobutton(r,text="Male",font='Helvetica 11 bold',bg="#ffffff",value="Male",variable=gender) pop11.place(x=290,y=310)
class EMNN(): def __init__(self, conn): conn.gui = True queue = self.queue = Queue.Queue() conn.queue = queue self.conn = conn def startgui(self): self.root = root = Tk() root.title('SIMAPSE - Simulation Maps for Ecological Niche Modelling') root.geometry('695x445+375+115') root.tk.call('encoding', 'system', 'utf-8') root.configure(bg='#d9d9d9') root.resizable(width='false', height='false') self.gui() self.root.after(100, self.periodicUpdate) root.mainloop() def gui(self): from Tkinter import Button, Entry, Frame, Label, Checkbutton, \ Scrollbar, Text, IntVar, StringVar, OptionMenu self.dir_project = '' self.folds = 0 self.func = "" self.aucfilter = IntVar() self.lightgray = '#d9d9d9' self.darkgray = '#d3d3d3' self.normaltext = ("Helvetica", -10) self.boldtext = ("Helvetica", -10, "bold") self.bigtext = ("Helvetica", -12, "bold") self.smalltext = ("Helvetica", -9) self.butData = Button(self.root) self.butData.place(in_=self.root, x=5, y=5) self.butData.configure(height=1, width=10, text="Data File", font=self.normaltext, highlightbackground=self.lightgray, command=self.dataOpen) self.butRasterFolder = Button(self.root) self.butRasterFolder.place(in_=self.root, x=5, y=35) self.butRasterFolder.configure(height=1, width=10, text="Raster Folder", font=self.normaltext, highlightbackground=self.lightgray, command=self.rasterOpen) self.butOutFolder = Button(self.root) self.butOutFolder.place(in_=self.root, x=5, y=65) self.butOutFolder.configure(height=1, width=10, text="Out Folder", font=self.normaltext, highlightbackground=self.lightgray, command=self.outOpen) self.entData = Entry(self.root) self.entData.place(in_=self.root, x=100, y=9) self.entData.configure(textvariable="file_data", font=self.normaltext, width=97, background=self.darkgray, relief="flat", highlightbackground=self.lightgray) self.entData.insert(0, '') self.entOutFolder = Entry(self.root) self.entOutFolder.place(in_=self.root, x=100, y=69) self.entOutFolder.configure(textvariable="out_dir", font=self.normaltext, width=97, background=self.darkgray, relief="flat", highlightbackground=self.lightgray) self.entOutFolder.insert(0, '') self.entRasterFolder = Entry(self.root) self.entRasterFolder.place(in_=self.root, x=100, y=39) self.entRasterFolder.configure(textvariable="dir_rasters", font=self.normaltext, width=97, background=self.darkgray, relief="flat", highlightbackground=self.lightgray) self.entRasterFolder.insert(0, '') self.activeMethod = StringVar(self.root) self.activeMethod.set("Random repetition") self.butMETHOD = OptionMenu( self.root, self.activeMethod, "Random repetition", "Cross validation", "Bootstrapping", command=lambda x: self.displayMethodFrame(x)) self.butMETHOD.place(in_=self.root, x=4, y=97, height="25", width="120") self.butMETHOD.configure(font=self.smalltext, background=self.lightgray) self.displayMethodFrame(self.activeMethod.get()) self.activeOption = StringVar(self.root) self.activeOption.set("Network structure") self.butOPTION = OptionMenu( self.root, self.activeOption, "Network structure", "Options", command=lambda x: self.displayOptionFrame(x)) self.butOPTION.place(in_=self.root, x=4, y=182, height="25", width="120") self.butOPTION.configure(font=self.smalltext, background=self.lightgray) self.displayOptionFrame(self.activeOption.get()) self.Progress_frame = Frame(self.root) self.Progress_frame.place(in_=self.root, x=5, y=423) self.Progress_frame.configure(borderwidth="2", relief='sunken', height="20", width="105", bg='white') self.Progress_bar = Label(self.Progress_frame) self.Progress_bar.place(x=0, y=0) self.Progress_bar.configure(font=self.smalltext) self.Progress_info = Label(self.root) self.Progress_info.place(x=110, y=425) self.Progress_info.configure(font=self.smalltext, bg=self.lightgray) self.frameButtons = Frame(self.root) self.frameButtons.place(in_=self.root, x=5, y=336) self.frameButtons.configure(borderwidth="2", bg=self.lightgray, relief="raise", height="84", width="260") self.butREAD = Button(self.root) self.butREAD.place(in_=self.frameButtons, x=5, y=5, width=70) self.butREAD.configure(font=self.bigtext, highlightbackground=self.lightgray, text="READ", command=self.read) self.butRUN = Button(self.root) self.butRUN.place(in_=self.frameButtons, x=80, y=5, width=70) self.butRUN.configure(font=self.bigtext, highlightbackground=self.lightgray, text="RUN", command=self.returnVar, state='disabled') self.butRESULTS = Button(self.root) self.butRESULTS.place(in_=self.frameButtons, x=155, y=5, width=80) self.butRESULTS.configure(font=self.bigtext, highlightbackground=self.lightgray, text="RESULTS", command=self.returnResults, state='disabled') self.butPROJECT = Button(self.root) self.butPROJECT.place(in_=self.frameButtons, x=5, y=45, width=70) self.butPROJECT.configure(font=self.boldtext, highlightbackground=self.lightgray, text="PROJECT", command=self.project, state='disabled') self.frameText = Frame(self.root) self.frameText.place(in_=self.root, x=270, y=100) self.frameText.configure(height=320, width=400) self.scrollbar = Scrollbar(self.root) self.textFrame = Text(self.frameText, wrap='word') self.textFrame.configure(font=self.normaltext, height="24", width="65") self.textFrame.place(x=0, y=0) self.textFrame.configure(yscrollcommand=self.scrollbar.set) self.scrollbar.configure(command=self.textFrame.yview, highlightbackground=self.lightgray) self.scrollbar.place(x=675, y=100, height=320) def displayMethodFrame(self, method): ''' Displays individual frames for the subsetting method''' from Tkinter import Button, Entry, Frame, Label if self.__dict__.has_key('frameMethodSelection'): self.frameMethodSelection.destroy() self.varupdate() c = self.conn.simargs self.frameMethodSelection = Frame(self.root) self.frameMethodSelection.place(in_=self.root, x=5, y=122) self.frameMethodSelection.configure(borderwidth="2", relief="raise", height="60", width="260", bg=self.lightgray) if method == "Random repetition": self.labRepetitions = Label(self.root) self.labRepetitions.place(in_=self.frameMethodSelection, x=2, y=10) self.labRepetitions.configure(font=self.normaltext, borderwidth="1", justify='left', anchor='e', bg=self.lightgray, text="Number of repetitions:") self.entRepetitions = Entry(self.root) self.entRepetitions.place(in_=self.frameMethodSelection, x=125, y=10) self.entRepetitions.configure(textvariable="repetitions", width="7", font=self.normaltext, highlightbackground=self.lightgray) self.entRepetitions.delete(0, 'end') self.entRepetitions.insert('end', c['repetitions']) elif method == "Cross validation": self.labRepetitions = Label(self.root) self.labRepetitions.place(in_=self.frameMethodSelection, x=2, y=10) self.labRepetitions.configure(font=self.normaltext, bg=self.lightgray, text="Number of folds:") self.entRepetitions = Entry(self.root) self.entRepetitions.place(in_=self.frameMethodSelection, x=100, y=10) self.entRepetitions.configure(textvariable="repetitions", width="7", highlightbackground=self.lightgray, font=self.normaltext) self.entRepetitions.delete(0, 'end') self.entRepetitions.insert('end', c['repetitions']) elif method == "Bootstrapping": self.labRepetition = Label(self.root) self.labRepetition.place(in_=self.frameMethodSelection, x=2, y=5) self.labRepetition.configure(borderwidth="1", text="Number of Bootstraps:", bg=self.lightgray, font=self.normaltext) self.entRepetitions = Entry(self.root) self.entRepetitions.place(in_=self.frameMethodSelection, x=125, y=5) self.entRepetitions.configure(textvariable="repetitions", width="7", highlightbackground=self.lightgray, font=self.normaltext) self.entRepetitions.delete(0, 'end') self.entRepetitions.insert('end', c['repetitions']) self.labBsize = Label(self.root) self.labBsize.place(in_=self.frameMethodSelection, x=2, y=30) self.labBsize.configure(borderwidth="1", text="Bootstraps Sample Size:", bg=self.lightgray, font=self.normaltext) self.entBsize = Entry(self.root) self.entBsize.place(in_=self.frameMethodSelection, x=125, y=30) self.entBsize.configure(textvariable="Bsize", width="7", highlightbackground=self.lightgray, font=self.normaltext) self.entBsize.delete(0, 'end') self.entBsize.insert('end', c['bsize']) def displayOptionFrame(self, option): ''' Displays individual frames for the subsetting method''' from Tkinter import Button, Entry, Frame, Label, Checkbutton if self.__dict__.has_key('frameOptionSelection'): self.frameOptionSelection.destroy() self.varupdate() c = self.conn.simargs self.frameOptionSelection = Frame(self.root) self.frameOptionSelection.place(in_=self.root, x=5, y=207) self.frameOptionSelection.configure(borderwidth="2", relief="raise", height="125", width="260", bg=self.lightgray) if option == "Network structure": self.labMaxiter = Label(self.root) self.labMaxiter.place(in_=self.frameOptionSelection, x=190, y=5) self.labMaxiter.configure(borderwidth="1", font=self.normaltext, text="Internal", bg=self.lightgray) self.labNNN = Label(self.root) self.labNNN.place(in_=self.frameOptionSelection, x=95, y=5) self.labNNN.configure(borderwidth="1", font=self.normaltext, text="Reported", bg=self.lightgray) self.labTI = Label(self.root) self.labTI.place(in_=self.frameOptionSelection, x=5, y=25) self.labTI.configure(borderwidth="1", font=self.normaltext, text="Total iterations =", bg=self.lightgray) self.entITERReport = Entry(self.root) self.entITERReport.place(in_=self.frameOptionSelection, x=88, y=25) self.entITERReport.configure(textvariable="AUCReport", width="10", font=self.normaltext, highlightbackground=self.lightgray) self.entITERReport.delete(0, 'end') self.entITERReport.insert('end', c['iterreport']) self.times = Label(self.root) self.times.place(in_=self.frameOptionSelection, x=160, y=25) self.times.configure(text="x", font=self.normaltext, bg=self.lightgray) self.entITERInter = Entry(self.root) self.entITERInter.place(in_=self.frameOptionSelection, x=180, y=25) self.entITERInter.configure(textvariable="maxiter", width="10", font=self.normaltext, highlightbackground=self.lightgray) self.entITERInter.delete(0, 'end') self.entITERInter.insert('end', c['iterinter']) self.labEta = Label(self.root) self.labEta.place(in_=self.frameOptionSelection, x=5, y=55) self.labEta.configure(borderwidth="1", font=self.normaltext, text="Learning Rate", bg=self.lightgray) self.butHINT = Button(self.root) self.butHINT.place(in_=self.frameOptionSelection, x=65, y=75, height=23, width=20) self.butHINT.configure(font=self.smalltext, text="H", command=self.hint, state='disabled', highlightbackground=self.lightgray) self.labMomentum = Label(self.root) self.labMomentum.place(in_=self.frameOptionSelection, x=88, y=55) self.labMomentum.configure(borderwidth="1", font=self.normaltext, text="Momentum", bg=self.lightgray) self.entLRATE = Entry(self.root) self.entLRATE.place(in_=self.frameOptionSelection, x=5, y=75) self.entLRATE.configure(textvariable="eta", width="8", font=self.normaltext, highlightbackground=self.lightgray) self.entLRATE.delete(0, 'end') self.entLRATE.insert('end', c['lrate']) self.entMomentum = Entry(self.root) self.entMomentum.place(in_=self.frameOptionSelection, x=90, y=75) self.entMomentum.configure(textvariable="momentum", width="8", font=self.normaltext, highlightbackground=self.lightgray) self.entMomentum.delete(0, 'end') self.entMomentum.insert('end', c['momentum']) self.labNNS = Label(self.root) self.labNNS.place(in_=self.frameOptionSelection, x=165, y=55) self.labNNS.configure(borderwidth="1", font=self.normaltext, text="Hidden Layers", bg=self.lightgray) self.entNNShape = Entry(self.root) self.entNNShape.place(in_=self.frameOptionSelection, x=160, y=75) self.entNNShape.configure(textvariable="HiddenLyr", width="14", font=self.normaltext, highlightbackground=self.lightgray) self.entNNShape.delete(0, 'end') self.entNNShape.insert('end', c['hiddenlyrs']) elif option == "Options": self.labPercentage = Label(self.root) self.labPercentage.place(in_=self.frameOptionSelection, x=2, y=5) self.labPercentage.configure(borderwidth="1", text="Test %:", font=self.normaltext, bg=self.lightgray) self.entPercentage = Entry(self.root) self.entPercentage.place(in_=self.frameOptionSelection, x=45, y=5, width=30) self.entPercentage.configure(textvariable="Percentage", font=self.normaltext, highlightbackground=self.lightgray) self.entPercentage.delete(0, 'end') self.entPercentage.insert('end', c['percentage']) self.labAPRatio = Label(self.root) self.labAPRatio.place(in_=self.frameOptionSelection, x=80, y=5) self.labAPRatio.configure(borderwidth="1", text="Pseudoabsences/Presences:", font=self.normaltext, bg=self.lightgray) self.entAPRatio = Entry(self.root) self.entAPRatio.place(in_=self.frameOptionSelection, x=220, y=5) self.entAPRatio.configure(textvariable="apratio", width="4", font=self.normaltext, highlightbackground=self.lightgray) self.entAPRatio.delete(0, 'end') self.entAPRatio.insert('end', c['apratio']) self.labBurnin = Label(self.root) self.labBurnin.place(in_=self.frameOptionSelection, x=2, y=30) self.labBurnin.configure(borderwidth="1", text="Burn-in iterations:", font=self.normaltext, bg=self.lightgray) self.entBurnin = Entry(self.root) self.entBurnin.place(in_=self.frameOptionSelection, x=90, y=30) self.entBurnin.configure(textvariable="burnin", width="8", font=self.normaltext, highlightbackground=self.lightgray) self.entBurnin.delete(0, 'end') self.entBurnin.insert('end', c['burnin']) self.chkAucFilter = Checkbutton(self.root) self.chkAucFilter.place(in_=self.frameOptionSelection, x=2, y=60) self.chkAucFilter.configure(font=self.normaltext, text="Filter with AUC threshold", variable=self.aucfilter, bg=self.lightgray, command=self.aucstate) self.labAUCTrain = Label(self.root) self.labAUCTrain.place(in_=self.frameOptionSelection, x=5, y=85) self.labAUCTrain.configure(borderwidth="1", font=self.normaltext, text="training data", bg=self.lightgray) self.entAUCTrain = Entry(self.root) self.entAUCTrain.place(in_=self.frameOptionSelection, x=70, y=85) self.entAUCTrain.configure(textvariable="valueAuc", width="8", font=self.normaltext, highlightbackground=self.lightgray) self.entAUCTrain.delete(0, 'end') self.entAUCTrain.insert('end', c['auctrain']) self.labAUCTest = Label(self.root) self.labAUCTest.place(in_=self.frameOptionSelection, x=130, y=85) self.labAUCTest.configure(borderwidth="1", font=self.normaltext, text="testing data", bg=self.lightgray) self.entAUCTest = Entry(self.root) self.entAUCTest.place(in_=self.frameOptionSelection, x=195, y=85) self.entAUCTest.configure(textvariable="valueAucTest", width="8", font=self.normaltext, highlightbackground=self.lightgray) self.entAUCTest.delete(0, 'end') self.entAUCTest.insert('end', c['auctest']) self.aucstate() def varupdate(self): extract = self.extract c = self.conn.simargs c['file_data'] = extract('entData', c['file_data']) c['dir_rasters'] = extract('entRasterFolder', c['dir_rasters']) c['out_dir'] = extract('entOutFolder', c['out_dir']) c['method'] = extract('activeMethod', c['method']) c['iterreport'] = int(extract('entITERReport', c['iterreport'])) c['iterinter'] = int(extract('entITERInter', c['iterinter'])) c['lrate'] = float(extract('entLRATE', c['lrate'])) c['momentum'] = float(extract('entMomentum', c['momentum'])) c['hiddenlyrs'] = extract('entNNShape', c['hiddenlyrs']) c['apratio'] = float(extract('entAPRatio', c['apratio'])) c['percentage'] = int(extract('entPercentage', c['percentage'])) c['burnin'] = int(extract('entBurnin', c['burnin'])) c['auctrain'] = float(extract('entAUCTrain', c['auctrain'])) c['auctest'] = float(extract('entAUCTest', c['auctest'])) c['repetitions'] = int(extract('entRepetitions', c['repetitions'])) c['bsize'] = int(extract('entBsize', c['bsize'])) c['aucfilter'] = bool(extract('aucfilter', int(c['aucfilter']))) def extract(self, test, default): if test in self.__dict__.keys(): value = self.__dict__[test].get() else: value = default return value def read(self): import time self.varupdate() self.conn.processor(self.conn.manager.read_all, 'read') def returnVar(self): # Updates variables self.varupdate() self.conn.processor(self.conn.manager.model, 'run') def returnResults(self): self.varupdate() self.conn.processor(self.conn.manager.results, 'results') def project(self): self.varupdate() project_dir = askdirectory() self.conn.simargs['project_dir'] = project_dir self.conn.processor(self.conn.manager.project, 'project') def hint(self): self.varupdate() self.conn.processor(self.conn.manager.hint, 'hint') def dataOpen(self): self.entData.delete(0, 'end') file_data = askopenfilename(filetypes=[("text files", "*.txt"), ("allfiles", "*")]) self.entData.insert('end', file_data) def rasterOpen(self): self.entRasterFolder.delete(0, 'end') dir_rasters = askdirectory() self.entRasterFolder.insert('end', dir_rasters) def outOpen(self): self.entOutFolder.delete(0, 'end') out_dir = askdirectory() self.entOutFolder.insert('end', out_dir) def update_text(self, string_txt): txt = string_txt + " \n" self.textFrame.insert('end', txt) self.textFrame.yview('end') def processGraph(self, graph_object): '''Just a wraper to call the graphics creation object''' graph_object() def periodicUpdate(self): """Executes periodic checks to GUI: - if there are new messages and displays when true""" try: while 1: code, args, kwargs = self.queue.get_nowait() if code == Connector.CODE_TEXT: self.update_text(*args) elif code == Connector.CODE_PROGRESS: self.progress(*args, **kwargs) elif code == Connector.CODE_MODIFY_BUTTON: self.modify_but(*args) elif code == Connector.CODE_SHOWRESULTS: self.showResults(*args) elif code == Connector.CODE_GRAPHS: self.processGraph(args) else: self.update_text('Unknown message...') self.queue.task_done() self.root.update() except Queue.Empty: pass self.root.after(100, self.periodicUpdate) def modify_but(self, state, buttonlist): if buttonlist == 'all': buttonlist = [ 'READ', 'RUN', 'RESULTS', 'PROJECT', 'HINT', 'METHOD', 'OPTION' ] for button in buttonlist: but = "self.but%s.configure(state=\'%s\')" % (button, state) exec(but) def abundance(self): self.entAUCTrain.configure(state='disabled') self.entAUCTest.configure(state='disabled') def aucstate(self): if self.aucfilter.get(): state = 'normal' else: state = 'disabled' self.entAUCTrain.configure(state=state) self.entAUCTest.configure(state=state) def progress(self, value, maxvalue, **kwargs): '''Shows the progress bar in GUI args are: Value - Value of the current progress MaxValue - Value where progress terminates kwargs are color - Color for the progess bar msg - message to display''' color = 'blue' if 'color' in kwargs: color = kwargs['color'] percent = (value * 100) / maxvalue self.Progress_bar.configure(font=self.smalltext, foreground="white", background=color) #"#0000ff" if percent <> 100: width = int((percent / 100.000) * 20) text = '%s%%' % percent self.Progress_bar.configure(text=text, width=width) if 'msg' in kwargs: self.Progress_info.configure(text=kwargs['msg']) elif percent == 100: self.Progress_bar.configure(text="", width=0, relief="flat", background="#ece9d8") self.Progress_info.configure(text="") def showResults(self, figures): from Tkinter import Button figures = [self.entOutFolder.get() + "/" + x for x in figures] ResultsWindow = mytoplevel(self.root, figures, self) ResultsWindow.title('Results') butRW = Button(ResultsWindow, text='CLOSE', command=ResultsWindow.destroy) butRW.pack() def update_queue(self): try: while self.queue.qsize(): msg = '%s\n' % self.queue.get(0) self.textFrame.insert('end', msg) self.textFrame.yview('end') except Queue.Empty: pass
class System(Rename): def __init__(self): Rename.__init__(self) ## MASTER PATHS self.userName = os.path.expanduser("~") self.systemLocation = self.userName + '\\Copy\\GHOST\\CINEMATIC_SCRIPTS\\' ## PROGRAMS self.vlc = '"C:\\Program Files (x86)\\VideoLAN\\VLC\\vlc.exe"' self.djv = '"C:\\Program Files (x86)\\djv 0.8.3\\bin\\djv_convert"' self.ffmpeg = self.systemLocation + "programs\\FFMPEG\\ffmpeg" self.ffprobe = self.systemLocation + "programs\\FFMPEG\\ffprobe" self.redline = '"C:\\Program Files\\REDCINE-X PRO 64-bit\\REDline"' self.vdub = self.systemLocation + "programs\\vDub\\vdub64.exe" self.mencoder = self.systemLocation + "programs\\MPlayer\\mencoder" ## FOLDER LOCATIONS self.libraries = self.systemLocation + "libraries" self.images = self.systemLocation + "images" self.files = self.systemLocation + "libraries\\files" self.scripts = self.userName +"\\Documents\\GitHub\\JR_Video\\scripts" self.settings = self.userName +"\\Documents\\GitHub\\JR_Video\\settings" self.sequences = self.systemLocation + "test\\sequences" self.TKicon = self.userName +"\\Documents\\GitHub\\JR_Video\\icons\\icon.ico" # CACHE ITEMS self.BRC = '' self.windowOpen = 1 ## SETTINGS self.movie_ext = ('.mov', '.R3D', '.MXF', '.mp4', '.MP4' , '.avi') self.image_ext = ('.jpg','.tiff','.png', '.tga', '.exr') # VDUB COMPRESSION self.compression = ( self.settings + '\\vDub_compression\\vDub_avi_compression.vcf', self.settings + '\\vDub_compression\\vDub_avi_compression_custom_01.vcf', self.settings + '\\vDub_compression\\vDub_avi_compression_custom_02.vcf', self.settings + '\\vDub_compression\\vDub_avi_compression_23976.vcf' ) # PRORES self.prores = { 'ProRes422_Proxy': 0, 'ProRes422_LT':1, 'ProRes422_Normal':2, 'ProRes422_HQ':3 } def systemStart(self, app): os.system('"''start '+app+'"') def findParentFolder(self, input_data): processed = self.processInput(input_data) file_path2 = processed[2] parent_dir = file_path2[1+[i for i, letter in enumerate(file_path2) if letter == '\\' or letter =='/'][-2]:-1] return parent_dir def findFolder(self, input_data, folderName): if folderName in input_data: ii = input_data.find(folderName) pp = [i for i, letter in enumerate(input_data) if letter == '\\'] high = [x for x in pp if x > ii] low = [x for x in pp if x < ii] return input_data[:high[0]], input_data[low[-1]+1:high[0]] def findVersioning(self, input_data): processed = self.processInput(input_data) parent_dir = self.findParentFolder(input_data) if 'v' in parent_dir: X = parent_dir.lower().rfind('v') if parent_dir[X+1:X+2].isdigit(): if 'v' in processed[3].lower(): X = input_data.lower().rfind('v') if input_data[X+1:X+2].isdigit(): Y = input_data[X+1:] break_list = [] for i in range(len(Y)): if Y[i].isdigit(): pass else: break_list.append(i) break return input_data[X:X+break_list[0]+1] else: return '' elif 'v' in input_data.lower(): X = input_data.lower().rfind('v') if input_data[X+1:X+2].isdigit(): Y = input_data[X+1:] break_list = [] for i in range(len(Y)): if Y[i].isdigit(): pass else: break_list.append(i) break return input_data[X:X+break_list[0]+1] else: return '' def setDirectory(self, message = 'Please select a folder'): root = Tkinter.Tk() root.withdraw() X = tkFileDialog.askdirectory(parent=root,initialdir="/",title= message) return X def returnItem(self, item): self.BRC = item self.tk.destroy() def setProResFormat(self): pass def getFileList (self, dirPath, name, uniq=True,sorted=True): X = [] for dirpath,dirnames,filenames in os.walk(dirPath): for file in filenames: if name == '': if file.endswith(self.image_ext): X.append(dirpath) elif name.lower() in file.lower(): X.append(dirpath) return X #Y = set(X) #return sorted(Y) #self.screenshotDirectory.append(dirpath) def regFind(self, itemToSearch, searchForThis): d = itemToSearch s = re.compile(r'/*'+searchForThis) # this finds the backslashes in the to be created directory f = s.finditer(d) g = [ x.span() for x in f ] return g def RenameWindow(self, input_data): #print input_data try: self.tk except AttributeError: self.tk = TK.Tk() self.tk.iconbitmap(default= self.TKicon) self.tk.geometry('200x120') #TITLE self.tk.title('Rename') # COLOURS bgColour = '#2f2f2f' self.btnColour2 = '#098400' input_bgColour = '#cecece' input_fgColour = 'black' # POSITION pointer_x = self.tk.winfo_pointerx() pointer_y = self.tk.winfo_pointery() self.tk.geometry('+'+str(int(pointer_x))+'+'+str(pointer_y) ) self.tk.resizable(width=FALSE, height=FALSE) # LABELS labelOffset = 25 Name = Label(text = 'Name :', bg = bgColour, fg = 'white').place(x=8, y=5) scene = Label(text = 'Replace :', bg = bgColour, fg = 'white').place(x=8, y=5+labelOffset) shots = Label(text = 'With :', bg = bgColour, fg = 'white').place(x=8, y=30+labelOffset) ## INPUT FIELDS # self.name_field = Entry(bg = input_bgColour, fg=input_fgColour, bd = 0) self.replace_field = Entry(bg = input_bgColour, fg=input_fgColour, bd = 0) self.with_field = Entry(bg = input_bgColour, fg=input_fgColour, bd = 0) a= self.processFinalName(input_data) self.name_field.insert(0,a) #self.name_field.focus() # INPUT FIELD POSITION self.name_field.place(x=60, y= 8) self.replace_field.place(x=60, y= 8+labelOffset ) self.with_field.place(x=60, y=33 + labelOffset ) # # BUTTON OPTIONS renameBtn = Button(text = 'RENAME', bg = bgColour, fg = 'white', width = 200 , command = partial(self.rename_custom, input_data ) ) #partial(return self.name_field, self.replace_field, self.with_field) ) # BUTTON POSITION renameBtn.pack(side = 'bottom' ) # self.tk.configure(background= bgColour) self.tk.bind('<Escape>', quit) # BIND TO ESC KEY self.tk.bind('<Return>', partial(self.rename_custom, input_data )) #self.tk.bind("<FocusOut>", self.killWindow) self.tk.mainloop() if Name.winfo_exists() == True: self.windowOpen = 1 else: self.windowOpen = 0 def rename_custom(self, input_data, *args): #print input_data self.custom_list = [self.name_field.get(), self.replace_field.get(), self.with_field.get()] self.tk.destroy() self.manual_rename = 'yes' self.rename_auto(input_data) #self.RenameWindow(input_data) def processRename(self, old, new): #print old #print new #print '#####' os.rename(old, new) def findImageSequence(self, input_data): fileList = [] processed = self.processInput(input_data) file_ext = processed[0] file_path = processed[2] original_name = self.processFinalName(input_data) os.chdir(file_path) for files in os.listdir("."): if original_name in files: X = file_path+files if len(self.processFinalName(X)) == len(original_name): if files.endswith(file_ext): fileList.append(files) return fileList def rename_auto(self, input_data): try: self.manual_rename except AttributeError: self.manual_rename = 'no' self.selection = [input_data] processed = self.processInput(input_data) file_path2 = processed[2] parent_dir = file_path2[1+[i for i, letter in enumerate(file_path2) if letter == '\\' or letter =='/'][-2]:-1] # find the parent folder name for automatically renaming file_extension2 = processed[0] original_name2 = self.processFinalName(input_data) ################################################## #fileList = [] #os.chdir(file_path2) #for files in os.listdir("."): # if original_name2 in files: # test = file_path2+files # if len(self.processFinalName(test)) == len(original_name2): # if files.endswith(file_extension2): # fileList.append(files) fileList = self.findImageSequence(input_data) iterator = -1 new_return = [] # this is for the return so the mov converters know what it is now ver = self.findVersioning(input_data) for x in sorted(fileList): #self.findVersioning(x) iterator +=1 if len(str(iterator)) == 1: padding = '000' elif len(str(iterator)) == 2: padding = '00' elif len(str(iterator)) == 3: padding = '0' else: padding = '' if self.manual_rename == 'yes': if self.custom_list[1] != '': replace_name = original_name2.replace(self.custom_list[1], self.custom_list[2]) y = replace_name + '_' + padding + str(iterator) + file_extension2 else: #print 'top' if self.custom_list[0][0] == '_': #print 'suffix' ### this is a suffix y = original_name2 + self.custom_list[0] + '_' + padding + str(iterator) + file_extension2 elif self.custom_list[0][-1] == '_': ### this is a prefix y = self.custom_list[0] + original_name2 + '_' + padding + str(iterator) + file_extension2 else: y = self.custom_list[0] + '_' + padding + str(iterator) + file_extension2 #y = parent_dir + '_' + padding + str(iterator) + file_extension2 else: if ver == '': y = parent_dir + '_' + padding + str(iterator) + file_extension2 else: y = parent_dir + '_' + ver + '_' + padding + str(iterator) + file_extension2 old = file_path2 + x new = file_path2 + y new_return.append(new) self.processRename(old, new) #os.rename(old, new) #os.rename(old, new) return new_return[0] # this is to return any item after it is renamed, for use in other functions """
hist_dim_label = Label(f_1, text='Размерность гистограммы') hist_dimension_entry = Entry(f_1, width=13, bd=3) hist_dimension_entry.insert(END, '1') metric_label = Label(f_1, text='Метрика сравнения гистограмм') metric_entry = Entry(f_1, width=13, bd=3) metric_entry.insert(END, 'MANHATTAN') # Создаем объекты изображений, чтобы их можно было менять из функции imgobj1 = model_image_canv.create_image(0, 0) imgobj2 = query_image_canv.create_image(0, 0) # Расположение всех выше указанных компонентов на форме # (в относиельных координатах) f_1.pack() model_path_label.place(relx=0.01, rely=0.003) model_path_entry.place(relx=0.01, rely=0.053) open_model_button.place(relx=0.36, rely=0.051) sensitivity_label.place(relx=0.02, rely=0.113) sensitivity_entry.place(relx=0.01, rely=0.193) num_of_parts_label.place(relx=0.25, rely=0.113) num_of_parts_X_entry.place(relx=0.255, rely=0.193) num_of_parts_Y_entry.place(relx=0.357, rely=0.193) def_finding_button.place(relx=0.443, rely=0.5) model_image_label.place(relx=0.12, rely=0.28) model_image_canv.place(relx=0.01, rely=0.33) query_image_label.place(relx=0.65, rely=0.28) query_image_canv.place(relx=0.57, rely=0.33) query_path_label.place(relx=0.55, rely=0.003) query_path_entry.place(relx=0.55, rely=0.053) open_query_button.place(relx=0.9, rely=0.051) color_model_label.place(relx=0.55, rely=0.119)
def readFile(self, filename, wel): #lblFile= Label(self, text=filename+" has successfully added", width=6) #lblFile.pack(side=LEFT, anchor=N, padx=5, pady=5) wel.pack_forget() f = open(filename, "r") text = f.read() L1 = Label(self, text="Size of property") L1.place(x=20, y=30) E1 = Entry(self, bd=5) E1.place(x=150, y=30) L2 = Label(self, text="Swimming pool") L2.place(x=20, y=60) E2 = Entry(self, bd=5) E2.place(x=150, y=60) L3 = Label(self, text="type") L3.place(x=20, y=90) E3 = Entry(self, bd=5) E3.place(x=150, y=90) L4 = Label(self, text="Interior") L4.place(x=20, y=120) E4 = Entry(self, bd=5) E4.place(x=150, y=120) L5 = Label(self, text="Lawn") L5.place(x=20, y=150) E5 = Entry(self, bd=5) E5.place(x=150, y=150) L6 = Label(self, text="View") L6.place(x=20, y=180) E6 = Entry(self, bd=5) E6.place(x=150, y=180) L7 = Label(self, text="Locality") L7.place(x=20, y=210) E7 = Entry(self, bd=5) E7.place(x=150, y=210) L8 = Label(self, text="Bathrooms") L8.place(x=20, y=240) E8 = Entry(self, bd=5) E8.place(x=150, y=240) L9 = Label(self, text="Parking") L9.place(x=20, y=270) E9 = Entry(self, bd=5) E9.place(x=150, y=270) cal = Button( self, text="Calculate", command=lambda: self.cal(filename, E1.get(), E2.get(), E3.get( ), E4.get(), E5.get(), E6.get(), E7.get(), E8.get(), E9.get())) cal.place(x=100, y=300)
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)
def initUI(self): self.parent.title("Property Rate Prediction System") self.pack(fill=BOTH, expand=1) menubar = Menu(self.parent) self.parent.config(menu=menubar) wel = Label(self, text="Welcome to property rate predictor", font=("Helvetica", 30)) wel.place( x=200,y=10) fileMenu = Menu(menubar) fileMenu.add_command(label="Exit", underline=0, command=self.onExit) menubar.add_cascade(label="File", underline=0, menu=fileMenu) L1 = Label(self, text="Num of bedrooms") L1.place( x=20,y=50) E1 = Entry(self, bd =5) E1.insert(0,'Only Integer') E1.place( x=150,y=50) L2 = Label(self, text="Swimming pool") L2.place( x=20,y=80) E2 = Entry(self, bd =5) E2.insert(0,'0->N0,1->Yes') E2.place( x=150,y=80) L3 = Label(self, text="type") L3.place( x=20,y=110) E3 = Entry(self, bd =5) E3.insert(0,'0->Bungalow,1->Apartment') E3.place( x=150,y=110) L4 = Label(self, text="Interior") L4.place( x=20,y=140) E4 = Entry(self, bd =5) E4.insert(0,'Rate from 0 to 5') E4.place( x=150,y=140) L5 = Label(self, text="Lawn") L5.place( x=20,y=170) E5 = Entry(self, bd =5) E5.insert(0,'0->N0,1->Yes') E5.place( x=150,y=170) L6 = Label(self, text="View") L6.place( x=20,y=200) E6 = Entry(self, bd =5) E6.insert(0,'Rate from 0 to 5') E6.place( x=150,y=200) L7 = Label(self, text="Locality") L7.place( x=20,y=230) E7 = Entry(self, bd =5) E7.insert(0,'Rate from 0 to 5') E7.place( x=150,y=230) L8 = Label(self, text="Bathrooms") L8.place( x=20,y=260) E8 = Entry(self, bd =5) E8.insert(0,'Only Integer') E8.place( x=150,y=260) L9 = Label(self, text="Parking") L9.place( x=20,y=290) E9 = Entry(self, bd =5) E9.insert(0,'0->N0,1->Yes') E9.place( x=150,y=290) cal=Button(self, text="Calculate", command=lambda:self.cal(E1.get(),E2.get(),E3.get(),E4.get(),E5.get(),E6.get(),E7.get(),E8.get(),E9.get())) cal.place( x=100,y=390) exit=Button(self, text="Exit", command=self.onExit) exit.place( x=200,y=390)
class _Hatch_GUI(object): """ create a Hatch object from hatch_supt and to then create a skeleton python project. """ def __init__(self, master): self.initComplete = 0 self.master = master self.x, self.y, self.w, self.h = -1, -1, -1, -1 # bind master to <Configure> in order to handle any resizing, etc. # postpone self.master.bind("<Configure>", self.Master_Configure) self.master.bind('<Enter>', self.bindConfigure) self.master.title("PyHatch GUI") self.master.resizable(0, 0) # Linux may not respect this dialogframe = Frame(master, width=810, height=630) dialogframe.pack() self.Shortdesc_Labelframe = LabelFrame( dialogframe, text="Short Description (1-liner)", height="90", width="718") self.Shortdesc_Labelframe.place(x=60, y=127) helv20 = tkFont.Font(family='Helvetica', size=20, weight='bold') self.Buildproject_Button = Button(dialogframe, text="Build Project", width="15", font=helv20) self.Buildproject_Button.place(x=492, y=10, width=263, height=68) self.Buildproject_Button.bind("<ButtonRelease-1>", self.Buildproject_Button_Click) self.Selectdir_Button = Button(dialogframe, text="<Select Directory>", width="15") self.Selectdir_Button.place(x=72, y=585, width=672, height=31) self.Selectdir_Button.bind("<ButtonRelease-1>", self.Selectdir_Button_Click) self.Author_Entry = Entry(dialogframe, width="15") self.Author_Entry.place(x=228, y=424, width=187, height=21) self.Author_Entry_StringVar = StringVar() self.Author_Entry.configure(textvariable=self.Author_Entry_StringVar) self.Author_Entry_StringVar.set("John Doe") self.Classname_Entry = Entry(dialogframe, width="15") self.Classname_Entry.place(x=192, y=73, width=165, height=21) self.Classname_Entry_StringVar = StringVar() self.Classname_Entry.configure( textvariable=self.Classname_Entry_StringVar) self.Classname_Entry_StringVar.set("MyClass") self.Copyright_Entry = Entry(dialogframe, width="15") self.Copyright_Entry.place(x=228, y=478, width=461, height=21) self.Copyright_Entry_StringVar = StringVar() self.Copyright_Entry.configure( textvariable=self.Copyright_Entry_StringVar) self.Copyright_Entry_StringVar.set("Copyright (c) 2013 John Doe") self.Email_Entry = Entry(dialogframe, relief="sunken", width="15") self.Email_Entry.place(x=228, y=505, width=458, height=21) self.Email_Entry_StringVar = StringVar() self.Email_Entry.configure(textvariable=self.Email_Entry_StringVar) self.Email_Entry_StringVar.set("*****@*****.**") self.GithubUserName_Entry = Entry(dialogframe, relief="sunken", width="15") self.GithubUserName_Entry.place(x=228, y=539, width=458, height=21) self.GithubUserName_Entry_StringVar = StringVar() self.GithubUserName_Entry.configure( textvariable=self.GithubUserName_Entry_StringVar) self.GithubUserName_Entry_StringVar.set("github_user_name") self.Funcname_Entry = Entry(dialogframe, width="15") self.Funcname_Entry.place(x=192, y=100, width=157, height=21) self.Funcname_Entry_StringVar = StringVar() self.Funcname_Entry.configure( textvariable=self.Funcname_Entry_StringVar) self.Funcname_Entry_StringVar.set("my_function") # License values should be correct format LICENSE_OPTIONS = tuple(sorted(CLASSIFIER_D.keys())) self.License_Entry_StringVar = StringVar() self.License_Entry = OptionMenu(dialogframe, self.License_Entry_StringVar, *LICENSE_OPTIONS) self.License_Entry.place(x=552, y=424, width=184, height=21) self.License_Entry_StringVar.set(LICENSE_OPTIONS[0]) self.Mainpyname_Entry = Entry(dialogframe, width="15") self.Mainpyname_Entry.place(x=168, y=37, width=196, height=21) self.Mainpyname_Entry_StringVar = StringVar() self.Mainpyname_Entry.configure( textvariable=self.Mainpyname_Entry_StringVar) self.Mainpyname_Entry_StringVar.set("main.py") self.Projname_Entry = Entry(dialogframe, width="15") self.Projname_Entry.place(x=168, y=10, width=194, height=21) self.Projname_Entry_StringVar = StringVar() self.Projname_Entry.configure( textvariable=self.Projname_Entry_StringVar) self.Projname_Entry_StringVar.set("MyProject") self.Shortdesc_Entry = Entry(dialogframe, width="15") self.Shortdesc_Entry.place(x=72, y=150, width=688, height=48) self.Shortdesc_Entry_StringVar = StringVar() self.Shortdesc_Entry.configure( textvariable=self.Shortdesc_Entry_StringVar) self.Shortdesc_Entry_StringVar.set("My project does this") # Status must be correct format self.Status_Entry_StringVar = StringVar() self.Status_Entry = OptionMenu(dialogframe, self.Status_Entry_StringVar, *DEV_STATUS_OPTIONS) self.Status_Entry.place(x=228, y=451, width=183, height=21) self.Status_Entry_StringVar.set(DEV_STATUS_OPTIONS[0]) self.Version_Entry = Entry(dialogframe, width="15") self.Version_Entry.place(x=552, y=451, width=184, height=21) self.Version_Entry_StringVar = StringVar() self.Version_Entry.configure(textvariable=self.Version_Entry_StringVar) self.Version_Entry_StringVar.set("0.1.1") self.Author_Label = Label(dialogframe, text="Author", width="15") self.Author_Label.place(x=96, y=424, width=112, height=22) self.Classname_Label = Label(dialogframe, text="Class Name", width="15") self.Classname_Label.place(x=60, y=73, width=112, height=22) self.Copyright_Label = Label(dialogframe, text="Copyright", width="15") self.Copyright_Label.place(x=96, y=478, width=113, height=23) self.Email_Label = Label(dialogframe, text="Email", width="15") self.Email_Label.place(x=96, y=505, width=113, height=23) self.GithubUserName_Label = Label(dialogframe, text="GithubUserName", width="15") self.GithubUserName_Label.place(x=96, y=539, width=113, height=23) self.Funcname_Label = Label(dialogframe, text="Function Name", width="15") self.Funcname_Label.place(x=60, y=100, width=112, height=22) self.License_Label = Label(dialogframe, text="License", width="15") self.License_Label.place(x=432, y=424, width=113, height=23) self.Longdesc_Label = Label(dialogframe, text="Paragraph Description", width="15") self.Longdesc_Label.place(x=216, y=220, width=376, height=22) self.Mainpyname_Label = Label(dialogframe, text="Main Python File", width="15") self.Mainpyname_Label.place(x=48, y=37, width=112, height=22) self.Projname_Label = Label(dialogframe, text="Project Name", width="15") self.Projname_Label.place(x=48, y=10, width=112, height=22) self.Selectdir_Label = Label( dialogframe, text="Select the Directory Below Which to Place Your Project", width="15") self.Selectdir_Label.place(x=156, y=567, width=536, height=24) self.Status_Label = Label(dialogframe, text="Status", width="15") self.Status_Label.place(x=96, y=451, width=114, height=24) self.Version_Label = Label(dialogframe, text="Version", width="15") self.Version_Label.place(x=432, y=451, width=113, height=23) self.Isclass_Radiobutton = Radiobutton(dialogframe, text="Class Project", value="Class Project", width="15", anchor=W) self.Isclass_Radiobutton.place(x=320, y=73, width=135, height=27) self.RadioGroup1_StringVar = StringVar() self.RadioGroup1_StringVar.set("Class Project") self.RadioGroup1_StringVar_traceName = \ self.RadioGroup1_StringVar.trace_variable("w", self.RadioGroup1_StringVar_Callback) self.Isclass_Radiobutton.configure(variable=self.RadioGroup1_StringVar) self.Isfunction_Radiobutton = Radiobutton(dialogframe, text="Function Project", value="Function Project", width="15", anchor=W) self.Isfunction_Radiobutton.place(x=320, y=100, width=135, height=27) self.Isfunction_Radiobutton.configure( variable=self.RadioGroup1_StringVar) lbframe = Frame(dialogframe) self.Text_1_frame = lbframe scrollbar = Scrollbar(lbframe, orient=VERTICAL) self.Text_1 = Text(lbframe, width="40", height="6", yscrollcommand=scrollbar.set) scrollbar.config(command=self.Text_1.yview) scrollbar.pack(side=RIGHT, fill=Y) self.Text_1.pack(side=LEFT, fill=BOTH, expand=1) self.Text_1_frame.place(x=72, y=250, width=665, height=160) # >>>>>>insert any user code below this comment for section "top_of_init" self.dirname = '<Select Directory>' self.Funcname_Entry.config(state=DISABLED) h = Hatch(projName='MyProject', mainDefinesClass='N') if h.author: self.Author_Entry_StringVar.set(h.author) if h.proj_license: self.License_Entry_StringVar.set(h.proj_license) if h.proj_copyright: self.Copyright_Entry_StringVar.set(h.proj_copyright) if h.email: self.Email_Entry_StringVar.set(h.email) if h.github_user_name: self.GithubUserName_Entry_StringVar.set(h.github_user_name) del h def build_result_dict(self): """Takes user inputs from GUI and builds a dictionary of results""" # pylint: disable=W0201 self.result = {} # return a dictionary of results self.result["author"] = self.Author_Entry_StringVar.get() self.result["status"] = self.Status_Entry_StringVar.get() self.result["proj_license"] = self.License_Entry_StringVar.get() self.result["version"] = self.Version_Entry_StringVar.get() self.result["proj_copyright"] = self.Copyright_Entry_StringVar.get() self.result["email"] = self.Email_Entry_StringVar.get() self.result[ "github_user_name"] = self.GithubUserName_Entry_StringVar.get() self.result["main_py_name"] = self.Mainpyname_Entry_StringVar.get() self.result["proj_name"] = self.Projname_Entry_StringVar.get() self.result["class_name"] = self.Classname_Entry_StringVar.get() self.result["func_name"] = self.Funcname_Entry_StringVar.get() self.result["short_desc"] = self.Shortdesc_Entry_StringVar.get() self.result["para_desc"] = self.Text_1.get(1.0, END) self.result["parent_dir"] = self.dirname if self.RadioGroup1_StringVar.get() == "Class Project": self.result["is_class_project"] = 'Y' else: self.result["is_class_project"] = 'N' def Buildproject_Button_Click(self, event): """When clicked, this method gathers all the user inputs and builds the project skeleton in the directory specified. """ # tkinter requires arguments, but I don't use them # pylint: disable=W0613 # >>>>>>insert any user code below this comment for section "compID=29" # replace, delete, or comment-out the following #print "executed method Buildproject_Button_Click" if not os.path.isdir(self.dirname): ShowError( title='Need Parent Directory', message= 'You need to choose a directory in which to place your project.' ) else: self.build_result_dict() # builds self.result dict r = self.result h = Hatch(projName=r["proj_name"], mainDefinesClass=r["is_class_project"], mainPyFileName=r["main_py_name"], mainClassName=r["class_name"], mainFunctionName=r["func_name"], author=r["author"], proj_copyright=r["proj_copyright"], proj_license=r["proj_license"], version=r["version"], email=r["email"], status=r["status"], github_user_name=r["github_user_name"], simpleDesc=r["short_desc"], longDesc=r["para_desc"]) call_result = h.save_project_below_this_dir(self.dirname) if call_result == 'Success': if AskYesNo(title='Exit Dialog', message='Do you want to leave this GUI?'): self.master.destroy() else: ShowWarning( title='Project Build Error', message='Project did NOT build properly.\n'+\ 'Warning Message = (%s)'%call_result) # return a string containing directory name def AskDirectory(self, title='Choose Directory', initialdir="."): """Simply wraps the tkinter function of the "same" name.""" dirname = tkFileDialog.askdirectory(parent=self.master, initialdir=initialdir, title=title) return dirname # <-- string def Selectdir_Button_Click(self, event): # I don't care what the exception is, if there's a problem, bail # Also, I want to redefine the dirname attribute here # pylint: disable=W0702, W0201 # tkinter requires arguments, but I don't use them # pylint: disable=W0613 """Selects the directory in which to build project.""" dirname = self.AskDirectory(title='Choose Directory For Nose Tests', initialdir='.') if dirname: try: dirname = os.path.abspath(dirname) except: self.dirname = '<Select Directory>' return # let Alarm force dir selection self.dirname = dirname self.Selectdir_Button.config(text=self.dirname) def RadioGroup1_StringVar_Callback(self, varName, index, mode): # tkinter requires arguments, but I don't use them # pylint: disable=W0613 """Responds to changes in RadioGroup1_StringVar.""" if self.RadioGroup1_StringVar.get() == "Class Project": self.Funcname_Entry.config(state=DISABLED) self.Classname_Entry.config(state=NORMAL) else: self.Classname_Entry.config(state=DISABLED) self.Funcname_Entry.config(state=NORMAL) # tk_happy generated code. DO NOT EDIT THE FOLLOWING. section "Master_Configure" def bindConfigure(self, event): """bindConfigure and Master_Configure help stabilize GUI""" # tkinter requires arguments, but I don't use them # pylint: disable=W0613 if not self.initComplete: self.master.bind("<Configure>", self.Master_Configure) self.initComplete = 1 def Master_Configure(self, event): """bindConfigure and Master_Configure help stabilize GUI""" # >>>>>>insert any user code below this comment for section "Master_Configure" # replace, delete, or comment-out the following if event.widget != self.master: if self.w != -1: return x = int(self.master.winfo_x()) y = int(self.master.winfo_y()) w = int(self.master.winfo_width()) h = int(self.master.winfo_height()) if (self.x, self.y, self.w, self.h) == (-1, -1, -1, -1): self.x, self.y, self.w, self.h = x, y, w, h if self.w != w or self.h != h: print "Master reconfigured... make resize adjustments" self.w = w self.h = h
class Window(Frame): def __init__(self, parent): Frame.__init__(self, parent, background="white") self.parent = parent self.initUI() home='/home/little_light/Desktop/workspace/python/data/GSTRB' modelFile=home+'/model/demo2.pkl' input_var = T.tensor4('inputs',dtype=theano.config.floatX) target_var = T.ivector('targets') network,loss,params=build_2f(input_var,target_var,regularW=0.0001) pvals=cPickle.load(open(modelFile)) [p.set_value(pval) for (p, pval) in zip(lasagne.layers.get_all_params(network), pvals)] predict=lasagne.layers.get_output(network, deterministic=True) input=lasagne.layers.get_all_layers(network)[0].input_var #lasagne.layers.input.input self.predict_fn=theano.function(inputs=[input],outputs=predict) def initUI(self): self.parent.title("Simple") self.pack(fill=BOTH, expand=1) self.tbImg=Entry(self.parent,width=50) self.tbImg.place(x=10,y=10) self.bLoad=Button(master=self,text="Load", command = self.load) self.bLoad.pack() self.bLoad.place(x=10,y=30) self.canvas = Canvas(self, width=400, height=400) self.canvas.pack() fileName='/home/little_light/Desktop/workspace/python/data/GSTRB/Final_Training/Images/00000/00004_00029.ppm' img = ImageTk.PhotoImage(Image.open(fileName)) self.canvas.image=img self.image_on_canvas=self.canvas.create_image(0,0,image=img,anchor='nw') self.canvas.place(x=10,y=60) self.v = StringVar() self.label=Label(master=self,textvariable=self.v) self.v.set("Target label:") self.label.place(x=10,y=470) def load(self): print "load" fileName=self.tbImg.get() img = ImageTk.PhotoImage(Image.open(fileName)) self.canvas.image=img #self.canvas.create_image(0,0,image=img) self.canvas.itemconfig(self.image_on_canvas, image =self.canvas.image) img=Image.open(fileName) img.load() img2=img.resize((32,32)) img2.load() data = np.asarray(img2, dtype="int32") mean=86.2111433696 data=np.transpose(data,(2,0,1)) data=np.asarray((data-mean)/256.0,dtype=theano.config.floatX) data2=np.zeros((1,3,32,32),dtype=theano.config.floatX) data2[0]=data data=data2 print np.argmax(self.predict_fn(data)[0]) self.v.set("Target label:"+str(np.argmax(self.predict_fn(data)[0])))
class Example(Frame): output_lines = 10 # make debug false when you are actually going to demo this to an audience debug = 1 def __init__(self, parent): Frame.__init__(self, parent) self.hsv_color = colorsys.rgb_to_hsv(0.0, 0.0, 1.0) self.hex_color = '#0000ff' # Added second copy of the above two fields for second color # For debugging, want an initial if self.debug : self.hsv_colorTwo = colorsys.rgb_to_hsv(0.0, 0.50, 0.625) self.hex_colorTwo = '#0088aa' else: self.hsv_colorTwo = colorsys.rgb_to_hsv(1.0, 0.0, 0.0) self.hex_colorTwo = '#ff0000' self.parent = parent print "Loading model..." self.lux = Lux() self.initUI() def update_output(self): (h, s, v) = self.hsv_color self.cv.set('Color {:.2f} {:.2f} {:.2f} (hsv)'.format(h, s, v)) #tjm Added second update_output method for when second color is chosen def update_outputTwo(self): (h, s, v) = self.hsv_colorTwo self.cvTwo.set('Color {:.2f} {:.2f} {:.2f} (hsv)'.format(h, s, v)) def initUI(self): row_height = 220 start_height = 30 left_column = 30 sq_size = 180 color_column = left_column assoc_column = color_column + sq_size + 30 dist_column = assoc_column + 220 y_label = 5 self.parent.title("Interactive LUX visualization") self.pack(fill=BOTH, expand=1) self.frame = Frame(self, border=1, relief=SUNKEN, width=sq_size, height=sq_size) self.frame.place(x=color_column, y=start_height) self.frame.config(bg=self.hex_color) self.frame.bind("<Button-1>", self.onChooseClick) #tjm Added second color display window self.frameTwo = Frame(self, border=1, relief=SUNKEN, width=sq_size, height=sq_size) self.frameTwo.place(x=color_column, y=start_height+row_height) self.frameTwo.config(bg=self.hex_colorTwo) self.frameTwo.bind("<Button-1>", self.onChooseTwoClick) #tjm First string field to display the H, S, and V values self.cv = StringVar() self.info = Label(self, textvariable=self.cv) self.info.place(x=color_column, y=y_label) #tjm second string field to display H, S, and V values self.cvTwo = StringVar() self.infoTwo = Label(self, textvariable=self.cvTwo) self.infoTwo.place(x=color_column, y=y_label+row_height) #tjm label for associated color terms field self.cvThree = StringVar() self.infoThree = Label(self, textvariable=self.cvThree) self.infoThree.place(x=assoc_column, y=y_label) #tjm label for distinguishing color terms field self.cvFour = StringVar() self.infoFour = Label(self, textvariable=self.cvFour) self.infoFour.place(x=dist_column, y=y_label) #tjm instruction text for color term assignment prediction function self.cvFive = StringVar() self.infoFive = Label(self, textvariable=self.cvFive) self.infoFive.place(x=left_column, y=y_label+2*row_height) self.display = Text(self, border=1, relief=SUNKEN, width=25, height=self.output_lines) self.display.place(x=assoc_column, y=start_height) self.display.tag_configure('undistinguished', foreground='dark salmon') #tjm Added second text window to display color labels self.displayTwo = Text(self, border=1, relief=SUNKEN, width=25, height=self.output_lines) self.displayTwo.place(x=assoc_column, y=start_height+row_height) self.displayTwo.tag_configure('undistinguished', foreground='dark salmon') #tjm Text field that displays distinction color term for top color self.distLabel = Text(self, border=1, relief=SUNKEN, width=25, height=self.output_lines) self.distLabel.place(x=dist_column, y=start_height) #tjm Text field that shows distinction color term for bottom color self.distLabelTwo = Text(self, border=1, relief=SUNKEN, width=25, height=self.output_lines) self.distLabelTwo.place(x=dist_column, y=start_height+row_height) #tjm added Entry widget for user to supply a color term self.e = Entry(self, bd = 5) self.e.bind("<Return>", lambda(event):self.onChooseAssign(self.e.get())) self.e.place(x = assoc_column, y=y_label+2*row_height) #tjm added text window to display result self.assignmentResult = Text(self, border = 1, relief=SUNKEN, width = 25, height = 2) self.assignmentResult.place(x = dist_column, y = y_label+2*row_height) self.cvThree.set('Associated Color Terms') self.cvFour.set('Differentiating Color Terms') self.cvFive.set('Test color term to interpret') self.update_output() self.update_outputTwo() self.distAndDisplay() def distAndDisplay(self): hueResultList = self.distinguish(1) hueResultListTwo = self.distinguish(2) #tjm displays top N choices and confidence ratings in the distLabel text field desc = [ '{:<17} {:.3f}\n'.format(hueResultList[i][0], hueResultList[i][1]) for i in range(self.output_lines) ] self.distLabel.config(state=NORMAL) self.distLabel.delete(1.0, END) self.distLabel.insert(END, ''.join(desc)) self.distLabel.config(state=DISABLED) descs = [hueResultList[i][0] for i in range(self.output_lines)] descTwo = [ '{:<17} {:.3f}\n'.format(hueResultListTwo[i][0], hueResultListTwo[i][1]) for i in range(self.output_lines) ] self.distLabelTwo.config(state=NORMAL) self.distLabelTwo.delete(1.0, END) self.distLabelTwo.insert(END, ''.join(descTwo)) self.distLabelTwo.config(state=DISABLED) descsTwo = [hueResultListTwo[i][0] for i in range(self.output_lines)] #tjm the "items" field holds the probability for each color term being used to describe hsv_color (h, s, v) = self.hsv_color items = self.lux.full_posterior((h * 360, s * 100, v * 100)) desc = [ '{:<17} {:.3f}\n'.format(items[i][0], items[i][1]) for i in range(self.output_lines) ] #tjm displays the HSV values self.display.config(state=NORMAL) self.display.delete(1.0, END) self.display.insert(END, ''.join(desc)) for i in range(self.output_lines) : if items[i][0] not in descs : self.display.tag_add('undistinguished', str(i+1) + ".0", str(i+1) + ".23") self.display.config(state=DISABLED) #tjm the "itemsTwo" field holds the probability for each color term being used to describe hsc_colorTwo (h, s, v) = self.hsv_colorTwo itemsTwo = self.lux.full_posterior((h * 360, s * 100, v * 100)) descTwo = [ '{:<17} {:.3f}\n'.format(itemsTwo[i][0], itemsTwo[i][1]) for i in range(self.output_lines) ] self.displayTwo.config(state=NORMAL) self.displayTwo.delete(1.0, END) self.displayTwo.insert(END, ''.join(descTwo)) for i in range(self.output_lines) : if itemsTwo[i][0] not in descsTwo : self.displayTwo.tag_add('undistinguished', str(i+1) + ".0", str(i+1) + ".23") self.displayTwo.config(state=DISABLED) self.onChooseAssign(self.e.get()) def onChoose(self): news = tkColorChooser.askcolor() if news and news[0]: ((red,green,blue), hx) = news self.hex_color = hx self.hsv_color = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0) self.frame.config(bg=hx) self.update_output() self.distAndDisplay() #tjm Added second onChoose function for when the second button is clicked def onChooseTwo(self): news = tkColorChooser.askcolor() if news and news[0]: ((red,green,blue), hx) = news self.hex_colorTwo = hx self.hsv_colorTwo = colorsys.rgb_to_hsv(red/255.0, green/255.0, blue/255.0) self.frameTwo.config(bg=hx) self.update_outputTwo() self.distAndDisplay() def onChooseClick(self, event) : self.onChoose() def onChooseTwoClick(self, event) : self.onChooseTwo() def onChooseAssign(self, colorTerm): node = self.lux.all.get(colorTerm) if node: scoreTop = self.score(node, self.hsv_color, self.hsv_colorTwo) scoreNumberTop = scoreTop[1] scoreBottom= self.score(node, self.hsv_colorTwo, self.hsv_color) scoreNumberBottom = scoreBottom[1] totalScoreTop = (scoreNumberTop/(scoreNumberTop+scoreNumberBottom)) if totalScoreTop > 0.5: winner = '{:<17} {:.3f}\n{:<14} {:.6f}'.format('top color!', totalScoreTop, colorTerm, scoreNumberTop) else: if totalScoreTop < 0.5: winner = '{:<17} {:.3f}\n{:<14} {:.6f}'.format('bottom color!', (1.0 - totalScoreTop), colorTerm, scoreNumberBottom) else: winner = 'Could describe either.\n{:<14f} {:.6f}'.format(colorTerm, scoreNumberTop) elif colorTerm : winner = 'Unknown term: ' + colorTerm else : winner = '' self.assignmentResult.config(state=NORMAL) self.assignmentResult.delete(1.0, END) self.assignmentResult.insert(END, winner) self.assignmentResult.config(state=DISABLED) def score(self, currentNode, hsvY, hsvZ): (hY, sY, vY) = hsvY (hZ, sZ, vZ) = hsvZ hY *= 360 sY *= 100 vY *= 100 hZ *= 360 sZ *= 100 vZ *= 100 muHLow = currentNode.dim_models[0].params[0] muHHigh = currentNode.dim_models[0].params[3] muSLow = currentNode.dim_models[1].params[0] muSHigh = currentNode.dim_models[1].params[3] muVLow = currentNode.dim_models[2].params[0] muVHigh = currentNode.dim_models[2].params[3] # mds changed to hY and hZ - never use the unscaled values phiHY = currentNode.dim_models[0].phi(hY) phiHZ = currentNode.dim_models[0].phi(hZ) phiSY = currentNode.dim_models[1].phi(sY) phiSZ = currentNode.dim_models[1].phi(sZ) phiVY = currentNode.dim_models[2].phi(vY) phiVZ = currentNode.dim_models[2].phi(vZ) # mds added: need to handle hue adjust if currentNode.dim_models[0].adjust : adjust = True; nhY = atan2(sin(hY*pi/180),cos(hY*pi/180))*180/pi nhZ = atan2(sin(hZ*pi/180),cos(hZ*pi/180))*180/pi else : adjust = False; nhY = hY; nhZ = hZ; """ ([product over opposite dimensions d] phi_d(y) ) * <== termA ([product over other dimensions d] phi_d(y) - <== termB [product over all dimensions d] phi_d(z)) <== termC """ termA = 1.0 termB = 1.0 termC = phiHZ * phiSZ * phiVZ oppSideCase = 0 #tjm determine which case and calculate appropriate y-but-not-z value #tjm opposite sides case for hue if ((nhY < muHLow) & (muHHigh < nhZ)) | ((nhZ < muHLow) & (muHHigh < nhY)): termA *= phiHY oppSideCase += 1 else: termB *= phiHY #tjm opposite sides case for saturation if ((sY < muSLow) & (muSHigh < sZ)) | ((sZ < muSLow) & (muSHigh < sY)): termA *= phiSY oppSideCase += 1 else: termB *= phiSY #tjm opposite sides case for value if ((vY < muVLow) & (muVHigh < vZ)) | ((vZ < muVLow) & (muVHigh < vY)): termA *= phiVY oppSideCase +=1 else: termB *= phiVY score = termA * (termB - termC) if score < 0: score = 0 #mds weight words by availability score *= currentNode.availability return [currentNode.name, score, termA, termB, termC, oppSideCase, adjust, nhY, nhZ, muHLow, muHHigh] #tjm Method to select color term that describes one color but not the other def distinguish(self, choice): """tjm process: 1) go through all color terms 1a) see if it's an acceptable case 1b) calculate y-but-not-z-confidence 1c) store color term name and y-but-not-z-confidence in list 2) return sorted list 3) print out top 5 values for sanity check """ #tjm list of color terms and associated y-but-not-z confidence hueResults = [] #tjm determine if you're picking a term to describe top color or bottom color if choice == 1: #tjm loop over all color terms for currentNodeChoice in self.lux.all.values(): #mds enable comprehensive debugging reports hueResults.append(self.score(currentNodeChoice, self.hsv_color, self.hsv_colorTwo)) else: for currentNodeChoice in self.lux.all.values(): #mds enable comprehensive debugging reports hueResults.append(self.score(currentNodeChoice, self.hsv_colorTwo, self.hsv_color)) total = sum(r[1] for r in hueResults) for r in hueResults : r[1] /= total return sorted(hueResults, key = lambda hueResults:hueResults[1], reverse=True)