class App(Frame): def __init__(self, parent): Frame.__init__(self, parent, background='blue') self.parent = parent self.initUI() def say_hi(self): print "hi there, everyone!" def initUI(self): self.QUIT = Button(self, text="Quit", fg="red", command=self.quit) self.QUIT.place(x=50, y=5) self.hi_there = Button(self) self.hi_there["text"] = "Hello", self.hi_there["command"] = self.say_hi self.hi_there.pack({"side": "left"}) kpdf = Image.open("../qt/kpdf.png") self.kpdftk = ImageTk.PhotoImage(kpdf) self.label1 = Label(self, image=self.kpdftk) self.label1.place(x=200, y=10) self.parent.title("Sample V.01") self.pack(fill=BOTH, expand=1)
def gridd(): """ Crée la grille avec l'interface tkinter et crée les boutons """ global window global intermediateVariable global player window.geometry("680x680") #Dimension de l'interface #default = PhotoImage(file='./Image/default.png') #Boutons: #Le x=0 est le bord gauche de la fenetre #Le y=0 est le bord haut de la fenetre #La position est la position du coin en haut à gauche du bouton # Création des boutons intermediateVariable = 0 cross = PhotoImage(file='./Image/croix.png') for nameCase in case.keys(): newbutton = Button(window, image=cross, name=str(nameCase).lower(), state="active") #Définition du bouton buttons.append(newbutton) #Ajouter à la liste #newbutton.config(command= intermediateFunction(nameCase)) #Commande du bouton substitute = case[nameCase] newbutton.place(x=substitute[2], y=substitute[3]) #Placement du bouton
def addButtonI(self, dim=(0, 0, 206, 109), x=0, y=0, command=0): try: crop = self.__texture[0].crop(dim) render = ImageTk.PhotoImage(crop) nbutton = Button(self, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1") nbutton.image = render nbutton.place(x=x, y=y) self.__list_button.append(nbutton) if command == 1: nbutton.configure(command=self.showOne) elif command == 2: nbutton.configure(command=self.showAll) elif command == 3: pass elif command == 4: nbutton.configure(command=self.master.destroy) return nbutton except Exception as e: self.Error("Error al cargar Texturas") return -1
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 make_top_bar(self): ''' make the top bar, with game restart, and statistics information ''' # reset game button button = Button(self.gui, text='reset game', height=30, width=120, \ command=self.reset_game) button.place(x=20, y=20, width=120, height=20) # about me button button = Button(self.gui, text='about me', height=30, width=120, \ command=self.about_me) button.place(x=160, y=20, width=120, height=20) # four labels for statistical numbers self.label_max_depth_text = Label(self.gui, text='max depth') self.label_nodes_text = Label(self.gui, text='nodes gen') self.label_prune_max_text = Label(self.gui, text='max prune') self.label_prune_min_text = Label(self.gui, text='min prune') self.label_max_depth = Label(self.gui, text='0') self.label_nodes = Label(self.gui, text='0') self.label_prune_max = Label(self.gui, text='0') self.label_prune_min = Label(self.gui, text='0') self.label_max_depth_text.place(x=20, y=50, width=70, height=20) self.label_nodes_text.place(x=100, y=50, width=70, height=20) self.label_prune_max_text.place(x=180, y=50, width=70, height=20) self.label_prune_min_text.place(x=260, y=50, width=70, height=20) self.label_max_depth.place(x=20, y=80, width=70, height=20) self.label_nodes.place(x=100, y=80, width=70, height=20) self.label_prune_max.place(x=180, y=80, width=70, height=20) self.label_prune_min.place(x=260, y=80, width=70, height=20)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Color chooser") self.pack(fill=BOTH, expand=1) self.btn = Button(self, text="Choose Color", command=self.onChoose) self.btn.place(x=30, y=30) self.frame = Frame(self, border=1, relief=SUNKEN, width=100, height=100) self.frame.place(x=160, y=30) def onChoose(self): (rgb, hx) = tkColorChooser.askcolor() self.frame.config(bg=hx)
def Exit(): global rootB rootC = Tk() rootC.geometry('220x150+500+200') rootC.overrideredirect(True) def sure_exit(): a1.place_forget() a2.place_forget() b.place_forget() c.place_forget() root.destroy() rootC.destroy() try: rootB.destroy() except: pass def cancel(): rootC.destroy() a1 = Label(rootC, text='Hope to see you soon. Thank You.') a1.place(x=15, y=20) a2 = Label(rootC, text='Do you really want to Exit ?') a2.place(x=15, y=40) b = Button(rootC, text='Cancel', command=cancel) b.place(x=15, y=100) c = Button(rootC, text='Exit', command=sure_exit) c.place(x=160, y=100) rootC.mainloop()
def add_assembly(): """添加组件""" init() buy_house_static = Label(master, text=u'购房: ', font=Font(size=15)) buy_house_static.place(anchor=u'nw', x=440, y=50) buy_car_static = Label(master, text=u'购车: ', font=Font(size=15)) buy_car_static.place(anchor=u'nw', x=440, y=75) age_static = Label(master, text=u'年龄: ', font=Font(size=15)) age_static.place(anchor=u'nw', x=440, y=100) height_static = Label(master, text=u'身高: ', font=Font(size=15)) height_static.place(anchor=u'nw', x=440, y=125) salary_static = Label(master, text=u'工资: ', font=Font(size=15)) salary_static.place(anchor=u'nw', x=440, y=150) education_static = Label(master, text=u'学历: ', font=Font(size=15)) education_static.place(anchor=u'nw', x=440, y=175) company_static = Label(master, text=u'公司: ', font=Font(size=15)) company_static.place(anchor=u'nw', x=440, y=200) industry_static = Label(master, text=u'行业: ', font=Font(size=15)) industry_static.place(anchor=u'nw', x=440, y=225) school_static = Label(master, text=u'学校: ', font=Font(size=15)) school_static.place(anchor=u'nw', x=440, y=250) position_static = Label(master, text=u'职位: ', font=Font(size=15)) position_static.place(anchor=u'nw', x=440, y=275) previous = Button(master, text=u'上一个', command=handle_previous) previous.place(anchor=u'nw', x=10, y=490) next = Button(master, text=u'下一个', command=handle_next) next.place(anchor=u'nw', x=520, y=490)
def add_assembly(): """添加组件""" init() buy_house_static = Label(master, text=u'购房: ', font=Font(size=15)) buy_house_static.place(anchor=u'nw', x=440, y=50) buy_car_static = Label(master, text=u'购车: ', font=Font(size=15)) buy_car_static.place(anchor=u'nw', x=440, y=75) age_static = Label(master, text=u'年龄: ', font=Font(size=15)) age_static.place(anchor=u'nw', x=440, y=100) height_static = Label(master, text=u'身高: ', font=Font(size=15)) height_static.place(anchor=u'nw', x=440, y=125) salary_static = Label(master, text=u'工资: ', font=Font(size=15)) salary_static.place(anchor=u'nw', x=440, y=150) education_static = Label(master, text=u'学历: ', font=Font(size=15)) education_static.place(anchor=u'nw', x=440, y=175) company_static = Label(master, text=u'公司: ', font=Font(size=15)) company_static.place(anchor=u'nw', x=440, y=200) industry_static = Label(master, text=u'行业: ', font=Font(size=15)) industry_static.place(anchor=u'nw', x=440, y=225) school_static = Label(master, text=u'学校: ', font=Font(size=15)) school_static.place(anchor=u'nw', x=440, y=250) position_static = Label(master, text=u'职位: ', font=Font(size=15)) position_static.place(anchor=u'nw', x=440, y=275) previous = Button(master, text=u'上一个', command=handle_previous) previous.place(anchor=u'nw', x=10, y=490) next = Button(master, text=u'下一个', command=handle_next) next.place(anchor=u'nw', x=520, y=490)
def __init__(self, root, prtr, settings, log, *arg): Toplevel.__init__(self, root, *arg) self.protocol('WM_DELETE_WINDOW', self.delTop) self.title("Macro Buttons") self.app = root self.settings = settings self.printer = prtr self.log = log self.macroList = self.settings.getMacroList() fw = BUTTONWIDTH * 3 fh = BUTTONHEIGHT * 10 self.f = Frame(self, width = BUTTONWIDTH*3, height=BUTTONHEIGHT*10) for m in self.macroList: b = Button(self.f, text=m[MTEXT], width=BWIDTH, command=lambda macro=m[MNAME]: self.doMacro(macro)) x = (m[MCOL]-1) * BUTTONWIDTH y = (m[MROW]-1) * BUTTONHEIGHT b.place(relx=0.0, rely=0.0, y=y, x=x, anchor=NW) self.f.pack() geometry = "%dx%d+50+50" % (fw, fh) self.geometry(geometry)
class Example(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initUI() def initUI(self): self.parent.title("Color chooser") self.pack(fill=BOTH, expand=1) self.btn = Button(self, text="Choose Color", command=self.onChoose) self.btn.place(x=30, y=30) self.frame = Frame(self, border=1, relief=SUNKEN, width=100, height=100) self.frame.place(x=160, y=30) def onChoose(self): (rgb, hx) = tkColorChooser.askcolor() self.frame.config(bg=hx)
def make_top_bar(self): ''' make the top bar, with game restart, and statistics information ''' # reset game button button = Button(self.gui, text='reset game', height=30, width=120, \ command=self.reset_game) button.place(x=20, y=20, width=120, height=20) # about me button button = Button(self.gui, text='about me', height=30, width=120, \ command=self.about_me) button.place(x=160, y=20, width=120, height=20) # four labels for statistical numbers self.label_max_depth_text = Label(self.gui, text='max depth') self.label_nodes_text = Label(self.gui, text='nodes gen') self.label_prune_max_text = Label(self.gui, text='max prune') self.label_prune_min_text = Label(self.gui, text='min prune') self.label_max_depth = Label(self.gui, text='0') self.label_nodes = Label(self.gui, text='0') self.label_prune_max = Label(self.gui, text='0') self.label_prune_min = Label(self.gui, text='0') self.label_max_depth_text.place(x=20, y=50, width=70, height=20) self.label_nodes_text.place(x=100, y=50, width=70, height=20) self.label_prune_max_text.place(x=180, y=50, width=70, height=20) self.label_prune_min_text.place(x=260, y=50, width=70, height=20) self.label_max_depth.place(x=20, y=80, width=70, height=20) self.label_nodes.place(x=100, y=80, width=70, height=20) self.label_prune_max.place(x=180, y=80, width=70, height=20) self.label_prune_min.place(x=260, y=80, width=70, height=20)
class GuiBatteryWindow(Frame): def __init__(self, master_batt): Frame.__init__(self, master_batt) self.master_batt = master_batt self.__initUi() #=========================================================================== # Initialize and reset GUI #=========================================================================== def __initUi(self): self.master_batt.title('Battery Plot') self.pack(fill=BOTH, expand=1) style = Style().configure("TFrame", background="#333") battPlot = ImageTk.PhotoImage(file="view/images/batteryPlot.png") label1 = Label(self, image=battPlot) label1.image = battPlot label1.place(x=0, y=0, width=1500, height=900) # Pass and Fail Buttons self.fail_button = Button(self, text="Fail", command=self.failed, height=4, width=20, background='red') self.fail_button.place(x=1080, y=850, width=100, height=30) self.pass_button = Button(self, text="Pass", command=self.passed, height=4, width=20, background='green') self.pass_button.place(x=1240, y=850, width=100, height=30) def failed(self): self.fail_button.config(state=DISABLED) self.fail_button.update() plot_passed = False time.sleep(DELAY_BEFORE_WINDOW_CLOSE) self.master_batt.plot_passed = plot_passed self.master_batt.quit() return def passed(self): self.pass_button.config(state=DISABLED) self.pass_button.update() plot_passed = True time.sleep(DELAY_BEFORE_WINDOW_CLOSE) self.master_batt.plot_passed = plot_passed self.master_batt.quit() return
def select_start_options(self): ''' popup box to select side and difficulty levels ''' print 'select game start options' popup = Toplevel(self.gui, width=300, height=110) popup.title('Choose Game Side and Level') # stays on top of the game canvass popup.transient(self.gui) popup.grab_set() # bind window close events popup.bind('<Escape>', lambda e: self.not_selected_start_options(popup)) popup.protocol("WM_DELETE_WINDOW", lambda : self.not_selected_start_options(popup)) # choose side label1 = Label(popup, text="Side", height=30, width=50) label1.place(x=10, y=5, height=30, width=50) val1 = IntVar() bt_north = Radiobutton(popup, text="White", variable=val1, value=1) bt_north.place(x=60, y=10) bt_south = Radiobutton(popup, text="Black", variable=val1, value=2) bt_south.place(x=120, y=10) # by default, human plays first, meaning play the north side if self.choose_side == 'north': bt_north.select() else: bt_south.select() # choose difficulty level label2 = Label(popup, text="Level", height=30, width=50) label2.place(x=10, y=35, height=30, width=50) val2 = IntVar() bt_level1 = Radiobutton(popup, text="Dumb", variable=val2, value=1) bt_level1.place(x=60, y=40) bt_level2 = Radiobutton(popup, text="Smart", variable=val2, value=2) bt_level2.place(x=120, y=40) bt_level3 = Radiobutton(popup, text="Genius", variable=val2, value=3) bt_level3.place(x=180, y=40) # by default, the game is medium level if self.choose_level == 1: bt_level1.select() elif self.choose_level == 2: bt_level2.select() elif self.choose_level == 3: bt_level3.select() button = Button(popup, text='SET', \ command=lambda: self.selected_start_options(popup, val1, val2)) button.place(x=70, y=70)
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)
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 initUI(self): self.parent.title("You have new notifications - Spion") self.pack(fill=BOTH, expand=1) quitButton = Button(self, text="View Notifications >>", command=self.openReport) quitButton.place(x=90, y=30)
def b(self,p,u,l2,v): u.set(p) if p == 'PQ_DHeap': c = self.creaSpinbox() else: c = 0 button1 = Button(self.m, text = 'Esegui Prim', command = lambda: self.avvio(v,u,c)) button1.place(x=100,y=200)
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)
def initUI(self): self.parent.title("Quit button") # self.style = Style() # self.style.theme_use("default") self.pack(fill=BOTH, expand=1) quitButton = Button(self, text="Quit", command=self.quit) quitButton.place(x=50, y=50)
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 Error(self, error="Se produjo un error"): Ventana2 = Toplevel(self.master) Ventana2.configure(height=100, width=260, bg="#4a4a4a") Ventana2.title("Error") Error = Label(Ventana2, text=error, bg="#4a4a4a", fg="#FFFFFF") Error.place(x=40, y=15) Error.config(font=("", 12)) Salir = Button(Ventana2, width=10, text="Salir", command=Ventana2.destroy) Salir.place(x=85, y=55)
def initUI(self): # Here we can set the title of the tk window self.parent.title("Simple") #pack organises widgets into vertical and horizontal boxes. It is one of three geometry managers #expanded in both directions self.pack(fill=BOTH, expand=1) openFileButton = Button(self, text="Load file", command=self.openFile) openFileButton.place(x=50, y=50) processFileButton = Button(self, text="Process a file", command=self.processFile) processFileButton.place(x=50, y=100)
class MySecondGUI: def __init__(self, master): if len(sys.argv) < 2: self.name = "default" else: self.name = sys.argv[1] self.master = master master.title("reading window") self.label = Label(master, text="This is our second GUI!") self.label.pack() self.text = Text(width=25, height=5, bg="darkgreen", fg='white') self.text.pack() self.read_button = Button(master, width=9, text="Read text", command=self.read) self.read_button.pack() self.read_button.place(x=120, y=40) self.close_button = Button(master, width=9, text="Close", command=master.quit) self.close_button.pack() self.close_button.place(x=120, y=70) self.pin = 0 def read(self): str_audio_name = self.name + "_combined.wav" open(str_audio_name, "w") os.remove(str_audio_name) open(str_audio_name, "w") text = self.text.get("1.0", 'end') user_text = map(lambda c: c, text) combined = AudioSegment.from_file(self.name + "_" + user_text[0] + ".wav") combined.export(str_audio_name, format='wav') user_text.pop(0) for number in user_text: if number == '\n' or number == ' ': continue sound1 = AudioSegment.from_file(str_audio_name) sound2 = AudioSegment.from_file(self.name + "_" + number + ".wav") combined = sound1 + sound2 combined.export(str_audio_name, format='wav') self.pin = subprocess.call("python voice_acting.py " + str_audio_name, shell=True)
def initUI(self): self.parent.title("Gurbani Brain Training") self.pack(fill=BOTH, expand=1) QuitButton = Button(self, text ="Quit", command=self.quit) QuitButton.place(x=200, y=200) QuitButton.pack() RandButton = Button(self, text ="Random", command=self.reloadData) RandButton.place(x=200, y=200) self.listBox1 = Listbox() self.listBox1.pack() RandButton.pack()
def no_acc(): global win2, habusrenr win2 = Toplevel(root) win2.geometry('250x50') win2.iconbitmap('Logo.ico') win2.resizable(width=FALSE, height=FALSE) win2.title("Support") habusrlab = Label(win2, text="Full Name") habusrenr = Entry(win2) habusrbtt = Button(win2, text="Send", command=send_acc_req) habusrlab.grid(column=0, row=0) habusrenr.grid(column=1, row=0) habusrbtt.place(relx=0.6, x=1, y=22.5, anchor=NE)
def initUI(self): self.parent.title("AlfredShare Auth") self.pack(fill=BOTH, expand=1) quitButton = Button(self, text="Quit", command=self.quit) quitButton.place(x=90, y=110) button = Button(self, text="Auth", command=self.openUrl) button.place(x=90, y=80) label = Label( self, text= "Press on Auth button then press\n'Allow' button in browser,\nand then quit this app" ) label.place(x=20, y=10)
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)
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('')
class GraphButton(object): def __init__(self, window, graphProgramInstance, mainProgramInstance): self.window = window self.graphProgramInstance = graphProgramInstance self.mainProgramInstance = mainProgramInstance def makeGraphUpdateButton(self): self.updateButton = Button(self.window, text = 'Update X&Y Scale', command = self.graphProgramInstance.updateKeyedParameters) self.updateButton.place(x = 10, y = 620) self.returnToMainScreenButton = Button(self.window, text = "Return to Analysis", command = self.mainProgramInstance.returnToMainScreenFromGraphScreen) self.returnToMainScreenButton.place(x = 575, y = 620)
def inputgui(): inputwindow = Tk() inputwindow.geometry("400x400") inputwindow.title('Input Message') exitbutton = Button(inputwindow, text='Exit', width=25, command=inputwindow.destroy) Label(inputwindow, text="Input Message : ").grid(row=0, column=0) inputtext = Text(inputwindow, height=10, width=56, bg='lightgray', highlightcolor='black') sendtbutton = Button(inputwindow, text='Send', width=25, command=lambda: retrieve_input()) encryptbutton = Button(inputwindow, text='Encrypt', width=25, command=lambda: encrypt_input()) inputtext.grid() sendtbutton.grid() encryptbutton.grid() exitbutton.place(relx=0.5, rely=0.9, anchor=tk.CENTER) def retrieve_input(): inputValue = inputtext.get("1.0", tk.END) inputmessage(inputValue) def encrypt_input(): ourMessage = '' for i in range(len(encryptedinput)): ourMessage += encryptedinput[i] messageVar = Message(inputwindow, text=ourMessage) messageVar.config(bg='lightgray') messageVar.config(aspect=400) messageVar.grid() inputwindow.mainloop()
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 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 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 prepare_the_playground(self, ncol, nrow): ''' draw the playground according to the cell status map different status maps to different color ''' # place the canvas canvass = Canvas(self.gui, bg="white", height=self.height, width=self.width) canvass.pack() # place top bar self.make_top_bar() # place side info #self.make_side_info() # place the buttons for row_idx in range(nrow): for col_idx in range(ncol): idx = ncol * row_idx + col_idx cell = self.game.canvass.get_cell((row_idx, col_idx)) # active buttons, with callback function passing the button index if cell.status == 'disabled': # disabled buttons, which are unclickable button = Button(self.gui, state=DISABLED) else: button = Button(self.gui, cursor="target", \ command=lambda row_idx=row_idx, col_idx=col_idx: \ self.game.human_play(row_idx, col_idx)) # calculate the x,y coordinates and place the buttons offset_x = self.margin + self.unit * col_idx offset_y = 4 * self.margin + self.unit * row_idx + 30 button.place(x=offset_x, y=offset_y, width=self.unit, height=self.unit) self.button_map[idx] = button self.refresh_playground()
def path(self): path_frame=LabelFrame(self.window,text='Input paths',width=450,height=100) path_frame.place(x=20,y=60) ora_mes=Message(path_frame,text='Excel from ORA:',width=120) ora_mes.place(x=10,y=0) self.ora_entry=Entry(path_frame,textvariable=self.ora_path,width=35) self.ora_entry.place(x=130,y=0) ora_button=Button(path_frame,text='Select…',command=self.selectPath1) ora_button.place(x=365,y=0) calcu_mes=Message(path_frame,text='Calculator:',width=120) calcu_mes.place(x=10,y=40) self.calcu_entry=Entry(path_frame,textvariable=self.calcu_path,width=35) self.calcu_entry.place(x=130,y=40) calcu_button=Button(path_frame,text='Select…',command=self.selectPath2) calcu_button.place(x=365,y=40)
def __init__(self,root,gua64): self.cntoint={u'少阳-----':'1',u'少阴-- --':'2',u'老阳--O--':'3',u'老阴--X--':'4'} self.tfont=tkFont.Font(family='Fixdsys',size=25,weight=tkFont.BOLD) self.gfont=tkFont.Font(family='Fixdsys',size=13,weight=tkFont.BOLD) self.dgua=[] #动爻 self.ygua=[] #原始卦 self.bbgua=[] #变卦 self.yguastr=[] #原始卦 self.gua=[] #只有12的卦 self.pabout=True #右键显示消失淮南标题 self.guax=200 self.guay=100 self.liushen={'甲':0,'乙':0,'丙':1,'丁':1,'戊':2,'己':3,'庚':4,'辛':4,'壬':5,'癸':5} self.liushencn=['青龙','朱雀','勾陈','腾蛇','白虎','玄武'] self.tiangan={'甲':1,'乙':2,'丙':3,'丁':4,'戊':5,'己':6,'庚':7,'辛':8,'壬':9,'癸':10} self.dizhi={'子':1,'丑':2,'寅':3,'卯':4,'辰':5,'巳':6,'午':7,'未':8,'申':9,'酉':10,'戌':11,'亥':12} self.kongwangzu=['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥'] self.root=root self.root.title(u'===六爻排盘===[淮南内部专用]') self.root.minsize(550,380) self.root.maxsize(550,380) self.canvas=Canvas(root,width=460,height=380,bg='gray') # self.picyang=PhotoImage(file='tk\\yang.gif') # self.picyin=PhotoImage(file='tk\\yin.gif') self.canvas.place(relx=0,rely=0) self.com={} for i in xrange(6): self.com[i]=Combobox(root,state='readonly') self.com[i]['values']=(u'少阳-----',u'少阴-- --',u'老阳--O--',u'老阴--X--') self.com[i].current(0) self.com[i].place(relx=0.85,rely=0.36-0.07*i,width=80) bt1=Button(self.root,text=u'排盘',command=self.paipan) bt2=Button(self.root,text=u'清除',command=self.cls) l1=Label(self.root,text=u'右键水印') l1.place(x=480,y=327) # bt1.place(relx=0.85,rely=0.35+0.7) # bt1.pack(side='right') bt1.place(x=467,y=170,width=78) bt2.place(x=467,y=350,width=78) self.date() #干支 #=========================== self.root.bind('<Button-3>',self.about)
def draw(self, init=False): if init: self.canvas_width, self.canvas_height = 0, 0 self.canvas = Canvas(self.root, bg="black") self.colour_cells = [] # update colour cells while self.colour_cells != []: #print('killing...') self.colour_cells[0].unbind("<Button-1>") self.colour_cells[0].destroy() del self.colour_cells[0] self.button_index_dict = dict() nb_colours = self.size[0]*self.size[1] pos = 0 for ix in range(self.size[0]): for iy in range(self.size[1]): colour = self.colours[pos] # create the new cell colour_cell = Button(self.canvas, bg=toHex([v/255. for v in colour]), activebackground=toHex([v/255. for v in colour])) colour_cell.bind("<Button-1>", self.handleColourSelector) # place the cell cell_width = self.canvas_width/self.size[0] cell_height = self.canvas_height/self.size[1] cell_width = min(cell_width, cell_height) cell_height = min(cell_width, cell_height) x = ix * cell_width y = iy * cell_height colour_cell.place(x = x, y = y, width = cell_width, height=cell_height) self.button_index_dict[colour_cell] = pos self.colour_cells.append(colour_cell) pos += 1
class BasePathFrame(BasePAFrame): """ фрейм для указания папки с фотографиями """ def __init__(self, *args, **kwargs): BasePAFrame.__init__(self, *args, **kwargs) self.w_label_base_path_label = Label(self, text=u'Папка с фотографиями') self.w_label_base_path = Label(self, text=settings.BASE_CATALOG) self.w_button_select_base_path = Button( self, text=u'Изменить', command=self.click_button_select_base_path) def _pa_layout(self): label_height = 0.25 self.w_label_base_path_label.place( relx=0, rely=0 ) self.w_label_base_path.place( relx=0, rely=label_height ) self.w_button_select_base_path.place( relx=0, rely=label_height * 2 ) def click_button_select_base_path(self): """ обработчик выбора папки с фотографиями :return: """ path = askdirectory( title=u'Выберите папку с фотографиями', initialdir=settings.BASE_CATALOG) if not path: return self.w_label_base_path['text'] = path settings.BASE_CATALOG = path
class SelectFileUI(Frame): def __init__(self, parent): Frame.__init__(self,parent) self.filePath = None self.parent = parent self.initUI() self.centerWindow() def initUI(self): self.parent.title("选择聊天日志文件") self.pack(fill=BOTH, expand=1) self.selectFileBtn = Button(self, text="请选择日志文件", command=self.selectClick) self.selectFileBtn.place(x = 100 , y = 20) self.nextBtn = Button(self, text="下一步", command=self.nextClick) self.nextBtn.place(x = 120 , y = 120) self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=60, y=80) def selectClick(self): ftypes = [('Text files', '*.txt'), ('All files', '*')] dlg = fileDialog.Open(self, filetypes = ftypes) file = dlg.show() if file != '': self.filePath = file self.var.set(file) def nextClick(self): if self.filePath and self.filePath != '': self.parent.destroy() readFile(self.filePath) else: box.showerror("错误", "请选择聊天日志文件!") def centerWindow(self): w = 300 h = 150 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 prepare_the_playground(self, ncol, nrow): ''' draw the playground according to the cell status map different status maps to different color ''' # place the canvas canvass = Canvas(self.gui, bg="white", height=self.height, width=self.width) canvass.pack() # place top bar self.make_top_bar() # place side info #self.make_side_info() # place the buttons for row_idx in range(nrow): for col_idx in range(ncol): idx = ncol * row_idx + col_idx cell = self.game.canvass.get_cell((row_idx, col_idx)) # active buttons, with callback function passing the button index if cell.status == 'disabled': # disabled buttons, which are unclickable button = Button(self.gui, state=DISABLED) else: button = Button(self.gui, cursor="target", \ command=lambda row_idx=row_idx, col_idx=col_idx: \ self.game.human_play(row_idx, col_idx)) # calculate the x,y coordinates and place the buttons offset_x = self.margin + self.unit * col_idx offset_y = 4 * self.margin + self.unit * row_idx + 30 button.place(x=offset_x, y=offset_y, width=self.unit, height=self.unit) self.button_map[idx] = button self.refresh_playground()
def __init__(self, *args, **kwargs): Tk.__init__(self, *args, **kwargs) # Force fullscreen self.geometry("{0}x{1}+0+0".format(self.winfo_screenwidth() / 4, (self.winfo_screenheight() / 2) - 100)) # Set the title self.title("AI-Prog Module 1 - Kristian Ekle & Thor Håkon") # Bring window to front self.lift() self.attributes('-topmost', True) self.attributes('-topmost', False) btn = Button(self, text="Start Game", font=("Helvetica", 22, "bold"), width=10, command=self.openGameFrame) btn.place(in_=self, anchor="c", relx=.5, rely=.5) btn.pack(pady=50) btn_quit = Button(self, text="Quit", font=("Helvetica", 22, "bold"), width=10, command=self.destroy) btn_quit.place(in_=self, anchor="c", relx=.5, rely=.5) btn_quit.pack()
def add_assembly(): """添加组件""" global index_label init() index_label = Label(master, text=u'{}/{}'.format(offset + 1, len(face_file_list)), font=Font(size=20)) index_label.place(anchor=u'nw', x=10, y=10) previous_button = Button(master, text=u'上一个', command=handle_previous) previous_button.place(anchor=u'nw', x=300, y=8) next_button = Button(master, text=u'下一个', command=handle_next) next_button.place(anchor=u'nw', x=380, y=8) rotate_button = Button(master, text=u'旋转', command=handle_rotate) rotate_button.place(anchor=u'nw', x=460, y=8) detect_button = Button(master, text=u'检查', command=handle_detect) detect_button.place(anchor=u'nw', x=520, y=8)
def Winning(self, color): self.someoneWin = True window = Toplevel(self.master, background="#f0e5df") window.attributes('-topmost', True) window.title("we have a winner!") window.geometry("300x200") message = Label(window, text="The winner is \n" + str(color), background="#f0e5df", font=("Courier", 20)) message.place(x=150, y=80, anchor="center") resetButton = Button(window, text="Reset Game", command=lambda: ((self.ResetGame()), (window.destroy()), (self.master.attributes('-topmost', True))), height=2, width=15) resetButton.place(x=150, y=160, anchor="center") center(window)
def menu_press_acc_reqs(): global row, listbox, lab root.geometry('220x170') F1 = Frame() lab = Label(root) s = Scrollbar(F1) listbox = Listbox(F1) s.pack(side=RIGHT, fill=Y) listbox.bind('<<ListboxSelect>>', onselect) listbox.pack(side=LEFT, fill=Y) F1.grid(column=0, row=0) s['command'] = listbox.yview listbox['yscrollcommand'] = s.set apprbtt = Button(root, text="Approved", command=app_acc) denybtt = Button(root, text="Denied") lab.place(relx=0.77, x=1, y=30, anchor=W) apprbtt.place(relx=0.67, x=1, y=60, anchor=W) denybtt.place(relx=0.7, x=1, y=100, anchor=W) forget_all() cursor.execute('''SELECT `username` FROM db_REQ''') while row is not None: for item in [row]: listbox.insert(END, row) row = cursor.fetchone()
def __init__(self, root): self.root = root self.columns = 26 button_play = Button(self.root, text="Play", command=self.callback_play) button_stop = Button(self.root, text="Stop", command=self.callback_stop) button_shutdown = Button(self.root, text="Shut down", command=self.callback_shutdown) button_close = Button(self.root, text="Close", command=self.callback_close) self.text = Text(self.root, height=1) scrollbar = Scrollbar(self.root, width=30) font = tkFont.Font(size=15) self.listbox = Listbox(self.root, yscrollcommand=scrollbar.set, selectmode=SINGLE, font=font) self.listbox.bind("<<ListboxSelect>>", self.callback_stream_selected) scrollbar.config(command=self.listbox.yview) button_stop.place(relx=0, rely=0) button_play.place(relx=0.18, rely=0) button_close.place(relx=0.5, rely=0) button_shutdown.place(relx=0.7, rely=0) scrollbar.place(relx=0.9, rely=0.2, relheight=0.7) self.listbox.place(relx=0, rely=0.2, relwidth=0.9, relheight=0.7) self.text.place(relx=0, rely=0.9) self.root.protocol("WM_DELETE_WINDOW", self.callback_close)
def make_widgets(self): widget1 = Label(text="Wybierz plik z danymi EKG pacjenta", background="white") widget1.place(y=30, width=250, height=25) widget2 = Button(text='Wybierz plik', command=self.przechwycEKG) widget2.place(x=250, y=30, width=120, height=25) widget3 = Label(text="Wybierz plik z danymi EMG pacjenta", background="white") widget3.place(y=60, width=250, height=25) widget4 = Button(text='Wybierz plik', command=self.przechwycEMG) widget4.place(x=250, y=60, width=120, height=25) widget5 = Button(text='Rozpocznij analize', command=self.call_main_receiver) #start to uruchomi receiver, potem sender widget5.place(relx=0.5, rely=0.4, height=40,width=150, anchor=CENTER)
def __init__(self, master): self.master = master master.title("Naive Bayes Classifier") creators_lbl = Label(master, text="Alon Galperin\nMatan Yeshurun", font="David", fg="Blue") #browse_button = Button(master, text="Browse", command=lambda: self.loadDataFromPath(browse_textbox.get()),height=1,width=10) browse_button = Button(master, text="Browse", command=lambda: self.getDirPath(), height=1, width=10) self.browse_value = StringVar() self.browse_textbox = Entry(master, width=55, exportselection=0, textvariable=self.browse_value) browse_lbl = Label(master, text="Directory Path: ") build_button = Button(master, text="Build", command=lambda: self.build(), height=1, width=20) classify_button = Button(master, text="Classify", command=lambda: self.classfy(), height=1, width=20) discretization_lbl = Label(master, text="Discretization Bins:") self.discretization_textbox = Entry(master, width=25) creators_lbl.place(x=220, y=20) browse_button.place(x=500, y=95) self.browse_textbox.place(x=150, y=100) browse_lbl.place(x=40, y=100) self.discretization_textbox.place(x=150, y=150) discretization_lbl.place(x=40, y=150) build_button.place(x=200, y=200) classify_button.place(x=200, y=250) master.minsize(width=600, height=400) master.maxsize(width=600, height=400)
def make_widgets(self): widget1 = Label(text="Wybierz dane EKG pacjenta do analizy", background="white") widget1.place(y=30, width=250, height=25) widget2 = Button(text='Wybierz ', command=self.przechwycEKG) widget2.place(x=250, y=30, width=120, height=25) widget3 = Label(text="Wybierz dane EMG pacjenta do analizy", background="white") widget3.place(y=60, width=250, height=25) widget4 = Button(text='Wybierz ', command=self.przechwycEMG) widget4.place(x=250, y=60, width=120, height=25) widget5 = Button(text='Rozpocznij analize danych pacjenta', command=self.call_main_sender) #start to uruchomi sender widget5.place(relx=0.5, rely=0.4, height=40,width=300, anchor=CENTER) Example.root.protocol('WM_DELETE_WINDOW', self.endProgram)
def __init__(self, master=None): self.new = False Tk.__init__(self, master) ScreenManipulation.checkPlatform(self) screensize = self.screensize self.seeding = False '''Setting the Window Size''' self.minsize(screensize[0], screensize[1]) self.rowconfigure(0, weight=1) self.columnconfigure(0, weight=1) '''Setting the Window Size''' '''Menu Bar''' menubar = Menu(self) self.filemenu = Menu(menubar, tearoff=0) self.suggestionmenu = Menu(menubar, tearoff=0) self.helpmenu = Menu(menubar, tearoff=0) tabbedPane = ttk.Notebook(self) t1 = ttk.Frame(tabbedPane) self.t2 = ttk.Frame(tabbedPane) self.tree = ttk.Treeview(t1, columns=("fullpath"), displaycolumns=(0), yscrollcommand=lambda f, l: ScreenManipulation .autoscroll(vsb, f, l)) self.config(menu=menubar) '''FILE MENU''' self.filemenu.add_command(label="Create", command=self.createFile) self.filemenu.add_command(label="Load Dataset", command=self.askToOpenDirectory) self.filemenu.add_command(label="Seed", command=self.seedFile) self.filemenu.add_command(label="Test", command=self.clickTestFile) self.filemenu.add_command(label="Exit", command=lambda: self.destroy()) menubar.add_cascade(label="Experimentation", menu=self.filemenu) '''HELP MENU''' self.helpmenu.add_command(label="About Us", command=aboutUs) self.helpmenu.add_command(label="User's Manual") menubar.add_cascade(label="Help", menu=self.helpmenu) '''Menu Bar''' '''Setting the Tabbed Pane''' tabbedPane.add(t1, text="Project") tabbedPane.add(self.t2, text="Results") tabbedPane.grid(row=0, column=0, sticky=(N, W, S, E)) '''Setting the Tabbed Pane''' '''Widgets''' '''File Text Box''' txtWidth = screensize[0] * .5 txtHeight = screensize[1] * .5 txtPosX = screensize[0] * .36 txtPosY = screensize[1] * .06 self.text = Text(t1, state='disabled', bg='gray', yscrollcommand=lambda f, l: ScreenManipulation. autoscroll(vsb1, f, l)) self.text.place(width=txtWidth, height=txtHeight, x=txtPosX, y=txtPosY) self.text.tag_configure("error", foreground="red", underline=True) vsb1 = Scrollbar(t1, orient="vertical") vsb1['command'] = self.text.yview vsb1Width = screensize[0] * .010 vsb1Height = screensize[1] * .5 vsb1PosX = screensize[0] * .86 vsb1PosY = screensize[1] * .061 vsb1.place(width=vsb1Width, height=vsb1Height, x=vsb1PosX, y=vsb1PosY) '''line numbering''' txtWidth = screensize[0] * .0225 txtHeight = screensize[1] * .5 txtPosX = screensize[0] * .34 txtPosY = screensize[1] * .06 self.lineNumbering = Text(t1, state='disabled', bg='gray', yscrollcommand=lambda f, l: ScreenManipulation.autoscroll(vsb1, f, l)) self.lineNumbering.place(width=txtWidth, height=txtHeight, x=txtPosX, y=txtPosY) vsb1['command'] = self.lineNumbering.yview '''File List Box''' fileWidth = screensize[0] * .30 fileHeight = screensize[1] * .5 filePosX = screensize[0] * .025 filePosY = screensize[1] * .06 self.tree.heading("#0", text="Directory Structure", anchor='w') self.tree.column("#0", stretch=0, width=500) populate_roots(self.tree, self.path) vsb = Scrollbar(t1, orient="vertical") vsb['command'] = self.tree.yview vsbWidth = screensize[0] * .010 vsbHeight = screensize[1] * .5 vsbPosX = screensize[0] * .325 vsbPosY = screensize[1] * .061 vsb.place(width=vsbWidth, height=vsbHeight, x=vsbPosX, y=vsbPosY) self.tree.place(width=fileWidth, height=fileHeight, x=filePosX, y=filePosY) fileLX = screensize[0] * .025 fileLY = screensize[1] * .025 fileLabel = Label(t1, text="Files:") fileLabel.place(x=fileLX, y=fileLY) '''File List Box''' '''Error Table w/ Label''' errLX = screensize[0] * .35 errLY = screensize[1] * .57 self.errLabel = Label(t1, text="Error:") self.errLabel.place(x=errLX, y=errLY) errListWidth = screensize[0] * .6 errListHeight = screensize[1] * .27 errListPosX = screensize[0] * .35 errListPosY = screensize[1] * .60 self.var = tktable.ArrayVar(t1) self.var["%i,%i" % (0, 0)] = 'Line' self.var["%i,%i" % (0, 1)] = 'Column' self.var["%i,%i" % (0, 2)] = 'Description' self.ErrorsTable = tktable.Table( t1, rows=9, cols=3, state='disabled', titlerows=1, selectmode='browse', selecttype='row', colstretch='last', resizeborders='none', flashmode='on', bg='white', variable=self.var, yscrollcommand=lambda x, v: ScreenManipulation.autoscroll( vsb2, x, v)) vsb2 = ttk.Scrollbar(t1, orient="vertical") self.ErrorsTable.tag_configure('flash', background='') vsb2['command'] = self.ErrorsTable.yview vsb2Width = screensize[0] * .010 vsb2Height = screensize[1] * .27 vsb2PosX = screensize[0] * .945 vsb2PosY = screensize[1] * .60 vsb2.place(width=vsb2Width, height=vsb2Height, x=vsb2PosX, y=vsb2PosY) self.ErrorsTable.place(width=errListWidth, height=errListHeight, x=errListPosX, y=errListPosY) '''Error Table w/ Label''' '''Results Table''' self.varRes = tktable.ArrayVar(self.t2) self.varRes["%i,%i" % (0, 0)] = 'FileName' self.varRes["%i,%i" % (0, 1)] = 'Errors Seeded' self.varRes["%i,%i" % (0, 2)] = 'Errors Detected' self.varRes["%i,%i" % (0, 3)] = 'Previous Errors Detected' self.varRes["%i,%i" % (0, 4)] = 'Effectiveness' self.varRes["%i,%i" % (0, 5)] = 'Count' self.resTb = tktable.Table(self.t2, rows=30, cols=6, state='disabled', titlerows=1, colwidth=05, selectmode='browse', selecttype='row', colstretch='all', variable=self.varRes, resizeborders='none', bg='white', yscrollcommand=lambda x, v: ScreenManipulation.autoscroll(vsb5, x, v)) resWidth = self.screensize[0] * .9 resHeight = self.screensize[1] * .85 resPosX = (self.screensize[0] * .5) - (self.screensize[0] * .45) resPosY = (self.screensize[1] * .5) - (self.screensize[1] * .425) self.resTb.place(width=resWidth, height=resHeight, x=resPosX, y=resPosY) vsb5 = Scrollbar(self.t2, orient="vertical") vsb5['command'] = self.resTb.yview vsb5Width = screensize[0] * .010 vsb5Height = screensize[1] * .85 vsb5PosX = (self.screensize[0] * .5) + (self.screensize[0] * .45) vsb5PosY = (self.screensize[1] * .5) - (self.screensize[1] * .425) vsb5.place(width=vsb5Width, height=vsb5Height, x=vsb5PosX, y=vsb5PosY) '''Results Table''' '''Suggestion Box''' sugLX = screensize[0] * .025 sugLY = screensize[1] * .57 self.sugLabel = Label(t1, text="Suggestion:") self.sugLabel.place(x=sugLX, y=sugLY) exactLX = screensize[0] * .025 exactLY = screensize[1] * .87 self.exacMatchLabel = Label(t1, text="Exact Match: None") self.exacMatchLabel.place(x=exactLX, y=exactLY) sugWidth = screensize[0] * .31 sugHeight = screensize[1] * .27 sugPosX = screensize[0] * .025 sugPosY = screensize[1] * .60 self.var2 = tktable.ArrayVar(t1) self.var2["%i,%i" % (0, 0)] = 'Tag' self.var2["%i,%i" % (0, 1)] = 'Value' suggestion = tktable.Table(t1, rows=10, cols=2, state='disabled', titlerows=1, colwidth=30, selectmode='browse', selecttype='row', colstretch='last', variable=self.var2, resizeborders='none', bg='white', yscrollcommand=lambda x, v: ScreenManipulation.autoscroll(vsb3, x, v)) vsb3 = ttk.Scrollbar(t1, orient="vertical") vsb3['command'] = suggestion.yview vsb3Width = screensize[0] * .010 vsb3Height = screensize[1] * .27 vsb3PosX = screensize[0] * .325 vsb3PosY = screensize[1] * .60 vsb3.place(width=vsb3Width, height=vsb3Height, x=vsb3PosX, y=vsb3PosY) suggestion.place(width=sugWidth, height=sugHeight, x=sugPosX, y=sugPosY) '''Suggestion Box''' '''Button''' brws = Button(t1, text='Browser', command=self.toBrowser) bWidth = screensize[0] * .1 bHeight = screensize[1] * .05 bPosX = screensize[0] * .875 bPosY = screensize[1] * .1 brws.place(width=bWidth, height=bHeight, x=bPosX, y=bPosY) Save = Button(t1, text='Save', command=self.toSave) SWidth = screensize[0] * .1 SHeight = screensize[1] * .05 SPosX = screensize[0] * .875 SPosY = screensize[1] * .15 Save.place(width=SWidth, height=SHeight, x=SPosX, y=SPosY) perfCorr = Button(t1, text='Edit', command=self.enableText) SWidth = screensize[0] * .1 SHeight = screensize[1] * .05 SPosX = screensize[0] * .875 SPosY = screensize[1] * .20 perfCorr.place(width=SWidth, height=SHeight, x=SPosX, y=SPosY) Val = Button(t1, text='Validate', command=self.validateFile) VWidth = screensize[0] * .1 VHeight = screensize[1] * .05 VPosX = screensize[0] * .875 VPosY = screensize[1] * .25 Val.place(width=VWidth, height=VHeight, x=VPosX, y=VPosY) suggest = Button(t1, text='View Suggestion', command=self.clickSuggestion) SWidth = screensize[0] * .1 SHeight = screensize[1] * .05 SPosX = screensize[0] * .35 SPosY = screensize[1] * .875 suggest.place(width=SWidth, height=SHeight, x=SPosX, y=SPosY) '''Button''' self.LLine = Label(t1, text='Line: \n') LLWidth = screensize[0] * .1 LLHeight = screensize[1] * .05 LLPosX = screensize[0] * .875 LLPosY = screensize[1] * .4 self.LLine.place(width=LLWidth, height=LLHeight, x=LLPosX, y=LLPosY) self.LColumn = Label(t1, text='Column: \n') LCWidth = screensize[0] * .1 LCHeight = screensize[1] * .05 LCPosX = screensize[0] * .875 LCPosY = screensize[1] * .45 self.LColumn.place(width=LCWidth, height=LCHeight, x=LCPosX, y=LCPosY) '''Status Bar''' errDetWidth = screensize[0] * .25 errDetHeight = screensize[1] * .03 errDetPosX = screensize[0] * .0 errDetPosY = screensize[1] * .93 self.errDetected = Label(t1, text="Errors Seeded: N/A", relief=SUNKEN) self.errDetected.place(width=errDetWidth, height=errDetHeight, x=errDetPosX, y=errDetPosY) totErrWidth = screensize[0] * .25 totErrHeight = screensize[1] * .03 totErrPosX = screensize[0] * .25 totErrPosY = screensize[1] * .93 self.totErrDetected = Label(t1, text="Total Errors Detected: N/A", relief=SUNKEN) self.totErrDetected.place(width=totErrWidth, height=totErrHeight, x=totErrPosX, y=totErrPosY) effWidth = screensize[0] * .25 effHeight = screensize[1] * .03 effPosX = screensize[0] * .50 effPosY = screensize[1] * .93 self.effectiveness = Label(t1, text="Effectiveness: N/A", relief=SUNKEN) self.effectiveness.place(width=effWidth, height=effHeight, x=effPosX, y=effPosY) ptotErrWidth = screensize[0] * .25 ptotErrHeight = screensize[1] * .03 ptotErrPosX = screensize[0] * .75 ptotErrPosY = screensize[1] * .93 self.ptotErrDetected = Label(t1, text="Previous Errors Detected: N/A", relief=SUNKEN) self.ptotErrDetected.place(width=ptotErrWidth, height=ptotErrHeight, x=ptotErrPosX, y=ptotErrPosY) '''Status Bar''' self.tree.bind('<<TreeviewOpen>>', update_tree) self.tree.bind('<<TreeviewSelect>>', self.readAndCreateRecord) tabbedPane.bind('<<NotebookTabChanged>>', self.results) self.text.bind('<Button-1>', self.key)
class Application(object): def __init__(self): self.logger = get_logger('dashboard') self.server = SocketServer.UDPServer( (settings.DASHBOARD_HOST, settings.DASHBOARD_PORT), self.handle_request) self.server.timeout = settings.DASHBOARD_REQUEST_TIMEOUT self.raw_telem_time = 0 self.raw_telem_bat = 0 self.raw_telem_temp = 0 self.raw_telem_photo = 0 self.__init_main() self.__init_motor() self.__init_light() self.__init_video() self.__init_telem() def __init_main(self): self.window = Tk() self.window.wm_minsize(400, 400) def __init_motor(self): self.w_lf_motor = LabelFrame(self.window, text=u'Моторы') self.w_scale_motor1 = Scale(self.w_lf_motor, from_=-255, to=255) self.w_scale_motor2 = Scale(self.w_lf_motor, from_=-255, to=255) self.w_lf_motor.place(relx=0, rely=0, relwidth=1, relheight=0.3) self.w_scale_motor1.place(relx=0, rely=0, relwidth=1, relheight=1) self.w_scale_motor2.place(relx=0.5, rely=0, relwidth=1, relheight=1) def __init_light(self): self.w_lf_light = LabelFrame(self.window, text=u'Свет') self.w_l_light = Label(self.w_lf_light, text=u'Выключен', fg='red', font='Arial 20') self.w_lf_light.place(relx=0, rely=0.3, relwidth=1, relheight=0.15) self.w_l_light.place(relx=0, rely=0, relwidth=1, relheight=1) def __init_video(self): self.w_lf_video = LabelFrame(self.window, text=u'Видео') self.w_l_video = Label(self.w_lf_video, text=u'Выключен', fg='red', font='Arial 20') self.w_b_show = Button(self.w_lf_video, text=u'mplayer', command=self.start_mplayer) self.w_lf_video.place(relx=0, rely=0.45, relwidth=1, relheight=0.15) self.w_l_video.place(relx=0, rely=0, relwidth=0.7, relheight=1) self.w_b_show.place(relx=0.7, rely=0, relwidth=0.3, relheight=1) def __init_telem(self): # телеметрия self.w_lf_telem = LabelFrame(self.window, text=u'Телеметрия') self.w_l_telem_time = Label(self.w_lf_telem, text=u'0', font='Arial 15') self.w_l_telem_bat = Label(self.w_lf_telem, text=u'0', font='Arial 15') self.w_l_telem_temp = Label(self.w_lf_telem, text=u'0', font='Arial 15') self.w_l_telem_photo = Label(self.w_lf_telem, text=u'0', font='Arial 15') self.w_lf_telem.place(relx=0, rely=0.6, relwidth=1, relheight=0.4) Label(self.w_lf_telem, text=u'Время:', font='Arial 15').place(relx=0, rely=0, relwidth=0.5, relheight=0.25) Label(self.w_lf_telem, text=u'Батарея:', font='Arial 15').place(relx=0, rely=0.25, relwidth=0.5, relheight=0.25) Label(self.w_lf_telem, text=u'Температура:', font='Arial 15').place(relx=0, rely=0.5, relwidth=0.5, relheight=0.25) Label(self.w_lf_telem, text=u'Освещенность:', font='Arial 15').place(relx=0, rely=0.75, relwidth=0.5, relheight=0.25) self.w_l_telem_time.place(relx=0.5, rely=0, relwidth=0.5, relheight=0.25) self.w_l_telem_bat.place(relx=0.5, rely=0.25, relwidth=0.5, relheight=0.25) self.w_l_telem_temp.place(relx=0.5, rely=0.5, relwidth=0.5, relheight=0.25) self.w_l_telem_photo.place(relx=0.5, rely=0.75, relwidth=0.5, relheight=0.25) def set_motor_value(self, left_value, right_value): if left_value > 255: left_value = 255 elif left_value < -255: left_value = -255 self.w_scale_motor1.set(left_value) if right_value > 255: right_value = 255 elif right_value < -255: right_value = -255 self.w_scale_motor2.set(right_value) def set_light(self, value): """ устанавливает значение для фонарика :param value: """ if value == 1: self.w_l_light['text'] = u'Включен' self.w_l_light['fg'] = 'green' else: self.w_l_light['text'] = u'Выключен' self.w_l_light['fg'] = 'red' def set_video(self, value): """ устанавливает значение для фонарика :param value: """ if value == 1: self.w_l_video['text'] = u'Включен' self.w_l_video['fg'] = 'green' else: self.w_l_video['text'] = u'Выключен' self.w_l_video['fg'] = 'red' def set_time(self, value): """ устанавливает значение для даты :param value: """ if self.raw_telem_time == value: return self.raw_telem_time = value try: value = datetime.fromtimestamp(value).strftime('%Y.%m.%d %H:%M:%S') except Exception as err: print(err) self.logger.debug(str(err)) self.w_l_telem_time['text'] = value def set_bat(self, value): """ устанавливает значение для батареи :param value: """ if self.raw_telem_bat == value: return self.raw_telem_bat = value self.w_l_telem_bat['text'] = value def set_temp(self, value): """ устанавливает значение для температуры :param value: """ if self.raw_telem_temp == value: return self.raw_telem_temp = value self.w_l_telem_temp['text'] = '{0} ({1})'.format( round((value * 3.3 / 1024 - 0.5) / 0.01, 3), value) def set_photo(self, value): """ устанавливает значение для температуры :param value: """ if self.raw_telem_photo == value: return self.raw_telem_photo = value self.w_l_telem_photo['text'] = value def start_mplayer(self): """ включает mplayer """ process = subprocess.Popen(settings.VIDEO_SHOW_CMD, shell=True) def handle_request(self, request, client_address, server): """ обработка входных данных :param request: :param client_address: :param server: :return: """ _request, _socket = request if ',' not in _request: return values = [int(i) for i in _request.split(',')] self.set_motor_value(*values[:2]) self.set_light(values[2]) self.set_video(values[3]) self.set_time(values[4]) self.set_temp(values[5]) self.set_bat(values[6]) self.set_photo(values[7]) def wait_request(self): """""" self.server.handle_request() self.register_mainloop() def register_mainloop(self): """ регистриуем обработчик, который периодический будет обрабатывать события """ self.window.after(after_timeout, self.wait_request) def run(self): """""" try: self.register_mainloop() self.window.mainloop() except KeyboardInterrupt: pass except Exception as err: self.logger.debug(err) import traceback self.logger.debug(traceback.format_exc()) raise
class Run(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent self.initConfig() self.initUI() def initConfig(self): self.run = False self.lastText = np.array([ "450.00", "450.00", "450.00", "450.00", "450.00", "450.00", "0.00", "0.00", "0.00", "0.00", "0.00", "0.00" ]) self.L = np.array([[ float(self.lastText[0]), float(self.lastText[1]), float(self.lastText[2]), float(self.lastText[3]), float(self.lastText[4]), float(self.lastText[5]) ]]) # motor parameter self.Bm = 1.15 self.Jm = 0.18 self.Km = 0.01 # PID parameter self.KP_L = 20 self.KP_L_dot = 200 self.TI_L_dot = 2 self.TD_L_dot = 0.0 # delta time self.dt = 0.01 def initUI(self): self.parent.title("5 AXIS STEWART CNC G-CODE READER") self.pack(fill=BOTH, expand=1) self.line = 1.0 self.maxLine = 1.0 menubar = Menu(self.parent) self.parent.config(menu=menubar) fileMenu = Menu(menubar) fileMenu.add_command(label="Open", command=self.onOpen) fileMenu.add_command(label="Clear", command=self.onClear) fileMenu.add_command(label="Save", command=self.onSave) fileMenu.add_command(label="Exit", command=self.onExit) menubar.add_cascade(label="File", menu=fileMenu) runMenu = Menu(menubar) runMenu.add_command(label="Initialize", command=self.onInit) runMenu.add_command(label="Run/Pause", command=self.onRun) runMenu.add_command(label="Stop", command=self.onStop) menubar.add_cascade(label="Run", menu=runMenu) self.execButton = Button(self, text="Execute", command=self.onExec) self.execButton.place(x=950, y=20) self.prevButton = Button(self, text="Prev", command=self.onPrev) self.prevButton.place(x=1080, y=20) self.nextButton = Button(self, text="Next", command=self.onNext) self.nextButton.place(x=1140, y=20) self.notif = "Application Started" self.lblNC = Label(self, text="NC") self.lblNC.place(x=10, y=0) self.lblL = Label(self, text="Link Length - Link Length/sec") self.lblL.place(x=930, y=80) self.lblL1 = Label( self, text= "1 : mm mm/s" ) self.lblL1.place(x=900, y=120) self.lblL2 = Label( self, text= "2 : mm mm/s" ) self.lblL2.place(x=900, y=150) self.lblL3 = Label( self, text= "3 : mm mm/s" ) self.lblL3.place(x=900, y=180) self.lblL4 = Label( self, text= "4 : mm mm/s" ) self.lblL4.place(x=900, y=210) self.lblL5 = Label( self, text= "5 : mm mm/s" ) self.lblL5.place(x=900, y=240) self.lblL6 = Label( self, text= "6 : mm mm/s" ) self.lblL6.place(x=900, y=270) self.txtNC = Text(self, width=120, height=17) self.txtNC.place(x=10, y=20) self.txtNC.tag_configure('highlightline', background="#a9e9e9") self.txtNC.config(font=("TkTextFont", 10)) self._highlight_current_line() self.txtL1 = Text(self, width=10, height=1) self.txtL1.place(x=930, y=120) self.txtL2 = Text(self, width=10, height=1) self.txtL2.place(x=930, y=150) self.txtL3 = Text(self, width=10, height=1) self.txtL3.place(x=930, y=180) self.txtL4 = Text(self, width=10, height=1) self.txtL4.place(x=930, y=210) self.txtL5 = Text(self, width=10, height=1) self.txtL5.place(x=930, y=240) self.txtL6 = Text(self, width=10, height=1) self.txtL6.place(x=930, y=270) self.txtL1Dot = Text(self, width=10, height=1) self.txtL1Dot.place(x=1090, y=120) self.txtL2Dot = Text(self, width=10, height=1) self.txtL2Dot.place(x=1090, y=150) self.txtL3Dot = Text(self, width=10, height=1) self.txtL3Dot.place(x=1090, y=180) self.txtL4Dot = Text(self, width=10, height=1) self.txtL4Dot.place(x=1090, y=210) self.txtL5Dot = Text(self, width=10, height=1) self.txtL5Dot.place(x=1090, y=240) self.txtL6Dot = Text(self, width=10, height=1) self.txtL6Dot.place(x=1090, y=270) self.f = Figure(figsize=(13.0, 3.5), dpi=100) self.canvas = FigureCanvasTkAgg(self.f, self) self.canvas.draw() # self.ax = Axes3D(self.f) # self.ax.mouse_init() # self.set_ax() self.canvas.get_tk_widget().place(x=10, y=350) def extractNC(self): self.extractL1() self.extractL2() self.extractL3() self.extractL4() self.extractL5() self.extractL6() self.extractL1Dot() self.extractL2Dot() self.extractL3Dot() self.extractL4Dot() self.extractL5Dot() self.extractL6Dot() def extractL1(self): try: posL1 = self.txtNC.search("LA", self.line, str(int(self.line)) + '.end', 8) textL1 = self.txtNC.get(posL1 + '+2c', posL1 + '+8c') self.txtL1.insert(1.0, textL1) self.lastText[0] = textL1 except: self.txtL1.insert(1.0, self.lastText[0]) return (self.txtL1.get(1.0, 'end')) def extractL2(self): try: posL2 = self.txtNC.search("LB", self.line, str(int(self.line)) + '.end', 8) textL2 = self.txtNC.get(posL2 + '+2c', posL2 + '+8c') self.txtL2.insert(1.0, textL2) self.lastText[1] = textL2 except: self.txtL2.insert(1.0, self.lastText[1]) return (self.txtL2.get(1.0, 'end')) def extractL3(self): try: posL3 = self.txtNC.search("LC", self.line, str(int(self.line)) + '.end', 8) textL3 = self.txtNC.get(posL3 + '+2c', posL3 + '+8c') self.txtL3.insert(1.0, textL3) self.lastText[2] = textL3 except: self.txtL3.insert(1.0, self.lastText[2]) return (self.txtL3.get(1.0, 'end')) def extractL4(self): try: posL4 = self.txtNC.search("LD", self.line, str(int(self.line)) + '.end', 8) textL4 = self.txtNC.get(posL4 + '+2c', posL4 + '+8c') self.txtL4.insert(1.0, textL4) self.lastText[3] = textL4 except: self.txtL4.insert(1.0, self.lastText[3]) return (self.txtL4.get(1.0, 'end')) def extractL5(self): try: posL5 = self.txtNC.search("LE", self.line, str(int(self.line)) + '.end', 8) textL5 = self.txtNC.get(posL5 + '+2c', posL5 + '+8c') self.txtL5.insert(1.0, textL5) self.lastText[4] = textL5 except: self.txtL5.insert(1.0, self.lastText[4]) return (self.txtL5.get(1.0, 'end')) def extractL6(self): try: posL6 = self.txtNC.search("LF", self.line, str(int(self.line)) + '.end', 8) textL6 = self.txtNC.get(posL6 + '+2c', posL6 + '+8c') self.txtL6.insert(1.0, textL6) self.lastText[5] = textL6 except: self.txtL6.insert(1.0, self.lastText[5]) return (self.txtL6.get(1.0, 'end')) def extractL1Dot(self): try: posL1Dot = self.txtNC.search("dLA", self.line, str(int(self.line)) + '.end', 8) textL1Dot = self.txtNC.get(posL1Dot + '+3c', posL1Dot + '+8c') self.txtL1Dot.insert(1.0, textL1Dot) self.lastText[6] = textL1Dot except: self.txtL1Dot.insert(1.0, self.lastText[6]) return (self.txtL1Dot.get(1.0, 'end')) def extractL2Dot(self): try: posL2Dot = self.txtNC.search("dLB", self.line, str(int(self.line)) + '.end', 8) textL2Dot = self.txtNC.get(posL2Dot + '+3c', posL2Dot + '+8c') self.txtL2Dot.insert(1.0, textL2Dot) self.lastText[7] = textL2Dot except: self.txtL2Dot.insert(1.0, self.lastText[7]) return (self.txtL2Dot.get(1.0, 'end')) def extractL3Dot(self): try: posL3Dot = self.txtNC.search("dLC", self.line, str(int(self.line)) + '.end', 8) textL3Dot = self.txtNC.get(posL3Dot + '+3c', posL3Dot + '+8c') self.txtL3Dot.insert(1.0, textL3Dot) self.lastText[8] = textL3Dot except: self.txtL3Dot.insert(1.0, self.lastText[8]) return (self.txtL3Dot.get(1.0, 'end')) def extractL4Dot(self): try: posL4Dot = self.txtNC.search("dLD", self.line, str(int(self.line)) + '.end', 8) textL4Dot = self.txtNC.get(posL4Dot + '+3c', posL4Dot + '+8c') self.txtL4Dot.insert(1.0, textL4Dot) self.lastText[9] = textL4Dot except: self.txtL4Dot.insert(1.0, self.lastText[9]) return (self.txtL4Dot.get(1.0, 'end')) def extractL5Dot(self): try: posL5Dot = self.txtNC.search("dLE", self.line, str(int(self.line)) + '.end', 8) textL5Dot = self.txtNC.get(posL5Dot + '+3c', posL5Dot + '+8c') self.txtL5Dot.insert(1.0, textL5Dot) self.lastText[10] = textL5Dot except: self.txtL5Dot.insert(1.0, self.lastText[10]) return (self.txtL5Dot.get(1.0, 'end')) def extractL6Dot(self): try: posL6Dot = self.txtNC.search("dLF", self.line, str(int(self.line)) + '.end', 8) textL6Dot = self.txtNC.get(posL6Dot + '+3c', posL6Dot + '+8c') self.txtL6Dot.insert(1.0, textL6Dot) self.lastText[11] = textL6Dot except: self.txtL6Dot.insert(1.0, self.lastText[11]) return (self.txtL6Dot.get(1.0, 'end')) def extractT(self): posT = self.txtNC.search("T", self.line, str(int(self.line)) + '.end', 8) return (float(self.txtNC.get(posT + '+1c', posT + '+4c'))) def _highlight_current_line(self, interval=100): '''Updates the 'current line' highlighting every "interval" milliseconds''' self.txtNC.tag_remove('highlightline', 1.0, "end") self.txtNC.tag_add('highlightline', self.line, str(int(self.line)) + '.end+1c') self.after(interval, self._highlight_current_line) def draw(self): self.f.clear() self.f.add_subplot(2, 6, 1).set_ylim([-30, 30]) self.f.add_subplot(2, 6, 2).set_ylim([-30, 30]) self.f.add_subplot(2, 6, 3).set_ylim([-30, 30]) self.f.add_subplot(2, 6, 4).set_ylim([-30, 30]) self.f.add_subplot(2, 6, 5).set_ylim([-30, 30]) self.f.add_subplot(2, 6, 6).set_ylim([-30, 30]) self.f.add_subplot(2, 6, 1).plot(self.time, self.L_dot_ref[:, 0], self.time, self.L_dot[:, 0]) self.f.add_subplot(2, 6, 2).plot(self.time, self.L_dot_ref[:, 1], self.time, self.L_dot[:, 1]) self.f.add_subplot(2, 6, 3).plot(self.time, self.L_dot_ref[:, 2], self.time, self.L_dot[:, 2]) self.f.add_subplot(2, 6, 4).plot(self.time, self.L_dot_ref[:, 3], self.time, self.L_dot[:, 3]) self.f.add_subplot(2, 6, 5).plot(self.time, self.L_dot_ref[:, 4], self.time, self.L_dot[:, 4]) self.f.add_subplot(2, 6, 6).plot(self.time, self.L_dot_ref[:, 5], self.time, self.L_dot[:, 5]) self.f.add_subplot(2, 6, 7).set_ylim([450, 750]) self.f.add_subplot(2, 6, 8).set_ylim([450, 750]) self.f.add_subplot(2, 6, 9).set_ylim([450, 750]) self.f.add_subplot(2, 6, 10).set_ylim([450, 750]) self.f.add_subplot(2, 6, 11).set_ylim([450, 750]) self.f.add_subplot(2, 6, 12).set_ylim([450, 750]) self.f.add_subplot(2, 6, 7).plot(self.time, self.L_ref[:, 0], self.time, self.L[:, 0]) self.f.add_subplot(2, 6, 8).plot(self.time, self.L_ref[:, 1], self.time, self.L[:, 1]) self.f.add_subplot(2, 6, 9).plot(self.time, self.L_ref[:, 2], self.time, self.L[:, 2]) self.f.add_subplot(2, 6, 10).plot(self.time, self.L_ref[:, 3], self.time, self.L[:, 3]) self.f.add_subplot(2, 6, 11).plot(self.time, self.L_ref[:, 4], self.time, self.L[:, 4]) self.f.add_subplot(2, 6, 12).plot(self.time, self.L_ref[:, 5], self.time, self.L[:, 5]) def onExec(self): self.resetData() self.control() self.draw() self.canvas.draw() def control(self): self.L_dot = np.zeros([1, 6]) self.L_dot_ref = self.L_dot # self.L = np.array([[597.010, 597.010, 597.010, 597.010, 597.010, 597.010]]) self.L = np.array([[ float(self.lastText[0]), float(self.lastText[1]), float(self.lastText[2]), float(self.lastText[3]), float(self.lastText[4]), float(self.lastText[5]) ]]) self.L_ref = self.L # position and velocity goals #L_goal = np.ones(6) * 597.018 # self.L_goal = np.array([594.41, 597.16, 594.44, 601.93, 602.65, 592.40]) #L_dot_goal = np.ones(6) * 9.063 # self.L_dot_goal = np.array([-0.920, 0.05, -0.910, 1.74, 1.99, -1.63]) self.L_goal = np.array([ float(self.extractL1()), float(self.extractL2()), float(self.extractL3()), float(self.extractL4()), float(self.extractL5()), float(self.extractL6()) ]) self.L_dot_goal = np.array([ float(self.extractL1Dot()), float(self.extractL2Dot()), float(self.extractL3Dot()), float(self.extractL4Dot()), float(self.extractL5Dot()), float(self.extractL6Dot()) ]) self.L_delta = self.L_goal - self.L[-1, :] # error initialization self.error_L_dot_last = np.zeros(6) self.error_L_dot = self.L_dot_ref[0, :] - self.L_dot[0, :] self.error_L = self.L_ref[0, :] - self.L[0, :] self.int_L_dot = 0 self.dif_L_dot = 0 self.time = np.zeros(1) self.time_rise = 0.1 self.time_delay = 0.1 self.time_goal_array = np.zeros(6) if (abs(self.L_dot_goal[0]) > 0): print(abs(self.L_delta[0] / self.L_dot_goal[0])) self.time_goal = self.extractT() else: self.time_goal = self.time_delay self.n_rise = int(self.time_rise / self.dt) self.n_goal = int(self.time_goal / self.dt) for self.n in range(0, self.n_goal + self.n_rise): # sensor acquisition here # motion planning velocity rising = np.ones(6) * (self.n / float(self.n_rise)) falling = np.ones(6) * ( (self.n - self.n_goal) / float(self.n_rise)) if (self.n < self.n_rise): self.L_dot_ref = np.append(self.L_dot_ref, self.L_dot_goal * rising[None, :], axis=0) elif (self.n < self.n_goal) and (self.n >= self.n_rise): self.L_dot_ref = np.append(self.L_dot_ref, self.L_dot_goal[None, :], axis=0) elif (self.n < self.n_goal + self.n_rise) and (self.n >= self.n_goal): self.L_dot_ref = np.append( self.L_dot_ref, -self.L_dot_goal * falling[None, :] + self.L_dot_goal, axis=0) elif (self.n > self.n_goal): self.L_dot_ref = np.append(self.L_dot_ref, np.zeros(6)) # motion planning position self.data_L_ref = self.L_ref[self.n, :] + ( self.L_dot_ref[self.n, :] * self.dt) self.L_ref = np.append(self.L_ref, self.data_L_ref[None, :], axis=0) # error L calculation self.error_L = self.L_ref[self.n, :] - self.L[self.n, :] # output PID L if (self.n % 10 == 0): self.PID_L = self.KP_L * self.error_L # error L dot calculation self.error_L_dot = self.L_dot_ref[self.n, :] - self.L_dot[ self.n, :] + self.PID_L self.int_L_dot += self.error_L_dot self.dif_L_dot = self.error_L_dot - self.error_L_dot_last # output PID L dot self.PID_L_dot = self.KP_L_dot * ( self.error_L_dot + 1 / self.TI_L_dot * self.int_L_dot + self.TD_L_dot * self.dif_L_dot) # plant simulation self.data_L_dot = (1 - (self.Bm / self.Jm) * self.dt) * self.L_dot[ self.n, :] + (self.Km / self.Jm) * self.PID_L_dot * self.dt self.data_L = self.L[self.n, :] + self.L_dot[self.n, :] * self.dt self.L_dot = np.append(self.L_dot, self.data_L_dot[None, :], axis=0) self.L = np.append(self.L, self.data_L[None, :], axis=0) # n + 1 self.error_L_dot_last = self.error_L_dot self.time = np.append(self.time, self.time[self.n] + self.dt) def onPrev(self): if self.line > 1.0: self.line -= 1.0 else: self.line = 1.0 def onNext(self): if self.line < self.maxLine: self.line += 1.0 def onSave(self): name = tkFileDialog.asksaveasfile(mode='w', defaultextension=".spnc") text2save = str(self.txtNC.get(0.0, END)) name.write(text2save) name.close def onClear(self): self.txtNC.delete(1.0, 'end') self.trajectoryG0 = np.array([[0.], [0.], [0.]]) self.trajectoryG1 = np.array([[0.], [0.], [0.]]) self.draw() self.canvas.draw() def onOpen(self): ftypes = [('Stewart Platform NC files', '*.spnc'), ('All files', '*')] dlg = tkFileDialog.Open(self, filetypes=ftypes) fl = dlg.show() if fl != '': text = self.readFile(fl) self.txtNC.insert(1.0, text) self.maxLine = math.floor(float(self.txtNC.index('end-1c'))) def readFile(self, filename): f = open(filename, "r") text = f.read() return text def onInit(self): self.trajectoryG0 = np.array([[0.], [0.], [0.]]) self.trajectoryG1 = np.array([[0.], [0.], [0.]]) self.line = 1.0 self.onExec() def onRun(self): self.run = not self.run if self.run: print("Robot Started") #time.sleep(5) while self.line <= self.maxLine: self.onExec() # t = 0. # while t < self.travelTime: # t+=0.1 #time.sleep(0.1) # run control here if self.line == self.maxLine: self.onStop() if not self.run: break #time.sleep(5) self.onNext() else: print("Robot Paused") def onStop(self): print("Robot Stopped") self.run = False def onExit(self): self.quit() self.destroy() def resetData(self): self.txtL1.delete(1.0, 'end') self.txtL2.delete(1.0, 'end') self.txtL3.delete(1.0, 'end') self.txtL4.delete(1.0, 'end') self.txtL5.delete(1.0, 'end') self.txtL6.delete(1.0, 'end') self.txtL1Dot.delete(1.0, 'end') self.txtL2Dot.delete(1.0, 'end') self.txtL3Dot.delete(1.0, 'end') self.txtL4Dot.delete(1.0, 'end') self.txtL5Dot.delete(1.0, 'end') self.txtL6Dot.delete(1.0, 'end')
class ChooseNameUI(Frame): def __init__(self, parent,names=["1","2","3"]): Frame.__init__(self, parent) self.parent = parent self.names = names self.initUI() self.centerWindow() def initUI(self): self.parent.title("选择角色名字") self.pack(fill=BOTH, expand=1) "source list" self.lb = Listbox(self) for i in self.names: self.lb.insert(END, i) self.lb.bind("<<ListboxSelect>>", self.onSelect) self.lb.place(x=80, y=20) "right list" self.lbRight = Listbox(self) #self.lbRight.bind("<<ListboxSelect>>", self.onSelect) self.lbRight.place(x=150, y=240) "left list" self.lbLeft = Listbox(self) #self.lbLeft.bind("<<ListboxSelect>>", self.onSelect) self.lbLeft.place(x=20, y=240) "label" self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=120, y=400) "left button" leftButton = Button(self, text="增加到自己的名字", command=self.leftClick) leftButton.place(x=20,y=180) "left add all button" leftAddAllBtn = Button(self, text="添加剩下的名字到自己", command=self.leftAddAllClick) leftAddAllBtn.place(x=20,y=210) "right button" rightButton = Button(self, text="增加到对方的名字", command=self.rightClick) rightButton.place(x = 150, y = 180) "right add all button" rightAddAllBtn = Button(self, text="添加剩下的名字到对方", command=self.rightAddAllClick) rightAddAllBtn.place(x=150,y=210) "move to right button" left2RightBtn = Button(self, text="移动到自己", command=self.move2Left) left2RightBtn.place(x=150,y=380) "move to left button" left2RightBtn = Button(self, text="移动到对方", command=self.move2Right) left2RightBtn.place(x=20,y=380) "finish button" self.finishBtn = Button(self, text="选择完毕", command = self.finishClick) self.finishBtn.place(x = 120 , y = 420) def onSelect(self, val): sender = val.widget idx = sender.curselection() if idx: value = sender.get(idx) self.var.set(value) def leftClick(self): str = self.var.get() if str is not None and str != "": self.lbLeft.insert(END,str) self.removeSelection() def rightClick(self): str = self.var.get() if str is not None and str != "": self.lbRight.insert(END,str) self.removeSelection() def removeSelection(self): index = self.lb.curselection() self.lb.delete(index,index) self.var.set("") "if select all data finish" if not self.lb.get(0): self.finishClick() def finishClick(self): if self.lb.get(0): box.showerror("错误", "还有名字没加入") else: if not self.lbLeft.get(0): box.showerror("错误", "没有自己的名字,请选择") elif not self.lbRight.get(0): box.showerror("错误", "没有对方的名字,请选择") else: "get the two list and generate json" myList = [self.lbLeft.get(i) for i in xrange(self.lbLeft.size())] herList = [self.lbRight.get(i) for i in xrange(self.lbRight.size())] #conversationtool.generateJSON(myList,herList) t = conversationtool.generateThread(myList,herList) t.start() t.join() def rightAddAllClick(self): while self.lb.get(0): value = self.lb.get(0) self.lb.delete(0) self.lbRight.insert(END , value) self.var.set("") def leftAddAllClick(self): while self.lb.get(0): value = self.lb.get(0) self.lb.delete(0) self.lbLeft.insert(END,value) self.var.set("") def move2Right(self): index = self.lbLeft.curselection() if index: value = self.lbLeft.get(index) self.lbLeft.delete(index) self.lbRight.insert(END, value) else: box.showerror("错误", "请选择自己的名字") def move2Left(self): index = self.lbRight.curselection() if index: value = self.lbRight.get(index) self.lbRight.delete(index) self.lbLeft.insert(END , value) else: box.showerror("错误", "请选择对方的名字") def centerWindow(self): w = 300 h = 450 sw = self.parent.winfo_screenwidth() sh = self.parent.winfo_screenheight() x = (sw - w)/2 y = (sh - h)/2 self.parent.geometry('%dx%d+%d+%d' % (w, h, x, y))
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 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 QuizLetter(Frame): def __init__(self, parent): Frame.__init__(self, parent) self.parent = parent # generate the options of buttons keys = shuffle_dictionary(LETTERS) right_answer, answers = generate_letters(keys, NUM_LETTERS) # create window self.create_window() self.create_letter(right_answer) #self.create_button() self.create_play_button(answers) self.create_option_buttons(right_answer, answers) def create_window (self): self.parent.geometry(WINDOW_DIMENSIONS) self.parent.title(TITLE) def create_letter(self, right_answer): self.label = Label(self.parent, text=right_answer, font=("",80)) self.label.pack() def create_play_button(self, answers): # create list of oggs list_oggs = [] i= 0 for i in range(0, NUM_LETTERS): list_oggs.append(LETTERS[answers[i]][1]) i+=1 self.play_image = PhotoImage(file=IMAGES_PATH + 'play.png') # create the button self.play_button = Button(self.parent,width=40,height=30,fg='black', image=self.play_image, command=lambda: play_ogg(list_oggs)).place(x=5,y=102) def right_button(self, button): """ Button right green and sound """ button.config(background = "green") button.config(activebackground="green") pygame.mixer.music.load(SOUNDS_PATH + 'right.ogg') pygame.mixer.music.play() def wrong_button(self, button): """ Button wrong red and sound """ button.config(background = "red") button.config(activebackground="red") pygame.mixer.music.load(SOUNDS_PATH + 'wrong.ogg') pygame.mixer.music.play() def create_option_buttons(self, right_answer, answers): # create buttons self.option_1 = Button(self.parent,width=7,height=3,fg='black', text=LETTERS[answers[0]][0]) self.option_1.place(x=5,y=140) self.option_2 = Button(self.parent,width=7,height=3,fg='black', text=LETTERS[answers[1]][0]) self.option_2.place(x=5,y=200) self.option_3 = Button(self.parent,width=7,height=3,fg='black', text=LETTERS[answers[2]][0]) self.option_3.place(x=95,y=140) self.option_4 = Button(self.parent,width=7,height=3,fg='black', text=LETTERS[answers[3]][0]) self.option_4.place(x=95,y=200) self.option_1.config(command=lambda: self.right_button(self.option_1) if answers[0] == right_answer else self.wrong_button(self.option_1)) self.option_2.config(command=lambda: self.right_button(self.option_2) if answers[1] == right_answer else self.wrong_button(self.option_2)) self.option_3.config(command=lambda: self.right_button(self.option_3) if answers[2] == right_answer else self.wrong_button(self.option_3)) self.option_4.config(command=lambda: self.right_button(self.option_4) if answers[3] == right_answer else self.wrong_button(self.option_4))
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)
def initUI(self): self.parent.title("选择角色名字") self.pack(fill=BOTH, expand=1) "source list" self.lb = Listbox(self) for i in self.names: self.lb.insert(END, i) self.lb.bind("<<ListboxSelect>>", self.onSelect) self.lb.place(x=80, y=20) "right list" self.lbRight = Listbox(self) #self.lbRight.bind("<<ListboxSelect>>", self.onSelect) self.lbRight.place(x=150, y=240) "left list" self.lbLeft = Listbox(self) #self.lbLeft.bind("<<ListboxSelect>>", self.onSelect) self.lbLeft.place(x=20, y=240) "label" self.var = StringVar() self.label = Label(self, text=0, textvariable=self.var) self.label.place(x=120, y=400) "left button" leftButton = Button(self, text="增加到自己的名字", command=self.leftClick) leftButton.place(x=20,y=180) "left add all button" leftAddAllBtn = Button(self, text="添加剩下的名字到自己", command=self.leftAddAllClick) leftAddAllBtn.place(x=20,y=210) "right button" rightButton = Button(self, text="增加到对方的名字", command=self.rightClick) rightButton.place(x = 150, y = 180) "right add all button" rightAddAllBtn = Button(self, text="添加剩下的名字到对方", command=self.rightAddAllClick) rightAddAllBtn.place(x=150,y=210) "move to right button" left2RightBtn = Button(self, text="移动到自己", command=self.move2Left) left2RightBtn.place(x=150,y=380) "move to left button" left2RightBtn = Button(self, text="移动到对方", command=self.move2Right) left2RightBtn.place(x=20,y=380) "finish button" self.finishBtn = Button(self, text="选择完毕", command = self.finishClick) self.finishBtn.place(x = 120 , y = 420)
def Graficar(BOLIVIA_var, ECUADOR_var, FRANCIA_var,JAPAN_var, SRILANKA_var, USA_var): ################ Crear Ventana ############### ventana = Tk() ventana.geometry("1357x628+0+0") ventana.title("Pantalla Principal") image = Image.open('mapas.png') photo = ImageTk.PhotoImage(image) label = Label(ventana,image=photo) label.image = photo label.pack() label.place(x=0, y=0, relwidth=1, relheight=1) button = Button(ventana, text="Exit", command=ventana.destroy) button.pack() button.place(width=50,x=10,y=10) USA_Label = Frame(ventana, borderwidth=2, relief=GROOVE) Label(USA_Label, text='USA', width=10).pack() USA_Label.place(width=50,x=20,y=150) USA_N = Frame(ventana, borderwidth=2, relief=GROOVE) Label(USA_N, text=USA_var, width=10).pack() USA_N.place(width=50,x=20,y=180) BOLIVIA_Label = Frame(ventana, borderwidth=2, relief=GROOVE) Label(BOLIVIA_Label, text='Bolivia', width=10).pack() BOLIVIA_Label.place(width=50,x=200,y=435) BOLIVIA_N = Frame(ventana, borderwidth=2, relief=GROOVE) Label(BOLIVIA_N, text=BOLIVIA_var, width=10).pack() BOLIVIA_N.place(width=50,x=200,y=465) ECUADOR_Label = Frame(ventana, borderwidth=2, relief=GROOVE) Label(ECUADOR_Label, text='Ecuador', width=10).pack() ECUADOR_Label.place(width=50,x=160,y=355) ECUADOR_N = Frame(ventana, borderwidth=2, relief=GROOVE) Label(ECUADOR_N, text=ECUADOR_var, width=10).pack() ECUADOR_N.place(width=50,x=160,y=385) JAPAN_Label = Frame(ventana, borderwidth=2, relief=GROOVE) Label(JAPAN_Label, text='Japan', width=10).pack() JAPAN_Label.place(width=50,x=1120,y=150) JAPAN_N = Frame(ventana, borderwidth=2, relief=GROOVE) Label(JAPAN_N, text=JAPAN_var, width=10).pack() JAPAN_N.place(width=50,x=1120,y=180) FRANCIA_Label = Frame(ventana, borderwidth=2, relief=GROOVE) Label(FRANCIA_Label, text='Francia', width=10).pack() FRANCIA_Label.place(width=50,x=470,y=140) FRANCIA_N = Frame(ventana, borderwidth=2, relief=GROOVE) Label(FRANCIA_N, text=FRANCIA_var, width=10).pack() FRANCIA_N.place(width=50,x=470,y=170) SRILANKA_Label = Frame(ventana, borderwidth=2, relief=GROOVE) Label(SRILANKA_Label, text='SriLanka', width=10).pack() SRILANKA_Label.place(width=50,x=870,y=340) SRILANKA_N = Frame(ventana, borderwidth=2, relief=GROOVE) Label(SRILANKA_N, text=SRILANKA_var, width=10).pack() SRILANKA_N.place(width=50,x=870,y=370) ventana.mainloop()