def key_event(event): canmovelist = [] derection_code = 9 global list_data if event.keycode == 37: derection_code = left if event.keycode == 39: derection_code = right if event.keycode == 38: derection_code = up if event.keycode == 40: derection_code = down for i in range(4): if CanMove(derection_code, i): Move(derection_code, i) canmovelist.append(i) if len(canmovelist) == 0: return list_data[derection_index[derection_code][canmovelist[random.randint(0,len(canmovelist)-1)]][3]] = 2 Refresh() for i_derection in range(4): for i_index in range(4): if CanMove(i_derection, i_index): return tkMessageBox.showinfo('Game Over','Your score is %u.\n' % sum(list_data)) list_data=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] Refresh()
def create_prom(self, lieu, date, h_deb, h_fin, T_descr, fen_prom): """ Actions effectuées : 1) check des données 2) On vérifie si le fichier data existe""" ##On récupère les différentes variables Lieu = lieu.get() Date = date.get() H_deb = h_deb.get() H_fin = h_fin.get() descr = T_descr.get('1.0', END+'-1c') #On vérifie ce qui a été rentré test_prom = check_entries_prom(Lieu, Date, H_deb, H_fin) #On enregistre seulement si test_prom = True if test_prom == True: #On met une majuscule au lieu (seulement s'il existe => après le test) prem_lettre = Lieu[0].upper() Lieu = prem_lettre + Lieu[1:] #on enregistre save_prom(Lieu, Date, H_deb, H_fin, descr) tkMessageBox.showinfo("Info", "Bravo,\n la promenade du {} au {} est enregistrée :)".format(Date, Lieu)) fen_prom.destroy() #On ré-affiche la fenêtre principale fen_create = Tk() fen_create.title("Choisir une action") interface_create = InterfaceCreate(fen_create) interface_create.mainloop()
def checkFiles(self): check_files=[] i=0 for movfolder in self.movDirectory: print movfolder for root, dirs, files in os.walk(movfolder): for file in files: i=i+1 self.updateProgressString(i) if(self.isMovFile(file)): fileURL = os.path.join(root, file) if (not os.path.islink(fileURL)): check_files.append(fileURL) historyMovFile = self.getHistoryMovFileName() if(check_files==self.MOV_FILES): checkResult = "correct" else: checkResult = "incorrect" outfile = open(historyMovFile,"wb") pickle.dump(check_files, outfile,2) outfile.close() if os.name == "nt": print checkResult else: tkMessageBox.showinfo( "Movie DB Verify", checkResult+' , Movie DB Verify Finish.')
def ExportSecretaris(): # Obrim el fitxer de text # Així es com estava abans quan el ficava a /exportacions ----> f=open("exportacions/secretaris-ajuntaments.txt","w") fitxer = tkFileDialog.asksaveasfilename( defaultextension="*.txt|*.*", filetypes=[("Fitxer TXT", "*.txt"), ("Tots els fitxers", "*.*")] ) f = open(fitxer, "w") # Generamos el select para obtener los datos de la ficha db = MySQLdb.connect(host=SERVIDOR, user=USUARI, port=4406, passwd=CONTRASENYA, db=BASE_DE_DADES) cursor = db.cursor() sql = "SELECT MUNICIPIO, SECRETARIO FROM ayuntamientos ORDER BY MUNICIPIO" cursor.execute(sql) resultado = cursor.fetchall() for i in resultado: f.write(str(i[0]) + " - " + str(i[1]) + "\n") # tanquem el fitxer f.close() if len(fitxer) > 0: tkMessageBox.showinfo("TXT Generat", "S'ha generat la fitxa amb els secretaris a " + fitxer) else: return
def __getCycleRootsManually(cycleNodes): """ Allows the user to break cycles by clicking no nodes to choose tree roots Returns the final rootNodes (ie: including those that break cycles) """ if(len(cycleNodes) > 0): showinfo('TreeLikeLayout: Cycle/s Detected', 'Manual cycle breaking mode in effect\n\n' + 'Cyclic nodes will be highlighted\n\n' + 'Please break the cycle/s by clicking on the node/s' + ' you want as tree root/s') rootNodes = [] while(len(cycleNodes) > 0): index = cycleNodes[0].chooseNode(cycleNodes) if(index != None): chosenRootNode = cycleNodes[index] chosenRootNode._treeVisit = True rootNodes.append(chosenRootNode) __markChildrenNodesBFS(chosenRootNode, []) # Cleanup: leave only nodes that still form a cycle temp = cycleNodes[:] for node in temp: if(node._treeVisit == True): cycleNodes.remove(node) return rootNodes
def _print_help(self, eventobj): """ Opens up a file dialog of the help button """ import tkMessageBox tkMessageBox.showinfo("Peak Identification Information", "The options in this section deal with calculating " "the water density and determining the density " "peak locations. cpptraj is used for this step")
def Suma(): n1=float(caja1.get()) n2=float(caja2.get()) suma=n1+n2 tkMessageBox.showinfo("Mensaje","El resultado es: %.2f"%suma) caja1.delete(0,20) caja2.delete(0,20)
def help_menu(): """ Shows the help message box popup of the GUI """ tkMessageBox.showinfo("Help", "1. Click on any of the buttons to sort\ \n2. Only the files on your Desktop are sorted\ \n3. The files are sorted based only on their extension, eg '.mp3', '.pdf', etc")
def drawError(self,errormsg=""): """ Draw a error message dialog @type errormsg: string @param errormsg: the messag to display """ messagebox.showinfo("Error",errormsg) return
def collect_edited_data(self): self.field_edit_win.config(cursor="watch") self.field_edit_win.update() new_vals = [] for entries in self.edited_entries: new_vals.append(entries.get()) # Remove the first item (corresponding to the title row in displayed table new_vals.pop(0) key_nb = 0 for key in self.field_dict.keys(): if "Value" in self.field_dict[key]: if self.field_dict[key]["Value"] == new_vals[key_nb]: self.field_dict[key]["Update"] = False else: self.field_dict[key]["Update"] = True self.field_dict[key]["Value"] = new_vals[key_nb] else: self.field_dict[key]["Update"] = False key_nb += 1 (anonymize_dcm, original_dcm) = methods.Dicom_zapping(self.dirname, self.field_dict) self.field_edit_win.destroy() if os.path.exists(anonymize_dcm) != [] and os.path.exists(original_dcm) != []: tkMessageBox.showinfo("Message", "Congrats! Your have successfully anonymized your files!") else: tkMessageBox.showinfo("Message", "There was an error when processing files")
def about_message(): """ Shows the about message box popup of the GUI """ tkMessageBox.showinfo("About", "Welcome to the Automatic Desktop Sorting Application\ \nBy EasyTech\nContact @ [email protected]\ \nVersion 1.0")
def mail(self): if(self.guideFile==""): tkMessageBox.showinfo("Error", "Please select guidelines file") else: self.msg = MIMEMultipart() self.msg['Subject'] = 'Important: Exam Guiedlines' self.msg['From'] = '*****@*****.**' #msg['Reply-to'] = 'otroemail@dominio' self.msg['To'] = '*****@*****.**' # That is what u see if dont have an email reader: self.msg.preamble = 'Multipart massage.\n' # This is the textual part: self.part = MIMEText("Please find attched guidelines for exams.") self.msg.attach(self.part) # This is the binary part(The Attachment): self.part = MIMEApplication(open(self.guideFile,'rb').read()) self.part.add_header('Content-Disposition', 'attachment', filename=self.guideFile) self.msg.attach(self.part) # Create an instance in SMTP server self.server = SMTP("smtp.gmail.com",587) # Start the server: self.server.ehlo() self.server.starttls() self.server.login("*****@*****.**", "exammanage") # Send the email self.server.sendmail(self.msg['From'], self.msg['To'], self.msg.as_string()) tkMessageBox.showinfo("Success", "Guidelines have been successfully mailed.") self.dest1()
def file_save1(event=None): try: savetex() except Cancel: pass tkMessageBox.showinfo(title="saving tex file", message ="saved!!! :D") return "break"
def __drawRiversHandler(): if self.layer2==0: shpFile = tkFileDialog.askopenfilename(parent=self.root, initialdir=".", title='Please select a shpfile', defaultextension='.shp', filetypes=(("shp file", "*.shp"),("all files", "*.*"))) self.addLayer(shpFile,"blue") self.layer2 = 1 else: tkMessageBox.showinfo("NOTE", "Please clean the canvas if you want to reload layer 2")
def onShow(self): if os.path.exists(reminderFilePath): self.createWindow() self.clear() else: print("The file doesn't exist!") box.showinfo("Information", "The file either doesnt exist or can't be found, plese enter a new reminder to create a file.")
def onMed(self): self.I2 = self.Ilast if self.Ilast.ndim == 3 : tkMessageBox.showinfo("Message", "This operation is slow ! \n Image will be converted to Grayscale.") self.onGryscl() self.I2 = self.Ilast self.onMedKsize(3)
def main(): Tk().withdraw() tkMessageBox.showinfo( "Image", "Select an Image") usrImag = askopenfilename() thres=Threshold(Image.open(str(usrImag))) value =int(raw_input("Give me the threshold value")) thres.threshold(value)
def addCP(self,origin=(0,0,0),normal=(1,1,1)): tkMessageBox.showinfo("Instructions:", "The rendering window will appear. Maneuver the plane into the position you want it in and press the q key.") self.planewidget = vtkImplicitPlaneWidget() self.planewidget.SetInput(self.reader.GetOutput()) self.planewidget.SetInteractor(self.renWinIn) self.planewidget.SetPlaceFactor(1) self.planewidget.PlaceWidget() self.planewidget.SetOrigin(origin) self.planewidget.SetNormal(normal) self.planewidget.AddObserver("InteractionEvent",cpinteractioncallback) global plane cutter = vtkCutter() self.planewidget.On() self.planewidget.GetPlane(plane) self.planewidget.DrawPlaneOff() self.planewidget.OutlineTranslationOff() cutter.SetCutFunction(plane) cutter.SetInputConnection(self.reader.GetOutputPort()) cutterMapper = vtkPolyDataMapper() cutterMapper.SetInputConnection(cutter.GetOutputPort()) cutterActor = vtkActor() cutterActor.SetMapper(cutterMapper) self.ren.AddActor(cutterActor) self.renWinIn.Initialize() self.renWinIn.Start() origin = self.planewidget.GetOrigin() normal = self.planewidget.GetNormal() self.planewidget.Off() self.ren.RemoveActor(cutterActor) cp = cuttingplane(self.reader.GetOutputPort(),origin,normal) self.cuttingplanes.append(cp) self.cplist.insert(Tkinter.END,str(cp)) self.ren.AddActor(cp.actor) self.renWin.Render()
def showit(pEvent): 'View expansion of selected command' lPrompt = pEvent.widget.cget("text") lCommand = mCmds[lPrompt] lCommand = Expand(lCommand, mFileName, lPrompt) tkMessageBox.showinfo('Expanded Command:', lPrompt + " = " + lCommand)
def handleCmd1(self): str = ('Left Mouse Button: Translate\n') str += ('Middle Mouse Button: Rotate\n') str += ('Right Mouse Button: Zoom\n') #str += ('Ctrl + H: Show/Hide Axes \n') tkMessageBox.showinfo(title='Controls', message=str)
def cmdSave( self): filename = self.filename.get() if path.isfile( filename): if not tkMessageBox.askokcancel('Save', 'File %s already exist!\n Overwrite?'% filename): return base, ext = path.splitext( filename) if ext == '': ext = '.c' if ext != '.c': tkMessageBox.showinfo( 'Error', 'Only .c files can be generated!', icon='warning') return filename = base + ext try: with open( filename, "wt") as f: f.write( '/*\n') f.write( ' * OLED display image \n') f.write( ' * %s x %s \n' % ( self.wx, self.wy)) f.write( ' */ \n') f.write( '#include "mcc_generated_files/mcc.h"\n\n') f.write( 'const uint8_t %s[]={ \n' % base) for x in xrange( 0, self.wx * self.wy/8, 16): for k in xrange( 16): f.write( '0x%02x, '% self.array[ x + k]) f.write( '\n') f.write( '};\n') self.modified = False except IOError: print 'Cannot write file:', filename
def runMission( self, mission_spec, mission_record_spec, action_space ): '''Sets a mission running. Parameters: mission_spec : MissionSpec instance, specifying the mission. mission_record_spec : MissionRecordSpec instance, specifying what should be recorded. action_space : string, either 'continuous' or 'discrete' that says which commands to generate. ''' sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0) # flush print output immediately self.world_state = None self.action_space = action_space total_reward = 0 if mission_spec.isVideoRequested(0): self.canvas.config( width=mission_spec.getVideoWidth(0), height=mission_spec.getVideoHeight(0) ) try: self.agent_host.startMission( mission_spec, mission_record_spec ) except RuntimeError as e: tkMessageBox.showerror("Error","Error starting mission: "+str(e)) return print "Waiting for the mission to start", self.world_state = self.agent_host.peekWorldState() while not self.world_state.is_mission_running: sys.stdout.write(".") time.sleep(0.1) self.world_state = self.agent_host.peekWorldState() for error in self.world_state.errors: print "Error:",error.text print if mission_spec.isVideoRequested(0) and action_space == 'continuous': self.canvas.config(cursor='none') # hide the mouse cursor while over the canvas self.canvas.event_generate('<Motion>', warp=True, x=self.canvas.winfo_width()/2, y=self.canvas.winfo_height()/2) # put cursor at center self.root.after(50, self.update) self.canvas.focus_set() while self.world_state.is_mission_running: self.world_state = self.agent_host.getWorldState() if self.world_state.number_of_observations_since_last_state > 0: self.observation.config(text = self.world_state.observations[0].text ) if mission_spec.isVideoRequested(0) and self.world_state.number_of_video_frames_since_last_state > 0: frame = self.world_state.video_frames[-1] image = Image.frombytes('RGB', (frame.width,frame.height), str(frame.pixels) ) photo = ImageTk.PhotoImage(image) self.canvas.delete("all") self.canvas.create_image(frame.width/2, frame.height/2, image=photo) self.canvas.create_line( frame.width/2 - 5, frame.height/2, frame.width/2 + 6, frame.height/2, fill='white' ) self.canvas.create_line( frame.width/2, frame.height/2 - 5, frame.width/2, frame.height/2 + 6, fill='white' ) self.root.update() for reward in self.world_state.rewards: total_reward += reward.getValue() self.reward.config(text = str(total_reward) ) time.sleep(0.01) if mission_spec.isVideoRequested(0) and action_space == 'continuous': self.canvas.config(cursor='arrow') # restore the mouse cursor print 'Mission stopped' if not self.agent_host.receivedArgument("test"): tkMessageBox.showinfo("Ended","Mission has ended. Total reward: " + str(total_reward) ) self.root.destroy()
def send(self): import httplib, urllib global errors email = self.email.get() desc = self.text.get('1.0', END).strip() # Send information self.config(cursor="watch") self.text.config(cursor="watch") self.update_idletasks() params = urllib.urlencode({"email":email, "desc":desc}) headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/plain"} conn = httplib.HTTPConnection("www.fluka.org:80") try: conn.request("POST", "/flair/send_email_bcnc.php", params, headers) response = conn.getresponse() except: tkMessageBox.showwarning(_("Error sending report"), _("There was a problem connecting to the web site"), parent=self) else: if response.status == 200: tkMessageBox.showinfo(_("Report successfully send"), _("Report was successfully uploaded to web site"), parent=self) del errors[:] else: tkMessageBox.showwarning(_("Error sending report"), _("There was an error sending the report\nCode=%d %s")%\ (response.status, response.reason), parent=self) conn.close() self.config(cursor="") self.cancel()
def __plist2Excel__(self): if self.outEntry.get() == "" or self.plistEntry.get() == "": tkMessageBox.showerror('Result',"input res or plist res is requested!") return info = self.scanPlist.scanPlistDir(self.outEntry.get(),self.plistEntry.get()) tkMessageBox.showinfo('Result',info)
def on_run(self): target_dir = self.target_dir.get().decode(sys.getfilesystemencoding()) if len(target_dir) == 0: tkMessageBox.showinfo(title="No target directory", message="No target directory selected.") return input_paths = self.input_dirs.get(0, Tkinter.END) input_paths = [ip.decode(sys.getfilesystemencoding()) for ip in input_paths] no_length_patch = bool(self.skip_ogg_patch.get()) # Disable GUI self.disable() logger = ThreadQueueLogger() # To avoid locking the GUI, run execution in another thread. thread = threading.Thread( target=r21buddy.run, args=(target_dir, input_paths), kwargs={"length_patch": (not no_length_patch), "verbose": True, "ext_logger": logger}) thread.start() # Initiate a polling function which will update until the # thread finishes. self._on_run(thread, logger)
def dex(): try: t1=t1_text.get() t2=t2_text.get() t3=t3_text.get() t4=t4_text.get() a1=float(t1) a2=float(t2) a3=float(t3) a4=float(t4) # num=a1+(float(a2)-1)*a3 # sum=(a1+num)/2*a2 sum=(a2-a1)*a3-10-a2*a3*a4/10000 string=str("您目前的盈亏为 %f" % sum) print "您目前的盈亏为 %f" % sum tkMessageBox.showinfo(title='结果',message=string) try: save=MySQLdb.connect(host='rm-bp12a3q2p8q14i0yk.mysql.rds.aliyuncs.com',user='******',passwd='Mysqlweb20',db='re5sh0bjj8') #save.query("grant all on *.* to 'root'@'10.2.48.100' identified by 'mysql'") except Exception,e: print e sys.exit() cursor=save.cursor() action="insert into stock(b_price,s_price,num,rate,profit) values (%f,%f,%f,%f,%f)" % (a1,a2,a3,a4,sum) try: cursor.execute(action) except Exception,e: print e
def __excel2Plist__(self): if self.inputentry.get() == "" or self.outEntry.get() =="": tkMessageBox.showerror('Result',"input res or output res is requested!") return info = self.scanExcel.sacnExcelDir(self.inputentry.get(),self.outEntry.get()) tkMessageBox.showinfo('Result',info)
def backupdata(self): print "You requested the backup routine" self.option_add('*font', 'Helvetica -14') self.option_add("*Dialog.msg.wrapLength", "10i") # Check to see if the directories were set for something else if self.varSource.get() == "SourceDir" : tkMessageBox.showwarning("Warning!", "First set the source directory!") elif self.varDestination.get() == "DestinationDir" : tkMessageBox.showwarning("Warning!", "Also remember to set the destination directory!") # OK good to go else: result = tkMessageBox.askyesno("Ready to backup!!", "You will now synchronize your folder\n\n%s\n\ninto your backup folder:\n\n%s" %(os.path.basename(self.varSource.get()),self.varDestination.get())) if result : print "You have accepted to backup" self.DiskUsage = Tkinter.StringVar() DiskUsage = os.popen('du -hs "%s"'%(self.varSource.get())).read() tkMessageBox.showinfo("First notification", "Your job size is :\n" +DiskUsage+ "\n this could take a while, please be patient.") var_rsync_command = subprocess.Popen(["rsync", "-ahv", self.varSource.get(), self.varDestination.get()], stdout=subprocess.PIPE) # Trying to make the textbox update all the time for line in iter(var_rsync_command.stdout.readline,''): self.var_textbox.insert(Tkinter.END, line) self.var_textbox.update() self.var_textbox.yview(Tkinter.END) # tkMessageBox.showinfo("Backup complete","The rsync job has finished") else: print "You declined to backup your data"
def genInitialInfo(): db = 'initialphoto.sqlite' sql_connection = sql.Connection(db) # This is the path to the database. If it doesn't exist, it will be created, though, of course, without the require tables cursor = sql.Cursor(sql_connection) mainDB = openFile('Locate Main Database File', 'Spatialite SQL Database', 'sqlite') mainImages = openFolder('Find Main Images Library Folder') icons = openFolder('Find Icons Folder') srid = tkSimpleDialog.askstring('Spatial Reference System', 'Please provide a spatial reference ID (SRID).\nRefer to spatialreference.org for more instructions') sql_connection = sql.Connection(db) # This is the path to the database. If it doesn't exist, it will be created, though, of course, without the require tables cursor = sql.Cursor(sql_connection) try: createsql = "CREATE TABLE INITIATION ('mainImages' text,'maindb' text,'icons' text, 'srid' text)" cursor.execute(createsql) except: pass insertsql = "INSERT INTO INITIATION VALUES ('{0}','{1}','{2}','{3}')".format(mainImages, mainDB,icons, srid) cursor.execute(insertsql) sql_connection.commit() tkMessageBox.showinfo('Database Initialized', 'Your settings have been recorded') standards = mainImages, mainDB, icons,srid return standards
def deleteLastCommandInQueue(self): if self.command_line_num > 1: self.deleteLastCommandFromTextField() self.commandArray.pop() else: tkMessageBox.showinfo("Error", "Number of instructions is already 0, cannot delete") return
import Tkinter import tkMessageBox window = Tkinter.Tk() window.wm_withdraw() tkMessageBox.showinfo(title="Aviso", message="Exercicio ignorado, feito em sala de aula!") tkMessageBox.showinfo(title="Aviso", message="Quem tiver o fonte, favor editar este arquivo!")
def alert(self, title="Info", msg=""): msb = tkMessageBox.showinfo(title, msg)
def about(self, event=None): tkMessageBox.showinfo("About","Tkinter GUI Application\n Development Hotshot")
def __init__(self, root, options): """ web2pyDialog constructor """ import Tkinter import tkMessageBox bg_color = 'white' root.withdraw() self.root = Tkinter.Toplevel(root, bg=bg_color) self.root.resizable(0, 0) self.root.title(ProgramName) self.options = options self.scheduler_processes = {} self.menu = Tkinter.Menu(self.root) servermenu = Tkinter.Menu(self.menu, tearoff=0) httplog = os.path.join(self.options.folder, self.options.log_filename) iconphoto = os.path.join('extras', 'icons', 'web2py.gif') if os.path.exists(iconphoto): img = Tkinter.PhotoImage(file=iconphoto) self.root.tk.call('wm', 'iconphoto', self.root._w, img) # Building the Menu item = lambda: start_browser(httplog) servermenu.add_command(label='View httpserver.log', command=item) servermenu.add_command(label='Quit (pid:%i)' % os.getpid(), command=self.quit) self.menu.add_cascade(label='Server', menu=servermenu) self.pagesmenu = Tkinter.Menu(self.menu, tearoff=0) self.menu.add_cascade(label='Pages', menu=self.pagesmenu) #scheduler menu self.schedmenu = Tkinter.Menu(self.menu, tearoff=0) self.menu.add_cascade(label='Scheduler', menu=self.schedmenu) #start and register schedulers from options self.update_schedulers(start=True) helpmenu = Tkinter.Menu(self.menu, tearoff=0) # Home Page item = lambda: start_browser('http://www.web2py.com/') helpmenu.add_command(label='Home Page', command=item) # About item = lambda: tkMessageBox.showinfo('About web2py', ProgramInfo) helpmenu.add_command(label='About', command=item) self.menu.add_cascade(label='Info', menu=helpmenu) self.root.config(menu=self.menu) if options.taskbar: self.root.protocol('WM_DELETE_WINDOW', lambda: self.quit(True)) else: self.root.protocol('WM_DELETE_WINDOW', self.quit) sticky = Tkinter.NW # Prepare the logo area self.logoarea = Tkinter.Canvas(self.root, background=bg_color, width=300, height=300) self.logoarea.grid(row=0, column=0, columnspan=4, sticky=sticky) self.logoarea.after(1000, self.update_canvas) logo = os.path.join('extras', 'icons', 'splashlogo.gif') if os.path.exists(logo): img = Tkinter.PhotoImage(file=logo) pnl = Tkinter.Label(self.logoarea, image=img, background=bg_color, bd=0) pnl.pack(side='top', fill='both', expand='yes') # Prevent garbage collection of img pnl.image = img # Prepare the banner area self.bannerarea = Tkinter.Canvas(self.root, bg=bg_color, width=300, height=300) self.bannerarea.grid(row=1, column=1, columnspan=2, sticky=sticky) Tkinter.Label(self.bannerarea, anchor=Tkinter.N, text=str(ProgramVersion + "\n" + ProgramAuthor), font=('Helvetica', 11), justify=Tkinter.CENTER, foreground='#195866', background=bg_color, height=3).pack(side='top', fill='both', expand='yes') self.bannerarea.after(1000, self.update_canvas) # IP Tkinter.Label(self.root, text='Server IP:', bg=bg_color, justify=Tkinter.RIGHT).grid(row=4, column=1, sticky=sticky) self.ips = {} self.selected_ip = Tkinter.StringVar() row = 4 ips = [('127.0.0.1', 'Local (IPv4)')] + \ ([('::1', 'Local (IPv6)')] if socket.has_ipv6 else []) + \ [(ip, 'Public') for ip in options.ips] + \ [('0.0.0.0', 'Public')] for ip, legend in ips: self.ips[ip] = Tkinter.Radiobutton( self.root, bg=bg_color, highlightthickness=0, selectcolor='light grey', width=30, anchor=Tkinter.W, text='%s (%s)' % (legend, ip), justify=Tkinter.LEFT, variable=self.selected_ip, value=ip) self.ips[ip].grid(row=row, column=2, sticky=sticky) if row == 4: self.ips[ip].select() row += 1 shift = row # Port Tkinter.Label(self.root, text='Server Port:', bg=bg_color, justify=Tkinter.RIGHT).grid(row=shift, column=1, pady=10, sticky=sticky) self.port_number = Tkinter.Entry(self.root) self.port_number.insert(Tkinter.END, self.options.port) self.port_number.grid(row=shift, column=2, sticky=sticky, pady=10) # Password Tkinter.Label(self.root, text='Choose Password:'******'*') self.password.bind('<Return>', lambda e: self.start()) self.password.focus_force() self.password.grid(row=shift + 1, column=2, sticky=sticky) # Prepare the canvas self.canvas = Tkinter.Canvas(self.root, width=400, height=100, bg='black') self.canvas.grid(row=shift + 2, column=1, columnspan=2, pady=5, sticky=sticky) self.canvas.after(1000, self.update_canvas) # Prepare the frame frame = Tkinter.Frame(self.root) frame.grid(row=shift + 3, column=1, columnspan=2, pady=5, sticky=sticky) # Start button self.button_start = Tkinter.Button(frame, text='start server', command=self.start) self.button_start.grid(row=0, column=0, sticky=sticky) # Stop button self.button_stop = Tkinter.Button(frame, text='stop server', command=self.stop) self.button_stop.grid(row=0, column=1, sticky=sticky) self.button_stop.configure(state='disabled') if options.taskbar: import gluon.contrib.taskbar_widget self.tb = gluon.contrib.taskbar_widget.TaskBarIcon() self.checkTaskBar() if options.password != '<ask>': self.password.insert(0, options.password) self.start() self.root.withdraw() else: self.tb = None
def helloCallBack(): tkMessageBox.showinfo("Hello Python", "Hello World")
def add(): global SIZE, e, MU, clicked # if clicked==0: # btnText.set("Exit") # clicked=1 # else: # quit() tkMessageBox.showinfo( "Alert", "Please Place the appropriate adjacency matrix file in the same folder as this file and name it net_adj.dat" ) #print "Enter The No. of Nodes" SIZE = int(size.get()) #print "Enter The Value of e" e = float(ep.get()) #print "Enter The Value of Mu" MU = float(mu.get()) while SIZE < 0 or SIZE > 1000: tkMessageBox.showinfo( "Invalid Input!", "Invalid number of Nodes(Out of bound 1-1000). Please Enter again!" ) clicked = 0 return while e > 1 or e < 0: tkMessageBox.showinfo( "Invalid Input!", "Invalid value of e(0 to 1). Please Enter again!") clicked = 0 return while MU < 0: tkMessageBox.showinfo( "Invalid Input!", "Invalid value of Mu (Mu > 0). Please Enter again!") clicked = 0 return for k in range(1, SIZE + 2): parent.append(0) print "Processing....." #PLOTTING CLASS DEFINED class plotCluster: fig = plt.figure() ax = plt.axes(xlim=(0, 1000), ylim=(0, 1000)) line = ax.plot(0, 0, lw=2, picker=True) # initialization function: plot the background of each frame def init(): line.set_data([], []) self.ax.set_autoscaley_on(True) return line # animation function. This is called sequentially def animate(i): #fig=plt.figure() global obj1, SIZE, vis, parent, ts, occur, clusterInfo obj1.initi() obj1.fill() obj1.analyze() obj1.dsu() plt.clf() ax = plt.axes(xlim=(0, SIZE + 1), ylim=(-1, SIZE + 1)) line = ax.plot(0, 0, lw=2, picker=True) # for k in range (0,20): # self.parent.append(randint(0,5)) pos = 1 ctr = 1 l = 1 marked = [] for p in range(0, SIZE + 1): marked.append(0) #NEW PLOT METHOD tempx = [] tempy = [] for p in range(1, SIZE + 1): for node in range(1, SIZE + 1): if parent[p] == parent[node] and marked[ node] == 0 and parent[p] != 0 and node != p: tempx.append(p) tempy.append(node) # tempy.append(p) # tempx.append(node) #marked[node]=1 #print tempx #print tempy #print parent df = 1 for k in range(1, SIZE + 1): group = [] plotx = [] ploty = [] for j in range(1, SIZE + 1): if parent[j] == k: group.append(j) gsize = len(group) if gsize > 1: #print group gsize = gsize for pl in range(0, gsize): for ql in range(0, gsize): plotx.append(df + pl) ploty.append(df + ql) clusterInfo[df + pl][df + ql] = str(group) df = df + gsize plt.plot(plotx, ploty, '.', color="blue", picker=2) plt.plot(networkx, networky, 'o', mfc='None') #print ploty[0] # #plt.plot(tempx,tempy,'.',color="black") totalpts = 0 #FIRST ITERATION PLOT METHOD # parent.sort() # while l<=SIZE: # px=[] # py=[] # if(parent[l]==parent[l-1]): # while l<SIZE and parent[l]==parent[l-1] and parent[l]!=0: # ctr=ctr+1 # #print a[l] # l=l+1 # apos=0 # totalpts=totalpts+ctr # for j in range (pos,pos+ctr): # for k in range (pos,pos+ctr): # px.append(j) # py.append(k) # plt.plot(px,py,'.',color="blue") # pos=pos+ctr # l=l+1 # ctr=1 print a[1] print a[30] plt.draw() if (obj1.counter == 100): obj1.counter = 100 #quit() obj1.counter = obj1.counter + 100 # for var in range(1,100): # print parent[var] del ts[:] ts = ["" for _ in range(0, 1001)] del times_occur[:] #times_occur=[] for _ in range(0, TIME + 1): times_occur.append([]) # for i in range(TIME+1): # times_occur.append(0) occur = [] for i in range(0, 101): occur.append([]) for j in range(0, 1001): occur[i].append(0) for i in range(1, SIZE + 1): a[i][0] = a[i][TIME] print obj1.counter return line def onpick1(event): thisline = event.artist global clusterInfo xdata = (thisline.get_xdata()) ydata = (thisline.get_ydata()) ind = event.ind tkMessageBox.showinfo("Cluster", clusterInfo[xdata[ind]][ydata[ind]]) print clusterInfo[xdata[ind]][ydata[ind]] anim = animation.FuncAnimation(fig, animate, frames=200, interval=5000, blit=True) fig.canvas.mpl_connect('pick_event', onpick1) plt.show()
def genCode(self): """ Generates class diagram code By Denis Dube """ # Save first, so if anything goes wrong, we got a fallback position hehehe status = self.statusbar.getState(self.statusbar.MODEL)[0] if (status == self.statusbar.MODIFIED): self.save() #=============================================================================== # Pathfinding initilization #=============================================================================== # Get the ASGroot for this formalism ASGroot = self.ASGroot.getASGbyName(Magic().ASGname) # Make sure we don't generate a formalism with no name... if (ASGroot and hasattr(ASGroot, 'name')): if (ASGroot.name.getValue() == ''): modelPathAndFile = self.statusbar.getState( self.statusbar.MODEL)[1][0] modelName = os.path.split(modelPathAndFile)[1].split('.')[0] modelName = modelName.split('_')[0] ASGroot.name.setValue(modelName) tkMessageBox.showerror( "Code Generator Error", "Please give your formalism a name, such as: " + modelName + "\nAnd then try to generate again" + "\n\nNOTE: A name was automatically generated, so just" + " press OK in the next dialog if you like it.", parent=self) self.modelAttributes(ASGroot) return # In cardConstObjects, we are storing the objects with cardinality constraints cardConstObjects = [] if ASGroot.keyword_: if self.console: self.console.appendText('Generating code for model ' + ASGroot.keyword_.toString()) else: if self.console: self.console.appendText('Generating code for model.') # Use directory of class diagram for generating code modelPathAndFile = self.statusbar.getState(self.statusbar.MODEL)[1][0] modelPath = os.path.split(modelPathAndFile)[0] oldCodeGenDir = self.codeGenDir self.codeGenDir = os.path.normpath(modelPath) #=============================================================================== # Generate code #=============================================================================== print 'Generating code to: ', self.codeGenDir errors = [] # for each node type for nodeType in [Magic().associationClassName, Magic().classClassName]: # for each object of any type for UMLobject in ASGroot.listNodes[nodeType]: # Generate code for this particular entity (Graphical icon code) error = genCodeFor(self, UMLobject) if (error): errors.append(error) if (errors): title = 'Entity Generation Warning' msg = '' for error in errors: msg += '--> ' + error + '\n' msg += '\nNOTE: Instantiating entities without icons will cause an exception' print '\n', title, '\n', msg, '\n' tkMessageBox.showwarning(title, msg) # see first if we have generative attributes... self.genASGCode(cardConstObjects, ASGroot) # generate code for the ASG node propagateCardinalities(self) # Inherit edges self.genButtons(ASGroot) # generate the file for the syntax actions # now generate the file with the GUI model... self.genButtonsModel(ASGroot) #=============================================================================== # Cleanup #=============================================================================== # Restore path self.codeGenDir = oldCodeGenDir # Clear the screen, and then reload the old diagram # WHY? Because this generator has totally messed up the diagram in order # to do the inheritance stuff (it's safer this way, trust Denis) self.clearModel(showDialog=False) #for nodeType in ASGroot.nodeTypes: # print nodeType, ASGroot.listNodes[nodeType] # Re-open the model self.open(fileName=modelPathAndFile) tkMessageBox.showinfo( "Code generated", "Code generated in:\n " + modelPath + "\n\nPlease restart AToM3 before trying to load the newly generated " + "formalism\n\nHINT: starting another instance of AToM3 works too")
def showMessageBox(title, msg): paused = data.isPaused data.isPaused = True tkMessageBox.showinfo(title, msg, parent=data.root) data.isPaused = paused
from Tkinter import Tk from tkFileDialog import askopenfilename import tkMessageBox Tk().withdraw( ) # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename( ) # show an "Open" dialog box and return the path to the selected file print(filename) tkMessageBox.showinfo(title="Greetings", message="Hello World!")
def handle(preamble, hotels): window = Tkinter.Tk() window.wm_withdraw() tkMessageBox.showinfo(title = 'Gencon Hotel Search', message = "%s\n\n%s" % (preamble, '\n'.join("%s: %s: %s" % (hotel['distance'], hotel['name'], hotel['room']) for hotel in hotels))) window.destroy()
def choose_color(self): rgb, _ = show_colordialog() if (not rgb): pass else: showinfo('提示', 'color:(%s,%s,%s)' % rgb)
def onInfo(self): mbox.showinfo("Information", "Download completed")
for i in range(30): init2 = time.time() data[i,:,:] = snapImages(500) # This code account for the variable delay in recording an imaage. t = time.time() - init2 if t <= delaytime: delay = delaytime-t time.sleep(delay) print "Recording %d of 10" %(i+1) # Prompts the user to add Isopropanol, then records 25 data points for each colony, at 15 second intervals. tkMessageBox.showinfo("Command", "Add Isopropanol") print "continuing after Isopropanol addition" for i in range(30,60): init2 = time.time() data[i,:,:] = snapImages(500) # This code account for the variable delay in recording an imaage. t = time.time() - init2 if t <= delaytime: delay = delaytime-t time.sleep(delay) print "Recording %d of 10" %(i+1)
def hello(self): name = self.nameInput.get() or 'world' tkMessageBox.showinfo('Message', 'Hello, %s' % name)
def notify_loser(self): tkMessageBox.showinfo( 'Loser!', 'You lost. Word was *' + self.hangman.word_to_guess + '*. Click on Restart to play again')
def alert(self, msg): showinfo('提示', msg)
def About(): tkMessageBox.showinfo("About", "pyScout\n Gheorghe Postelnicu, 2006" )
keypath = argv[1] return extractKeyfile(keypath) def main(argv=sys.argv): root = Tkinter.Tk() root.withdraw() progname = os.path.basename(argv[0]) keypath = 'adeptkey.der' success = False try: success = retrieve_key(keypath) except ADEPTError, e: tkMessageBox.showerror("ADEPT Key", "Error: " + str(e)) except Exception: root.wm_state('normal') root.title('ADEPT Key') text = traceback.format_exc() ExceptionDialog(root, text).pack(fill=Tkconstants.BOTH, expand=1) root.mainloop() if not success: return 1 tkMessageBox.showinfo( "ADEPT Key", "Key successfully retrieved to %s" % (keypath)) return 0 if __name__ == '__main__': if len(sys.argv) > 1: sys.exit(cli_main()) sys.exit(main())
def onHelp(self): tkMessageBox.showinfo('Help', helpText)
def award_win(self): tkMessageBox.showinfo('Winner!', 'You won. Click on Restart to play again')
def DefaultPath(): global path path = 'C:\Program Files\OpenDSS\IEEETestCases\8500-Node' tkMessageBox.showinfo("Define Path", "The path adopted is: " + path)
def Showinfo(cls, title=None, message=None, **options): '''Sample usage: tkMessageBox.showinfo("Spam", "Egg Information") ''' tkMessageBox.showinfo(title, message, **options)
def callback_button(): tkMessageBox.showinfo( "Certificate of Button Pushery", "Are glowing pixels a reality?")
def PowerFlowYesGen(): Submit() if not path: tkMessageBox.showinfo("Bad Move", "Path not assigned") DefaultPath() global ConnectedBusEntry, SizeEntry, PFEntry, GenWindow # ASK USER: Generator data GenWindow = Tk() GenWindow.title('Connect a generator') SizeLabel = Label(GenWindow, text="Size (kW)", font=("Sans Serif", 14)) SizeEntry = Entry(GenWindow, bd=5, font="Helvetica 14") PFLabel = Label(GenWindow, text="Power Factor", font=("Sans Serif", 14)) PFEntry = Entry(GenWindow, bd=5, font="Helvetica 14") ConnectedBusLabel = Label(GenWindow, text="Bus", font=("Sans Serif", 14)) ConnectedBusEntry = Entry(GenWindow, bd=5, font="Helvetica 14") TitleLabel = Label(GenWindow, text="Define Generator Properties", font=("Helvetica", 16, "bold italic")) TitleLabel.grid(columnspan=3, sticky='W') SizeLabel.grid(row=1, column=0) PFLabel.grid(row=1, column=1) ConnectedBusLabel.grid(row=1, column=2) Button(GenWindow, text="Bus List", command=ShowBusList, height=1, width=12, font=("Sans Serif", 14)).grid(row=1, column=3, sticky='WE') SizeEntry.grid(row=2, column=0) PFEntry.grid(row=2, column=1) ConnectedBusEntry.grid(row=2, column=2) Button(GenWindow, text="Bus Location", command=ShowBusLocation, height=1, width=12, font=("Sans Serif", 14)).grid(row=2, column=3, sticky='WENS') Button(GenWindow, text="Power Flow", command=Power_Flow, height=1, width=12, font=("Sans Serif", 14)).grid(row=3, column=0, sticky='WENS') # Plot results PlotLabel = Label(GenWindow, text="Show results", font=("Helvetica", 16, "bold italic")) PlotLabel.grid(columnspan=2, sticky='W') Button(GenWindow, text="Summary", command=Show_Summary_GenCase, height=1, width=12, font=("Sans Serif", 14)).grid(row=5, column=0, sticky='WENS') Button(GenWindow, text="Voltage Profile", command=Show_VoltageProfile, height=1, width=12, font=("Sans Serif", 14)).grid(row=5, column=1, sticky='WENS') Button(GenWindow, text="Event Log", command=Show_EventLog, height=1, width=12, font=("Sans Serif", 14)).grid(row=5, column=2, sticky='WENS') Button(GenWindow, text="EXIT", command=CloseWindow, height=1, width=12, font=("Sans Serif", 14)).grid(row=7, column=0, sticky='WENS') GenWindow.mainloop()
def make_errorbox(arg1,arg2): window = tki.Tk() window.wm_withdraw() tkMessageBox.showinfo(arg1,arg2)
from Tkinter import * import tkMessageBox tkMessageBox.showinfo("Help", "Press the Arrow to Proceed.")
def Succesful_All(): tkMessageBox.showinfo( "Thanks For Using", "All Courses Succesfully Taken Press Ok To Continue") Udemy_Hacker.All_Courses()
def instruction(): tkMessageBox.showinfo( "Instructions", "The rules in Minesweeper are simple: Uncover a mine, and the game ends.Uncover an empty square, and you keep playing. Uncover a number, and it tells you how many mines lay hidden in the eight surrounding squares-information you use to deduce which nearby squares are safe to click." )
def Succesful_Design(): tkMessageBox.showinfo( "Thanks For Using", "Design Courses Succesfully Taken Press Ok To Continue") Udemy_Hacker.Designing_Courses()
def Succesful_HAcking(): tkMessageBox.showinfo( "Thanks For Using", "Hacking Courses Succesfully Taken Press Ok To Continue ") Udemy_Hacker.hacking_courses()