def error_and_exit(title, main_text): """ Show a pop-up window and sys.exit() out of Python. :param title: the short error description :param main_text: the long error description """ # NOTE: We don't want to load all of these imports normally. # Otherwise we will have these unused GUI modules loaded in the main process. from Tkinter import Tk, Canvas, DISABLED, INSERT, Label, Text, WORD root = Tk() root.wm_title("Tribler: Critical Error!") root.wm_minsize(500, 300) root.wm_maxsize(500, 300) root.configure(background='#535252') # Place the window at the center root.update_idletasks() w = root.winfo_screenwidth() h = root.winfo_screenheight() size = tuple(int(_) for _ in root.geometry().split('+')[0].split('x')) x = w / 2 - 250 y = h / 2 - 150 root.geometry("%dx%d+%d+%d" % (size + (x, y))) Canvas(root, width=500, height=50, bd=0, highlightthickness=0, relief='ridge', background='#535252').pack() pane = Canvas(root, width=400, height=200, bd=0, highlightthickness=0, relief='ridge', background='#333333') Canvas(pane, width=400, height=20, bd=0, highlightthickness=0, relief='ridge', background='#333333').pack() Label(pane, text=title, width=40, background='#333333', foreground='#fcffff', font=("Helvetica", 11)).pack() Canvas(pane, width=400, height=20, bd=0, highlightthickness=0, relief='ridge', background='#333333').pack() main_text_label = Text(pane, width=45, height=6, bd=0, highlightthickness=0, relief='ridge', background='#333333', foreground='#b5b5b5', font=("Helvetica", 11), wrap=WORD) main_text_label.tag_configure("center", justify='center') main_text_label.insert(INSERT, main_text) main_text_label.tag_add("center", "1.0", "end") main_text_label.config(state=DISABLED) main_text_label.pack() pane.pack() root.mainloop() # Exit the program sys.exit(1)
def main(): global fingerprint root = Tk() root.geometry("240x320") root.wm_title('Marauders Map') if len(sys.argv) > 1 and sys.argv[1] == 'fs': root.wm_attributes('- fullscreen', True) app = Marauders(root) channel_hop.start_mon_mode('wlan0') # Start channel hopping iface = channel_hop.get_mon_iface() #iface = 'wlan2' hop = threading.Thread(target=channel_hop.channel_hop, args=[iface]) hop.daemon = True hop.start() os.system("sudo hciconfig hci0 reset") #p = Popen(["hciconfig", "hci0", "down"], stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) #p = Popen(["hciconfig", "hci0","up"], stdout=PIPE, stderr=PIPE, preexec_fn=os.setsid) #p = Popen([app.path+"/ibeacon_scan","-b"], stdout=PIPE, preexec_fn=os.setsid) if(os.path.isfile(app.path + '/fingerprint.pkl')): fingerprint_file = open(app.path + '/fingerprint.pkl', 'rb') fingerprint = pickle.load(fingerprint_file) fingerprint_file.close() root.mainloop()
def main(): # helper method used when quitting program def kill_all_threads(): if input_frame.backend_call is not None: input_frame.backend_call.stop() input_frame.backend_call.join() root.destroy() root = Tk() root.wm_protocol ("WM_DELETE_WINDOW", kill_all_threads) root.wm_title("Seating Chart Creator") centered_window = Frame(root) centered_window.pack() header_frame = HeaderFrame(centered_window) header_frame.grid(row=0, column=0, columnspan=3, sticky=(W)) instructions_frame = InstructionsFrame(centered_window) instructions_frame.grid(row=1, column=0, columnspan=3, padx=(0,20)) progress_frame = ProgressFrame(centered_window) progress_frame.grid(row=2, column=1, padx=10, pady=20, sticky=(N)) results_frame = ResultsFrame(centered_window, progress_frame.plot_frame) results_frame.grid(row=2, column=2, padx=10, sticky=(N)) input_frame = InputFrame(centered_window, progress_frame, results_frame) input_frame.grid(row=2, column=0, padx=(30,20), sticky=(N)) progress_frame.input_frame = input_frame results_frame.input_frame = input_frame root.mainloop()
def error_and_exit(title, main_text): """ Show a pop-up window and sys.exit() out of Python. :param title: the short error description :param main_text: the long error description """ # NOTE: We don't want to load all of these imports normally. # Otherwise we will have these unused GUI modules loaded in the main process. from Tkinter import Tk, Canvas, DISABLED, INSERT, Label, Text, WORD root = Tk() root.wm_title("Tribler: Critical Error!") root.wm_minsize(500, 300) root.wm_maxsize(500, 300) root.configure(background='#535252') Canvas(root, width=500, height=50, bd=0, highlightthickness=0, relief='ridge', background='#535252').pack() pane = Canvas(root, width=400, height=200, bd=0, highlightthickness=0, relief='ridge', background='#333333') Canvas(pane, width=400, height=20, bd=0, highlightthickness=0, relief='ridge', background='#333333').pack() Label(pane, text=title, width=40, background='#333333', foreground='#fcffff', font=("Helvetica", 11)).pack() Canvas(pane, width=400, height=20, bd=0, highlightthickness=0, relief='ridge', background='#333333').pack() main_text_label = Text(pane, width=45, height=6, bd=0, highlightthickness=0, relief='ridge', background='#333333', foreground='#b5b5b5', font=("Helvetica", 11), wrap=WORD) main_text_label.tag_configure("center", justify='center') main_text_label.insert(INSERT, main_text) main_text_label.tag_add("center", "1.0", "end") main_text_label.config(state=DISABLED) main_text_label.pack() pane.pack() root.mainloop()
def main(): root = Tk() if platform.system()!="Darwin": MyHwCtrl = Hardware_control() MyHwCtrl.go_to_base() root.geometry("480x320") root.wm_title('Medimi') if len(sys.argv) > 1 and sys.argv[1] == 'fs': root.wm_attributes('-fullscreen', True) os = platform.system() print os if platform.system()!="Darwin": app = PiMenu(root, MyHwCtrl) else: print "Runnning on Mac" app = PiMenu(root,None) # myClock = Clock(root) # root.bind("<Button-1>", callback, root) # # myClock.tick() root.mainloop()
def __init__(self, container, img=None, p=None): root = Tk() root.attributes('-topmost', 1) hint = '(Enter - submit, Esc - abort)' if img is None: root.wm_title('Address') hint = 'Please enter your Bitcoin address.\n' + hint else: root.wm_title('Captcha {0:g}'.format(p)) img = ImageTk.PhotoImage(img) root.img_reference = img image = Label(root, image=img, text=hint, compound='top') image.pack() entry = Entry(root) entry.bind('<Escape>', lambda _: root.destroy()) entry.bind( '<Return>', lambda _: (container.setdefault(0, (entry.get())), root.destroy())) entry.pack() entry.focus_set() root.update_idletasks() xp = (root.winfo_screenwidth() / 2) - (root.winfo_width() / 2) - 8 yp = (root.winfo_screenheight() / 2) - (root.winfo_height() / 2) - 20 root.geometry('+%d+%d' % (xp, yp)) root.mainloop()
def init_screen(self): # intialise screen and turn off auto-render root = Tk() root.wm_title(self.window_title) window = TK.Canvas(master=root, width=self.width, height=self.height) window.pack() self.screen = TurtleScreen(window) self.screen.tracer(0, 0)
def main(): root = Tk() root.geometry("800x600") # window size root.wm_title('OP_Launcher') if len(sys.argv) > 1 and sys.argv[1] == 'fs': root.wm_attributes('-fullscreen', True) oplauncher(root) root.mainloop()
def main(): root = Tk() root.geometry("320x240") root.wm_title('PiMenu') if len(sys.argv) > 1 and sys.argv[1] == 'fs': root.wm_attributes('-fullscreen', True) app = PiMenu(root) root.mainloop()
def main(): root = Tk() root.geometry("320x240") root.wm_title('PiMenu') if len(sys.argv) > 1 and sys.argv[1] == 'fs': root.wm_attributes('-fullscreen', True) PiMenu(root) root.mainloop()
def main(config=config): """ Creates an application instance. """ root = Tk() root.columnconfigure(0, weight=1) root.wm_title("ayy lmap") app = Application(master=root, config=config) return app
def main(): root = Tk() root.geometry("800x480") root.wm_title('faigh ar ais as an fharraige') if len(sys.argv) > 1 and sys.argv[1] == 'fs': root.wm_attributes('-fullscreen', True) faaaaf_item(root) root.config(cursor='none') root.mainloop()
def createWindow(self): root = Tk() root.wm_title("Config") root.iconbitmap( default= 'C:\Users\user\Desktop\Uni\FP\Eclipse\Lab 5-7 Propper\sourceImages\ICON.ico' ) self.app = appStart(master=root) self.app.mainloop() root.destroy()
def createWindow(self, C1, C2, C3, C4, U1): root = Tk() root.wm_title("Faculty") root.iconbitmap( default= 'C:\Users\user\Desktop\Uni\FP\Eclipse\Lab 5-7 Propper\sourceImages\ICON.ico' ) app = Application(C1, C2, C3, C4, U1, master=root) app.mainloop() root.destroy()
def displayBoard(board): """ Displays the current board, both printed to the console as well as in a pop up graphical window. """ for x in range(3): print board[x] print "\n" root = Tk() gridDisplay(root, board) root.geometry("%dx%d" % (WIDTH, HEIGHT + 40)) root.wm_title("Game Progress") root.mainloop()
def __init__(self, width, height, title="NinjaTurtle"): self.width = width self.height = height self.window_title = title root = Tk() root.wm_title(self.window_title) window = TK.Canvas(master=root, width=self.width, height=self.height) window.pack() self.screen = TurtleScreen(window) self.screen.tracer(0, 0) self.turtles = dict()
def main(config=config): """ Launches the map editor. """ root = Tk() root.wm_title("MAP EDITOR") app = Application(master=root, config=config) try: app.mainloop() except KeyboardInterrupt: pass try: root.destroy() except TclError: pass
def main(): global form global track_var form = Tk() form.wm_title("Audrey 3.0") form.minsize(height=148, width=74) Label(form, text="Use velocity for the visme parameters.").grid(row=0, column=0, pady=5, columnspan=2) Label(form, text="Use channel as a multiplier for velocty to reach 255.").grid( row=1, column=0, pady=5, columnspan=2) ttk.Separator(form, orient="horizontal").grid(row=2, column=0, columnspan=2) tracks = get_all_track_names() OPTIONS = [t for t in tracks if t.startswith("LIPSYNC")] track_var = StringVar(form) track_var.set(OPTIONS[0]) trackOpt = apply(OptionMenu, (form, track_var) + tuple(OPTIONS)) trackOpt.grid(row=3, column=0, columnspan=1, sticky="WE", pady=3) btn_fromnotes = Button(form, text="Notes to Text", width=22, command=execute_notes_to_text) btn_fromnotes.grid(row=4, column=0, padx=3, pady=3, sticky="w") btn_fromtext = Button(form, text="Text to Notes", width=22, command=execute_text_to_notes) btn_fromtext.grid(row=4, column=1, padx=3, pady=3, sticky="w") Label(form, text="This may take some time. Please be patient.").grid( row=5, column=0, pady=5, columnspan=2) form.mainloop()
class FrameTk(object): def __init__(self, height, width, box_size, title = "Tk", bg = None): self.BOX_SIZE = box_size self.main = Tk() self.main.wm_title(title) self.canvas = Canvas(self.main, height = height, width = width, bg = bg) self.canvas.pack() def run(self): self.main.mainloop() def repeat(self, end, timeMillis, callback): def _repeat(end, time, func): if self.sma.stop: return if end > 0: end -= 1 self.repeat(end, time, func) func() self._draw() self.canvas.after(timeMillis, _repeat, end, timeMillis, callback) def after(self, timeMillis, callback): def _callback(time, func): if self.sma.stop: return self.after(time, func) func() self._draw() self.canvas.after(timeMillis, _callback, timeMillis, callback) def _draw(self): pass def drawTkImage(self, x, y, tkimage): self.canvas.create_image(x, y, anchor = NW, image = tkimage) def drawText(self, x, y, text, color = 'black', size = 8): self.canvas.create_text(x, y, anchor = NW, text = text, font = ('Arial', size), width = self.BOX_SIZE, fill = color)
def main(): form = Tk() form.wm_title("venuegen") form.minsize(height=148, width=74) Label(form, text="Apply to VENUE").grid(row=0, column=0, pady=5) Label(form, text="Apply to CAMERA/LIGHTING").grid(row=0, column=2, pady=5) ttk.Separator(form, orient="vertical").grid(row=0, column=1, rowspan=4, sticky="ns", padx=5) btn_cpylight = Button(form, text="Copy LIGHTING to VENUE", width=22, command=copy_lights_to_venue) btn_cpylight.grid(row=1, column=0, padx=3, pady=3, sticky="w") btn_cpycam = Button(form, text="Copy CAMERA to VENUE", width=22, command=copy_camera_to_venue) btn_cpycam.grid(row=2, column=0, padx=3, pady=3, sticky="w") btn_pulllight = Button(form, text="Pull LIGHTING from VENUE", width=22, command=pull_lighting_from_venue) btn_pulllight.grid(row=1, column=2, padx=3, pady=3, sticky="e") btn_pullcam = Button(form, text="Pull CAMERA from VENUE", width=22, command=pull_camera_from_venue) btn_pullcam.grid(row=2, column=2, padx=3, pady=3, sticky="e") btn_generate = Button(form, text="Generate!", width=30, command=generate_venue) btn_generate.grid(row=4, column=0, columnspan=3, padx=3, pady=16) form.mainloop()
def tk_plot (): from Tkinter import Tk, TOP, BOTH import matplotlib matplotlib.use('TkAgg') from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg """ Function doc """ window=Tk() window.wm_title("EasyHybrid TkWindow Plot") fig = matplotlib.figure.Figure() canvas = FigureCanvasTkAgg(fig, master=window) canvas.show() canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) canvas._tkcanvas.pack(side=TOP, fill=BOTH, expand=1) toolbar = NavigationToolbar2TkAgg(canvas, window) log_file = parameters[1].get('log_file','log_file unknown') window.wm_title(log_file) self.figure_plot(parameters, fig) window.mainloop()
def main(): root = Tk() root.geometry("640x480") root.wm_title('PiMenu') root.attributes('-alpha',0.0) pabcf = open("/home/pi/pi-apps/pimenu/settings/Pi_apps_button_color") pabc = pabcf.read() if len(sys.argv) > 2 and sys.argv[2] == 'fs': root.wm_attributes('-fullscreen', True) btn_frame = Frame(root, bg=pabc) img = PhotoImage(file=os.path.dirname(os.path.dirname(os.path.realpath(sys.argv[0]))) + "/icons/proglogo.png") pi_apps_btn = SimpleFlatButton(btn_frame,text=sys.argv[1], image=img, command=pi_apps_mainpage ) pi_apps_btn.set_color(pabc) pi_apps_btn.pack() piframe = Frame(root, bg="#155CAA") btn_frame.pack(padx=1,pady=1, fill=TkC.BOTH) piframe.pack(fill=TkC.BOTH, expand=1) PiMenu(piframe) root.mainloop()
def startSession(self): assert TkinterIsInstalled, ''' Tkinter is not installed. If you have Linux you could try using "apt-get install python-tk"''' try: import nlopt except ImportError: s = ''' To use OpenOpt multifactor analysis tool you should have nlopt with its Python API installed, see http://openopt.org/nlopt''' print(s) showerror('OpenOpt', s) raw_input() return import os hd = os.getenv("HOME") self.hd = hd root = Tk() self.root = root from openopt import __version__ as oover root.wm_title( ' OpenOpt %s Multifactor analysis tool for experiment planning ' % oover) SessionSelectFrame = Frame(root) SessionSelectFrame.pack(side='top', padx=230, ipadx=40, fill='x', expand=True) var = StringVar() var.set('asdf') Radiobutton(SessionSelectFrame, variable = var, text = 'New', indicatoron=0, \ command=lambda: (SessionSelectFrame.destroy(), self.create())).pack(side = 'top', fill='x', pady=5) Radiobutton(SessionSelectFrame, variable = var, text = 'Load', indicatoron=0, \ command=lambda:self.load(SessionSelectFrame)).pack(side = 'top', fill='x', pady=5) root.protocol("WM_DELETE_WINDOW", self.exit) root.mainloop() self.exit()
def startGui(): root=Tk() root.wm_title("Eagle V6 to Kicad Converter") root.wm_minsize(400,200) frame = Frame(root, relief=RIDGE, bg="BLUE", borderwidth=2) frame.pack(fill=BOTH,expand=1) label = Label(frame, font=20, bg="BLUE", text="What Would You Like to Do:") label.pack(fill=X, expand=1) butBrd = Button(frame, text="Convert Board",command=convertBoard) butBrd.pack(fill=X,expand=1) butLib = Button(frame, text="Convert Library",command=convertLib) butLib.pack(fill=X,expand=1) butSch = Button(frame, text="Convert Schematic",command=convertSch) butSch.pack(fill=X,expand=1) label = Label(frame,bg="BLUE", text="www.github.com/Trump211") label.pack(fill=X, expand=1) root.mainloop()
def run(self): dummy_count = 0 root = Tk() root.wm_title("Debug Window") bgndFrm = VerticalScrolledFrame(root) cmdFrm = TkCmdFrm(bgndFrm.interior) # Changed to bgndFrm.interior bgndFrm.pack() numInpBrds = 0 numSolBrds = 0 for i in xrange(len(TkinterThread.GameData.RulesData.INV_ADDR_LIST)): if ((TkinterThread.GameData.RulesData.INV_ADDR_LIST[i] & (ord)(rs232Intf.CARD_ID_TYPE_MASK)) == (ord)(rs232Intf.CARD_ID_INP_CARD)): GameData.tkInpBrd.append(TkInpBrd(numInpBrds, i, TkinterThread.GameData.RulesData.INV_ADDR_LIST[i], bgndFrm.interior)) # Changed to bgndFrm.interior numInpBrds += 1 elif ((TkinterThread.GameData.RulesData.INV_ADDR_LIST[i] & (ord)(rs232Intf.CARD_ID_TYPE_MASK)) == (ord)(rs232Intf.CARD_ID_SOL_CARD)): GameData.tkSolBrd.append(TkSolBrd(numSolBrds, i, TkinterThread.GameData.RulesData.INV_ADDR_LIST[i], bgndFrm.interior)) # Changed to bgndFrm.interior numSolBrds += 1 for i in xrange(TkinterThread.GameData.LedBitNames.NUM_LED_BRDS): GameData.tkLedBrd.append(TkLedBrd(i, numSolBrds + numInpBrds + i + 1, bgndFrm.interior)) # Changed to bgndFrm.interior root.update() TkinterThread.doneInit = True while TkinterThread._runTkinterThread: root.update() cmdFrm.Update_Cmd_Frm() # Copy the current LED state self.blinkOn = not self.blinkOn ledData = list(LedBrd.currLedData) if self.blinkOn: ledBlink = list(LedBrd.currBlinkLeds) for i in xrange(TkinterThread.GameData.LedBitNames.NUM_LED_BRDS): ledData[i] |= ledBlink[i] for i in xrange(TkinterThread.GameData.LedBitNames.NUM_LED_BRDS): GameData.tkLedBrd[i].updateLeds(ledData[i]) for i in xrange(numSolBrds): GameData.tkSolBrd[i].update_status_field(SolBrd.currSolData[i]) for i in xrange(numInpBrds): GameData.tkInpBrd[i].update_status_field(InpBrd.currInpData[i]) dummy_count += 1 time.sleep(float(GlobConst.TK_SLEEP)/1000.0)
def main(): # Authenticate using your Google Docs email address and password. client.ClientLogin(config.username, config.password) ## Query the server for an Atom feed containing a list of your documents. #documents_feed = client.GetDocumentListFeed() ## Loop through the feed and extract each document entry. #for document_entry in documents_feed.entry: # # Display the title of the document on the command line. # print document_entry.title.text ## This is a simple GUI, so we allow the root singleton to do the legwork root = Tk() WIDTH, HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight() # root.overrideredirect(1) root.geometry("%dx%d+0+0" % (WIDTH, HEIGHT)) root.focus_set() # <-- move focus to this widget root.wm_attributes("-topmost", True) root.wm_title("Wedding Photobooth") frame = Frame(root) frame.pack() photobooth = Photobooth(root) ## add a software button in case hardware button is not available #interface_frame = Frame(root) #snap_button = Button(interface_frame, text="*snap*", command=takePicture) #snap_button.pack(side=RIGHT) #interface_frame.pack(side=RIGHT) ### check button after waiting for 200 ms #root.after(200, check_and_snap) # Instead of the preview, we might write an image every half second or so root.after(200, photobooth.start) root.mainloop()
class monitor(object): def __init__(self, title): self.root = Tk() self.root.wm_title(title) self.text = Text(self.root) self.text.pack() self.root.update() def write(self, msg): self.text.insert(END, msg) self.text.see(END) self.root.update() def writeln(self, msg): self.text.insert(END, str(msg) + '\n') self.text.see(END) self.root.update() def update(self): self.root.update() def close(self): self.root.destroy
class Lamp(object): def __init__(self, queue): self.root = Tk() self.root.wm_title("lamp") self.circle = Canvas(self.root, width=100, height=100, bg='gray') self.circle.grid(padx=10, pady=10) self.queue = queue self.turnoff = True self.color = DEFAULT_COLOR self.circle.create_oval(20, 20, 80, 80, fill = self.color) def mainloop(self): self.root.mainloop() def action(self): xtype, xlen, xcolor = self.queue.get(block = True) if xcolor is not None: self.color = xcolor try: getattr(self, '_' + TYPE_MAP[xtype])() except Exception, e: error('action error %s' % e) finally:
def startSession(self): assert TkinterIsInstalled, ''' Tkinter is not installed. If you have Linux you could try using "apt-get install python-tk"''' try: import nlopt except ImportError: s = ''' To use OpenOpt multifactor analysis tool you should have nlopt with its Python API installed, see http://openopt.org/nlopt''' print(s) showerror('OpenOpt', s) raw_input() return import os hd = os.getenv("HOME") self.hd = hd root = Tk() self.root = root from openopt import __version__ as oover root.wm_title(' OpenOpt %s Multifactor analysis tool for experiment planning ' % oover) SessionSelectFrame = Frame(root) SessionSelectFrame.pack(side='top', padx=230, ipadx = 40, fill='x', expand=True) var = StringVar() var.set('asdf') Radiobutton(SessionSelectFrame, variable = var, text = 'New', indicatoron=0, \ command=lambda: (SessionSelectFrame.destroy(), self.create())).pack(side = 'top', fill='x', pady=5) Radiobutton(SessionSelectFrame, variable = var, text = 'Load', indicatoron=0, \ command=lambda:self.load(SessionSelectFrame)).pack(side = 'top', fill='x', pady=5) root.protocol("WM_DELETE_WINDOW", self.exit) root.mainloop() self.exit()
from PIL import Image, ImageTk ''' This is the class for hidden marcov model which ralate to 3 previous subject of the system. This reads the calculated proberbility value in the text file at the configeration level This is the class which create the model relationship starting probabilities are assign to the state equal brobabilities Ex: [0.25, 0.25,0.25, 0.25] Emmission proberbilities are assign more more gerneral way. It is if 2nd prediction is much closer of same to the second prediction ''' class Example(): def onError(self): box.showerror("Error", "Error In Input Grade ") mastert = Tk() mastert.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(mastert, image=img).grid(row=0, column=3) mastert.wm_title("Pediction Based on 3 Subjects") Label(mastert,background='#8A002E',foreground="white", text="Enter Subject 1 Grade:").grid(row=1) Label(mastert,background='#8A002E',foreground="white", text="Enter Subject 2 Grade:").grid(row=2) Label(mastert,background='#8A002E',foreground="white", text="Enter Subject 3 Grade:").grid(row=3) e1 = Entry(mastert) e2 = Entry(mastert) e3= Entry(mastert) e1.grid(row=1, column=1) e2.grid(row=2, column=1) e3.grid(row=3, column=1) def Fun(): subgrd = e1.get() subgrd2 = e2.get() subgrd3 = e3.get() obs=[]
def test(): app = Tk() app.wm_title("CropGUI -- lossless cropping and rotation of jpeg files") app.wm_iconname("CropGUI") preview = Label(app) do_crop = Button(app, text="Crop") info = Label(app) preview.pack(side="bottom") do_crop.pack(side="left") info.pack(side="left") max_h = app.winfo_screenheight() - 64 - 32 max_w = app.winfo_screenwidth() - 64 drag = DragManager(app, preview, do_crop, info) app.wm_protocol('WM_DELETE_WINDOW', drag.close) def image_names(): if len(sys.argv) > 1: for i in sys.argv[1:]: yield i else: while 1: names = askopenfilename( master=app, defaultextension=".jpg", multiple=1, parent=app, filetypes=( ("JPEG Image Files", ".jpg .JPG .jpeg .JPEG"), ("All files", "*"), ), title="Select images to crop") if not names: break for name in names: yield name pids = set() def reap(): global pids pids = set(p for p in pids if p.poll() is None) for image_name in image_names(): img = Image.open(image_name) iw, ih = img.size scale = 1 while iw > max_w or ih > max_h: iw /= 2 ih /= 2 scale *= 2 img.thumbnail((iw, ih)) drag.image = img drag.round = max(1, 8/scale) if not drag.wait(): continue # user hit "next" (tba) without cropping base, ext = os.path.splitext(image_name) t, l, r, b = drag.top, drag.left, drag.right, drag.bottom t *= scale l *= scale r *= scale b *= scale cropspec = "%dx%d+%d+%d" % (r-l, b-t, l, t) target = base + "-crop" + ext target = open(target, "wb") pids.add(subprocess.Popen( ['jpegtran', '-optimize', '-progressive', '-crop', cropspec, image_name], stdout=target)) target.close() while pids: reap() sys.stdout.write("Waiting for %d children to exit. \r" % len(pids)) sys.stdout.flush() time.sleep(.1) sys.stdout.write(" "*79 + "\r")
""" # set up the output list out = [] for option in sorted(file_name_options)[::5]: if option[-3:] == ".ng": out.append(option[:-5]) return out # initialize the nGram variable nGram = {} # set up the ui frame and give it a title root = Tk() root.wm_title("Text Predictor") # set up a label prompting the user to enter text Label(root, text="Enter text:").grid(row=0) # set up as string variable to call the match entry function whenever it is changed enteredText = StringVar() enteredText.set("") enteredText.trace("w", match_entry) # set up the entry box for the user to enter text (using the enteredText string variable) matchThis = Entry(root, textvariable=enteredText, justify=RIGHT) matchThis.grid(row=0, column=1) # set up the result string variable and the label that holds it result = []
class TkView(object): ''' TkView represents a window container for components ''' def __init__(self): ''' Constructor: Excepts no arguments ''' self.die = Die(6) self.root = Tk() self.root.wm_title(APP_NAME) self.root.resizable(False, False) self.set_up_menu() self.set_up_labels() self.set_up_entries_and_buttons() def set_up_menu(self): ''' Sets up the menu bar and its submenus ''' menubar = Menu(self.root) filemenu = Menu(menubar, tearoff=0) filemenu.add_command(label="About", command=self.about) filemenu.add_separator() filemenu.add_command(label="Exit", command=self.root.quit) menubar.add_cascade(label="File", menu=filemenu) self.root.config(menu=menubar) def set_up_labels(self): ''' Sets up the text labels for components ''' Label(self.root, text="Sides ").grid() Label(self.root, text="Mod ").grid(row=1) Label(self.root, text="Result :").grid(row=2) self.result = Label(self.root, text="~") self.result.grid(row=2, column=1, sticky=W) def set_up_entries_and_buttons(self): ''' Sets up entries and buttons the user interacts with ''' self.sides = Entry(self.root) self.sides.grid(row=0, column=1, sticky=W) self.sides.insert(0, "6") self.mod = Entry(self.root) self.mod.grid(row=1, column=1, sticky=W) self.mod.insert(0, "0") Button(self.root, text="Roll ", command=self.roll).grid(row=0, column=2, rowspan=3, sticky=(N, S)) def run(self): ''' Begins the main GUI loop ''' self.root.mainloop() def about(self): ''' Displays a pop up about the author and contact information ''' new_pop_up(APP_NAME, "PyRoller: a simple die roller\n\n" + "Wrote by Corey Prophitt <*****@*****.**>") def roll(self): ''' Rolls the die and sets the result ''' # Avoid user entering blank values if self.sides.get() != '': # Only re-instantiate die if the side has changed if self.die.face != int(self.sides.get()): self.die = Die(int(self.sides.get())) text_ = str(self.die.roll()) + " + " # Only use mod entry if sides is defined and mod isn't blank if self.mod.get() != '': text_ += str(int(self.mod.get())) text_ += " = " + str(self.die.face+int(self.mod.get())) else: text_ += str(0) + " = " + str(self.die.face) else: text_ = 0 self.result.config(text=text_)
def gui(): from Tkinter import Tk, Label, Entry, Button, Scale, Checkbutton, W, HORIZONTAL, Frame, StringVar, IntVar, DoubleVar, Radiobutton, BooleanVar, E global root root = Tk() root.wm_title("Compute R_complete") line = 0 global insFile, hklFile, nHKL, nParams, nHKLLabel, fracFree, status, nParamsLabel, nCPU, rCompleteLabel, cycles, lsType, cleanup, nFree, nRunsLabel, mergeCheck, compileMap insFile = StringVar() hklFile = StringVar() nHKL = IntVar() nParams = IntVar() nFree = IntVar() fracFree = DoubleVar() fracFree.set(5.0) nCPU = IntVar() nCPU.set(maxCPU) cycles = IntVar() cycles.set(10) lsType = IntVar() lsType.set(1) cleanup = BooleanVar() cleanup.set(True) mergeCheck = BooleanVar() mergeCheck.set(True) compileMap = BooleanVar() compileMap.set(True) Label(root, text='Instruction File:').grid(row=line, column=0, sticky=E) Entry(root, textvariable=insFile).grid(row=line, column=1) Button(root, text='Browse', command=browseINS).grid(row=line, column=2) line += 1 Label(root, text='Reflection File:').grid(row=line, column=0, sticky=E) Entry(root, textvariable=hklFile).grid(row=line, column=1) Button(root, text='Browse', command=browseHKL).grid(row=line, column=2) line += 1 Checkbutton(root, var=mergeCheck, text='Merge Reflections').grid(row=line, column=1, sticky=W) line += 1 Button(root, text='Load', command=load).grid(row=line, columnspan=3) line += 1 Frame(root, height=20).grid(row=line) line += 1 Label(root, text='# of reflections:').grid(row=line, sticky=E) nHKLLabel = Label(root, text='???') nHKLLabel.grid(row=line, column=1, sticky=W) line += 1 Label(root, text='# of atoms:').grid(row=line, sticky=E) nParamsLabel = Label(root, text='???') nParamsLabel.grid(row=line, column=1, sticky=W) line += 1 Frame(root, height=20).grid(row=line) line += 1 Label(root, text='Select Parameters').grid(row=line, column=1) line += 1 Frame(root, height=20).grid(row=line) line += 1 Label(root, text='# of free reflections:').grid(row=line, sticky=E) nFreeEntry = Entry(root, width=5, textvariable=nFree) nFreeEntry.grid(row=line, column=1, sticky=W) nFreeEntry.bind('<Return>', setScale) nRunsLabel = Label(root, text='# runs') nRunsLabel.grid(row=line, column=2) line += 1 Label(root, text='% of free reflections:').grid(row=line, column=0, sticky=E) w = Scale(root, from_=0.1, to=10.0, resolution=0.1, orient=HORIZONTAL, length=200, var=fracFree, command=percentScale) w.grid(row=line, column=1, columnspan=2, sticky=W) line += 1 Label(root, text='stable <-------------------------------> fast').grid( row=line, column=1, columnspan=2, sticky=W) line += 1 Frame(root, height=10).grid(row=line) line += 1 Label(root, text='Refinement cycles:').grid(row=line, column=0, sticky=E) ls = Scale(root, from_=0, to=50, resolution=1, orient=HORIZONTAL, length=200, var=cycles) ls.grid(row=line, column=1, columnspan=2, sticky=W) line += 1 Label(root, text='fast <--------------------> less model bias').grid( row=line, column=1, columnspan=2, sticky=W) line += 1 Frame(root, height=10).grid(row=line) line += 1 Label(root, text='# of CPUs:').grid(row=line, column=0, sticky=E) ww = Scale(root, from_=1, to=maxCPU, orient=HORIZONTAL, length=200, var=nCPU) ww.grid(row=line, column=1, columnspan=2, sticky=W) line += 1 Label(root, text='Refinement Type:').grid(row=line, column=0, sticky=E) Radiobutton(root, text='CGLS', var=lsType, value=1).grid(row=line, column=1, sticky=W) Radiobutton(root, text='L.S.', var=lsType, value=2).grid(row=line, column=2, sticky=W) line += 1 Frame(root, height=10).grid(row=line) line += 1 Label(root, text='Compile map:').grid(row=line, column=0, sticky=E) Checkbutton(root, var=compileMap).grid(row=line, column=1, sticky=W) line += 1 Label(root, text='Cleanup:').grid(row=line, column=0, sticky=E) Checkbutton(root, var=cleanup).grid(row=line, column=1, sticky=W) line += 1 Button(root, text='RUN', command=run, width=25).grid(row=line, columnspan=3) line += 1 Frame(root, height=20).grid(row=line) line += 1 Label(root, text='R_complete:').grid(row=line, column=0, sticky=E) rCompleteLabel = Label(root, text='???') rCompleteLabel.grid(row=line, column=1, sticky=W) line += 1 Frame(root, height=20).grid(row=line) line += 1 Label(root, text='Status:').grid(row=line, column=0, sticky=E) status = Label(root, text='Idle... Please load files.') status.grid(row=line, column=1, columnspan=2, sticky=W) global IDLE IDLE = True root.mainloop()
def onError(self): box.showerror("Error", "Could not Upadate") def onQuest(self): box.askquestion("Question", "Are you sure to quit?") def onInfo(self): box.showinfo("Information", "Upadate Sucessfully") #-------------------------------------- master = Tk() master.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(master, image=img).grid(row=0, column=3) master.wm_title("Enter Data") Label(master, background='#8A002E', foreground="white", text="Student Index:").grid(row=1) Label(master, background='#8A002E', foreground="white", text="Test Number:").grid(row=2) Label(master, background='#8A002E', foreground="white", text="Enter marks:").grid(row=3) Label(master, background='#8A002E', foreground="white", text="Module code:").grid(row=4) e1 = Entry(master) e2 = Entry(master) e3 = Entry(master) e4 = Entry(master) e1.grid(row=1, column=1)
__author__ = 'Yas' #!/usr/bin/python from Tkinter import * import MySQLdb from ttk import Frame, Button, Style from Tkinter import Tk import matplotlib.pyplot as plt from PIL import Image, ImageTk import os import numpy master = Tk() master.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(master, image=img).grid(row=0, column=3) master.wm_title("Lectures Progress") Label(master,background='#8A002E',foreground="white", text="Enter Module Code:").grid(row=1) Label(master,background='#8A002E',foreground="white", text="Enter Year:").grid(row=2) e1 = Entry(master) e2 = Entry(master) e1.grid(row=1, column=1) e2.grid(row=2, column=1) def getUserNm(): tem=[] with open('Config.txt','r') as f: for line in f: for word in line.split(): tem.append(word)
# print text results = self.movieSearcher.searchMovie(text) self.outputArea.writeText(results) # print results class OutputArea(Text): def __init__(self, parent): Text.__init__(self, parent) def clearText(self): self.delete("1.0", END) def writeText(self, text): self.clearText() self.insert("1.0", text) class SearchButton(Button): def __init__(self, parent): Button.__init__(self, parent, text="Get movie data") root = Tk() root.wm_title("IMDb searcher") mf = MainFrame(root) root.mainloop() root.destroy()
This is the class which create the model relationship starting probabilities are assign to the state equal brobabilities Ex: [0.25, 0.25,0.25, 0.25] Emmission proberbilities are assign more more gerneral way. It is if 2nd prediction is much closer of same to the second prediction ''' class Example(): def onError(self): box.showerror("Error", "Error In Input Grade ") mastert = Tk() mastert.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(mastert, image=img).grid(row=0, column=3) mastert.wm_title("Pediction Based on 3 Subjects") Label(mastert, background='#8A002E', foreground="white", text="Enter Subject 1 Grade:").grid(row=1) Label(mastert, background='#8A002E', foreground="white", text="Enter Subject 2 Grade:").grid(row=2) Label(mastert, background='#8A002E', foreground="white", text="Enter Subject 3 Grade:").grid(row=3) e1 = Entry(mastert) e2 = Entry(mastert) e3 = Entry(mastert)
def onError(self): box.showerror("Error", "Could not Upadate") def onQuest(self): box.askquestion("Question", "Are you sure to quit?") def onInfo(self): box.showinfo("Information", "Upadate Sucessfully") #-------------------------------------- master = Tk() master.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(master, image=img).grid(row=0, column=3) master.wm_title("All Students Result") Label(master, background='#8A002E', foreground="white", text="Enter Module Code:").grid(row=1) Label(master, background='#8A002E', foreground="white", text="Enter Year:").grid(row=2) e1 = Entry(master) e2 = Entry(master) std = [] e1.grid(row=1, column=1) e2.grid(row=2, column=1)
from ttk import Frame, Button, Style from Tkinter import Tk import matplotlib.pyplot as plt from PIL import Image, ImageTk import os import numpy ''' This is the class for Gernerate feed back from the database. Password of the database is read from the file This calculate the mean value of the student at each test ''' master = Tk() master.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(master, image=img).grid(row=0, column=3) master.wm_title("Lectures Progress") Label(master,background='#8A002E',foreground="white", text="Enter Module Code:").grid(row=1) Label(master,background='#8A002E',foreground="white", text="Enter Year:").grid(row=2) e1 = Entry(master) e2 = Entry(master) e1.grid(row=1, column=1) e2.grid(row=2, column=1) def getUserNm(): tem=[] with open('Config.txt','r') as f: for line in f: for word in line.split(): tem.append(word)
delete_content(f) f.close() root.quit() #sys.exit() f.write(line[:-1]) f.write("\n") f.close() showinfo("Final Status","File converted. Please see this path %s"%(fileout)) root.quit() #print "Finished writing ",fileout def quit(): root.quit() def file_selector(): Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing filename = askopenfilename(parent=root,initialdir=home,title='Please select a spreadsheet for converting') #,filetypes = (("Spreadsheet Files","*.xls;"),)) #*.xlsx;*.odt"),("HTML files", "*.html;*.htm"))) if filename: convert_excel_to_txt(filename) #showinfo("Answer", filename) root = Tk() root.wm_title("Kodak Excel Parser") frame = Frame(root,height=300,width=300) Button(text='Select Spreadsheet File', command=file_selector).pack(fill=X) Button(text='Quit', command=quit).pack(fill=X) root.mainloop()
import os from PIL import Image, ImageTk class Example(): def onError(self): box.showerror("Error", "Login Fail") def onInfo(self): box.showinfo("Information", "Login Sucessfully") mastert = Tk() mastert.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(mastert, image=img).grid(row=0, column=3) mastert.wm_title("System Login") Label(mastert,background='#8A002E',foreground="white", text="Enter System UserName").grid(row=1) Label(mastert, background='#8A002E',foreground="white",text="Enter System Passwor:").grid(row=2) e1 = Entry(mastert) e2 = Entry(mastert) e1.grid(row=1, column=1) e2.grid(row=2, column=1) #read password from file------------------- def getUserUserNm(user): tem=[] with open('Config.txt','r') as f: for line in f: for word in line.split():
self.searchButton.bind('<Button-1>', self.buttonClicked) def buttonClicked(self, evt): text = self.get() # print text results = self.movieSearcher.searchMovie(text) self.outputArea.writeText(results) # print results class OutputArea(Text): def __init__(self, parent): Text.__init__(self, parent) def clearText(self): self.delete("1.0", END) def writeText(self, text): self.clearText() self.insert("1.0", text) class SearchButton(Button): def __init__(self, parent): Button.__init__(self, parent, text="Get movie data") root = Tk() root.wm_title("IMDb searcher") mf = MainFrame(root) root.mainloop() root.destroy()
def onError(self): box.showerror("Error", "Could not Upadate") def onQuest(self): box.askquestion("Question", "Are you sure to quit?") def onInfo(self): box.showinfo("Information", "Upadate Sucessfully") master = Tk() master.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(master, image=img).grid(row=0, column=3) master.wm_title("System Configuration") Label(master,background='#8A002E',foreground="white", text="System UserName").grid(row=1, column=0) Label(master,background='#8A002E',foreground="white", text="System Password:"******"white", text="No of Related Subjects:").grid(row=3, column=0) def getUserNm(): tem=[] with open('Config.txt','r') as f: for line in f: for word in line.split(): tem.append(word) f.close() return tem[2] #get password def getPass(): tem=[] with open('Config.txt','r') as f:
class TronClient(object): """non-threadsafe client which mimics the Turing API""" OUTCOME="tie","win","lose","tie" def __init__(self,*args): self._t=self._x=self._y=self.t=self.x=self.y=-1 self.outcome="ongoing" self.sock=None self.full=[[False]*49 for _ in xrange(50)] self.show=False self.root=self.cvs=None self.dropped=0 if args: self.start(*args) def start(self,user=None,pw=None,host="",port=PORT): if isinstance(user,str)and not isinstance(pw,str): user,pw,host,port=None,None,user,pw if pw is not None else port self.sock=create_connection((host,port)) setsockopt(self.sock,option=TCP_NODELAY) buf="" if user is not None: buf+='L'+pack(STRUCT_UP_LOGIN,user,pw) buf+='S' self.sock.sendall(buf) startlogin=start def _recv(self): self._t,self._x,self._y,a=unpack(STRUCT_DOWN_FRAME,self.sock.recv(calcsize(STRUCT_DOWN_FRAME))) setsockopt(self.sock) self._t-=1 self._x-=1 self._y-=1 if self._x!=-1: self.t=self._t+1 if self._t>1 and(self.x!=self._x or self.y!=self._y): self.dropped+=1 self.x=self._x self.y=self._y else: self._close() outcome=self.OUTCOME[self._y+1] self.__init__() self.outcome=outcome for i in xrange(50): for j in xrange(49): k=i*49+j self.full[i][j]=(ord(a[k/8])>>(k%8))&1==1 if self.show: if not self.root: self.root=Tk() self.root.resizable(0,0) self.root.protocol("WM_DELETE_WINDOW",self._close) self.root.wm_title(argv[0]) self.cvs=Canvas(self.root,width=201,height=197,highlightthickness=0) self.cvs.pack() self.rects=[[self.cvs.create_rectangle(4*i,4*j,4*(i+1),4*(j+1))for j in reversed(xrange(49))]for i in xrange(50)] for i in xrange(50): for j in xrange(49): self.cvs.itemconfig(self.rects[i][j],fill="#088"if i==self.x and j==self.y else"#ccc"if self.full[i][j]else"white") self.root.update() elif self.root: self.root.destroy() self.root=self.cvs=self.rects=None def ended(self): if not self.sock: return True err=False if self.t>=0: assert abs(self._x-self.x)+abs(self._y-self.y)<=self.t-self._t and(self.t!=self._t+1 or(self._x-self.x)**2+(self._y-self.y)**2==1) try: self.sock.sendall(pack(STRUCT_UP_MOVE,self.t+1,self.x+1,self.y+1)) except IOError: err=True try: self._recv() except IOError: err=True if err: self._close() return not self.sock def _close(self): if self.sock: try: self.sock.shutdown(SHUT_RDWR) except error: pass try: self.sock.close() except: pass self.sock=None def __iter__(self): while not self.ended(): yield self def __repr__(self): return"<"+self.__class__.__name__+"@%(dropped)d/%(t)d (%(x)d,%(y)d) %(outcome)s>"%self.__dict__
class GUI: def __init__(self, model, title='PyCX Simulator', interval=0, stepSize=1, param_gui_names=None): self.model = model self.titleText = title self.timeInterval = interval self.stepSize = stepSize self.param_gui_names = param_gui_names if param_gui_names is None: self.param_gui_names = {} self.param_entries = {} self.statusStr = "" self.running = False self.modelFigure = None self.currentStep = 0 self.initGUI() def initGUI(self): #create root window self.rootWindow = Tk() self.statusText = StringVar(value=self.statusStr) self.setStatusStr("Simulation not yet started") self.rootWindow.wm_title(self.titleText) self.rootWindow.protocol('WM_DELETE_WINDOW', self.quitGUI) self.rootWindow.geometry('550x700') self.rootWindow.columnconfigure(0, weight=1) self.rootWindow.rowconfigure(0, weight=1) self.frameSim = Frame(self.rootWindow) self.frameSim.pack(expand=YES, fill=BOTH, padx=5, pady=5, side=TOP) self.status = Label(self.rootWindow, width=40, height=3, relief=SUNKEN, bd=1, textvariable=self.statusText) self.status.pack(side=TOP, fill=X, padx=1, pady=1, expand=NO) self.runPauseString = StringVar() self.runPauseString.set("Run") self.buttonRun = Button(self.frameSim, width=30, height=2, textvariable=self.runPauseString, command=self.runEvent) self.buttonRun.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonRun, "Runs the simulation (or pauses the running simulation)") self.buttonStep = Button(self.frameSim, width=30, height=2, text="Step Once", command=self.stepOnce) self.buttonStep.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonStep, "Steps the simulation only once") self.buttonReset = Button(self.frameSim, width=30, height=2, text="Reset", command=self.resetModel) self.buttonReset.pack(side=TOP, padx=5, pady=5) self.showHelp(self.buttonReset, "Resets the simulation") for param in self.model.params: var_text = self.param_gui_names.get(param, param) can = Canvas(self.frameSim) lab = Label(can, width=25, height=1 + var_text.count('\n'), text=var_text, anchor=W, takefocus=0) lab.pack(side='left') ent = Entry(can, width=11) val = getattr(self.model, param) if isinstance(val, bool): val = int(val) # Show 0/1 which can convert back to bool ent.insert(0, str(val)) ent.pack(side='left') can.pack(side='top') self.param_entries[param] = ent if self.param_entries: self.buttonSaveParameters = Button(self.frameSim, width=50, height=1, command=self.saveParametersCmd, text="Save parameters to the running model", state=DISABLED) self.showHelp(self.buttonSaveParameters, "Saves the parameter values.\n" + "Not all values may take effect on a running model\n" + "A model reset might be required.") self.buttonSaveParameters.pack(side='top', padx=5, pady=5) self.buttonSaveParametersAndReset = Button(self.frameSim, width=50, height=1, command=self.saveParametersAndResetCmd, text="Save parameters to the model and reset the model") self.showHelp(self.buttonSaveParametersAndReset, "Saves the given parameter values and resets the model") self.buttonSaveParametersAndReset.pack(side='top', padx=5, pady=5) can = Canvas(self.frameSim) lab = Label(can, width=25, height=1, text="Step size ", justify=LEFT, anchor=W, takefocus=0) lab.pack(side='left') self.stepScale = Scale(can, from_=1, to=500, resolution=1, command=self.changeStepSize, orient=HORIZONTAL, width=25, length=150) self.stepScale.set(self.stepSize) self.showHelp(self.stepScale, "Skips model redraw during every [n] simulation steps\n" + "Results in a faster model run.") self.stepScale.pack(side='left') can.pack(side='top') can = Canvas(self.frameSim) lab = Label(can, width=25, height=1, text="Step visualization delay in ms ", justify=LEFT, anchor=W, takefocus=0) lab.pack(side='left') self.stepDelay = Scale(can, from_=0, to=max(2000, self.timeInterval), resolution=10, command=self.changeStepDelay, orient=HORIZONTAL, width=25, length=150) self.stepDelay.set(self.timeInterval) self.showHelp(self.stepDelay, "The visualization of each step is " + "delays by the given number of " + "milliseconds.") self.stepDelay.pack(side='left') can.pack(side='top') def setStatusStr(self, newStatus): self.statusStr = newStatus self.statusText.set(self.statusStr) #model control functions def changeStepSize(self, val): self.stepSize = int(val) def changeStepDelay(self, val): self.timeInterval = int(val) def saveParametersCmd(self): for param, entry in self.param_entries.items(): val = entry.get() if isinstance(getattr(self.model, param), bool): val = bool(int(val)) setattr(self.model, param, val) # See if the model changed the value (e.g. clipping) new_val = getattr(self.model, param) if isinstance(new_val, bool): new_val = int(new_val) entry.delete(0, END) entry.insert(0, str(new_val)) self.setStatusStr("New parameter values have been set") def saveParametersAndResetCmd(self): self.saveParametersCmd() self.resetModel() def runEvent(self): if not self.running: self.running = True self.rootWindow.after(self.timeInterval, self.stepModel) self.runPauseString.set("Pause") self.buttonStep.configure(state=DISABLED) if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) self.buttonSaveParametersAndReset.configure(state=DISABLED) else: self.stopRunning() def stopRunning(self): self.running = False self.runPauseString.set("Continue Run") self.buttonStep.configure(state=NORMAL) self.drawModel() if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) self.buttonSaveParametersAndReset.configure(state=NORMAL) def stepModel(self): if self.running: if self.model.step() is True: self.stopRunning() self.currentStep += 1 self.setStatusStr("Step " + str(self.currentStep)) self.status.configure(foreground='black') if (self.currentStep) % self.stepSize == 0: self.drawModel() self.rootWindow.after(int(self.timeInterval * 1.0 / self.stepSize), self.stepModel) def stepOnce(self): self.running = False self.runPauseString.set("Continue Run") self.model.step() self.currentStep += 1 self.setStatusStr("Step " + str(self.currentStep)) self.drawModel() if self.param_entries: self.buttonSaveParameters.configure(state=NORMAL) def resetModel(self): self.running = False self.runPauseString.set("Run") self.model.reset() self.currentStep = 0 self.setStatusStr("Model has been reset") self.drawModel() def drawModel(self): if self.modelFigure is None: self.modelFigure = plt.figure() plt.ion() self.model.draw() # Tell matplotlib to redraw too. The darwin-version works with more # types of matplotlib backends, but seems to fail on some Linux # machines. Hence we use the TkAgg specific method when available. if sys.platform == 'darwin': self.modelFigure.canvas.manager.show() else: self.modelFigure.canvas.manager.window.update() def start(self): if self.model.step.__doc__: self.showHelp(self.buttonStep, self.model.step.__doc__.strip()) self.model.reset() self.drawModel() self.rootWindow.mainloop() def quitGUI(self): plt.close('all') self.rootWindow.quit() self.rootWindow.destroy() def showHelp(self, widget, text): def setText(self): self.statusText.set(text) self.status.configure(foreground='blue') def showHelpLeave(self): self.statusText.set(self.statusStr) self.status.configure(foreground='black') widget.bind("<Enter>", lambda e: setText(self)) widget.bind("<Leave>", lambda e: showHelpLeave(self))
The code that follows is not optimal nor is it well organized but it does work. It solves the Minimum Steiner Problem in relatively small time with Rectilinear Space in O(n^3 * logn) and Graphical Space in O(n^4 * logn) Note to self: Add comments and organization to the functions. Note to reader: Sorry for the lack of comments and organization. See above. """ from Tkinter import Canvas, Tk, Frame, Button, RAISED, TOP, StringVar, Label, RIGHT, RIDGE import random import math import sys from UnionFind import UnionFind tk = Tk() tk.wm_title("Steiner Trees") global OriginalPoints OriginalPoints = [] global RectSteinerPoints RectSteinerPoints = [] global GraphSteinerPoints GraphSteinerPoints = [] global RMST RMST = [] global RSMT RSMT = [] global GMST GMST = [] global GSMT GSMT = []
class Example(): def onError(self): box.showerror("Error", "Could not Upadate") def onQuest(self): box.askquestion("Question", "Are you sure to quit?") def onInfo(self): box.showinfo("Information", "Upadate Sucessfully") #-------------------------------------- master = Tk() master.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(master, image=img).grid(row=0, column=3) master.wm_title("Enter Data") Label(master,background='#8A002E',foreground="white", text="Enter Test Number:").grid(row=1) Label(master,background='#8A002E',foreground="white", text="Year:").grid(row=2) Label(master,background='#8A002E',foreground="white", text="Module code:").grid(row=3) Label(master,background='#8A002E',foreground="white", text="Test Weight:").grid(row=4) e2 = Entry(master) e3 = Entry(master) e4 = Entry(master) e5 = Entry(master) e2.grid(row=1, column=1) e3.grid(row=2, column=1) e4.grid(row=3, column=1) e5.grid(row=4, column=1)
class Example(): def onError(self): box.showerror("Error", "Could not Upadate") def onQuest(self): box.askquestion("Question", "Are you sure to quit?") def onInfo(self): box.showinfo("Information", "Upadate Sucessfully") #-------------------------------------- master = Tk() master.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(master, image=img).grid(row=0, column=3) master.wm_title("All Students Result") Label(master,background='#8A002E',foreground="white", text="Enter Module Code:").grid(row=1) Label(master,background='#8A002E',foreground="white", text="Enter Year:").grid(row=2) e1 = Entry(master) e2 = Entry(master) std=[] e1.grid(row=1, column=1) e2.grid(row=2, column=1) def getUserNm(): tem=[] with open('Config.txt','r') as f: for line in f: for word in line.split(): tem.append(word)
from PIL import Image, ImageTk ''' This is the class for Rredeirecting class to the marckcov model 1 , 2 and 3 ''' class Example(): def onError(self): box.showerror("Error", "No Of Subjects Exceed Maximun Limits ") mastert = Tk() mastert.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(mastert, image=img).grid(row=0, column=3) mastert.wm_title("System Login") Label(mastert, background='#8A002E', foreground="white", text="Enter No Dependent Subjects:").grid(row=1) e1 = Entry(mastert) e1.grid(row=1, column=1) def SysLog1(): os.system('python win_Mac_sub1.py') def SysLog2(): os.system('python win_Mac_sub2.py')
streams = self._tolist(json.load(fd)) for idx,stream in enumerate(streams): if not stream.has_key('name'): stream['name'] = self.get_stream_name(idx) return streams def action_dump_last_stream(self): # None -> 'null' # dict -> dict with open(self._fn_last_stream, 'w') as fd: json.dump(self.selected_stream, fd) def get_stream_name(self, idx): return self.streams[idx]['name'] if __name__ == '__main__': parser = argparse.ArgumentParser(description='raspi radio') parser.add_argument('-v', '--verbose', help="verbose debug output", action='store_true', default=False) args = parser.parse_args() root = Tk() root.geometry("320x210") root.wm_title("raspi radio") if args.verbose: VERBOSE = True p = TkMplayer(root) root.mainloop()
#!/usr/bin/python import os from Tkinter import Tk, Label, Button, Entry, ACTIVE root = Tk() root.wm_title("Enter MFA Token") Label(root, text="Token").pack() entry = Entry(root) entry.pack(padx=5) def done(): print entry.get() root.destroy() b = Button(root, text="OK", default=ACTIVE, command=done) b.pack(pady=5) entry.focus_force() root.bind('<Return>', (lambda e, b=b: b.invoke())) os.system(('''/usr/bin/osascript -e 'tell app "Finder" to set ''' '''frontmost of process "Python" to true' ''')) root.mainloop()
def onError(self): box.showerror("Error", "Could not Upadate") def onQuest(self): box.askquestion("Question", "Are you sure to quit?") def onInfo(self): box.showinfo("Information", "Upadate Sucessfully") master = Tk() master.configure(background='#8A002E') img = ImageTk.PhotoImage(Image.open("logo4.jpg")) imglabel = Label(master, image=img).grid(row=0, column=3) master.wm_title("System Configuration") Label(master, background='#8A002E', foreground="white", text="System UserName").grid(row=1, column=0) Label(master, background='#8A002E', foreground="white", text="System Password:"******"white", text="No of Related Subjects:").grid(row=3, column=0) def getUserNm(): tem = [] with open('Config.txt', 'r') as f:
imag, sqrt, abs, log10, concatenate, ) import phringes.backends.sma as sma from phringes.backends.basic import NoCorrelations from phringes.plotting.rtplot import RealTimePlot logging.basicConfig() logger = logging.getLogger() logger.setLevel(logging.INFO) root = Tk() root.iconify() root.wm_title("Correlator Monitor") frame = Frame(root) frame.pack(fill=BOTH, expand=1) correlator = sma.BEE2CorrelatorClient(gethostbyname(gethostname()), 8332) server = sma.SubmillimeterArrayClient('128.171.116.126', 59998) try: server.subscribe(correlator.host, correlator.port) except: pass server.start_correlator() f = arange(-7, 8) corr = RealTimePlot(master=frame, mode='replace', ylim=[-pi, pi], xlim=[f.min(), f.max()]) corr.tkwidget.pack(fill=BOTH, expand=1)
class imsi_mon_demo(object): def __init__(self): self.imsi_mon_str = '/opt/nokiasiemens/bin/dmxsendcli --unit auto -h *,0102,054f,0,00,04,00,2b24 -b' self.imsi_list = imsi_list() self.imsi_mon_start = imsi_mon_start(self.imsi_list) self.imsi_val_1_row = 0 self.imsi_val_2_row = self.imsi_val_1_row + 1 self.imsi_val_3_row = self.imsi_val_2_row + 1 self.imsi_val_4_row = self.imsi_val_3_row + 1 self.imsi_val_5_row = self.imsi_val_4_row + 1 self.imsi_val_6_row = self.imsi_val_5_row + 1 self.imsi_val_7_row = self.imsi_val_6_row + 1 self.imsi_val_8_row = self.imsi_val_7_row + 1 self.imsi_val_9_row = self.imsi_val_8_row + 1 self.imsi_val_10_row = self.imsi_val_9_row + 1 self.imsi_val_11_row = self.imsi_val_10_row + 1 self.imsi_val_12_row = self.imsi_val_11_row + 1 self.imsi_val_13_row = self.imsi_val_12_row + 1 self.imsi_val_14_row = self.imsi_val_13_row + 1 self.imsi_val_15_row = self.imsi_val_14_row + 1 self.imsi_val_16_row = self.imsi_val_15_row + 1 self.dmx_output_row = self.imsi_val_15_row + 3 self.root = Tk() self.root.wm_title("IMSI List notify") # valid percent substitutions (from the Tk entry man page) # %d = Type of action (1=insert, 0=delete, -1 for others) # %i = index of char string to be inserted/deleted, or -1 # %P = value of the entry if the edit is allowed # %s = value of entry prior to editing # %S = the text string being inserted or deleted, if any # %v = the type of validation that is currently set # %V = the type of validation that triggered the callback # (key, focusin, focusout, forced) # %W = the tk name of the widget vcmd = (self.root.register(self.OnValidate), '%d', '%i', '%P', '%s', '%S', '%v', '%V', '%W') self.label_imsi_val_1 = Label (self.root, text= "imsi_val[0]") self.label_imsi_val_1.grid(row=self.imsi_val_1_row) self.imsi_val_1_text = StringVar() # self.imsi_val_1_text.set('ffff') Entry(self.root, textvariable=self.imsi_val_1_text, validate="key", validatecommand=vcmd).grid(row=0, column=1) self.label_imsi_val_2 = Label (self.root, text= "imsi_val[1]") self.label_imsi_val_2.grid(row=self.imsi_val_2_row) self.imsi_val_2_text = StringVar() Entry(self.root, textvariable=self.imsi_val_2_text, validate="key", validatecommand=vcmd).grid(row=1, column=1) self.label_imsi_val_3 = Label (self.root, text= "imsi_val[2]") self.label_imsi_val_3.grid(row=self.imsi_val_3_row) self.imsi_val_3_text = StringVar() Entry(self.root, textvariable=self.imsi_val_3_text, validate="key", validatecommand=vcmd).grid(row=2, column=1) self.label_imsi_val_4 = Label (self.root, text= "imsi_val[3]") self.label_imsi_val_4.grid(row=self.imsi_val_4_row) self.imsi_val_4_text = StringVar() Entry(self.root, textvariable=self.imsi_val_4_text, validate="key", validatecommand=vcmd).grid(row=3, column=1) self.label_imsi_val_5 = Label (self.root, text= "imsi_val[4]") self.label_imsi_val_5.grid(row=self.imsi_val_5_row) self.imsi_val_5_text = StringVar() Entry(self.root, textvariable=self.imsi_val_5_text, validate="key", validatecommand=vcmd).grid(row=4, column=1) self.label_imsi_val_6 = Label (self.root, text= "imsi_val[5]") self.label_imsi_val_6.grid(row=self.imsi_val_6_row) self.imsi_val_6_text = StringVar() Entry(self.root, textvariable=self.imsi_val_6_text, validate="key", validatecommand=vcmd).grid(row=5, column=1) self.label_imsi_val_7 = Label (self.root, text= "imsi_val[6]") self.label_imsi_val_7.grid(row=self.imsi_val_7_row) self.imsi_val_7_text = StringVar() Entry(self.root, textvariable=self.imsi_val_7_text, validate="key", validatecommand=vcmd).grid(row=6, column=1) self.label_imsi_val_8 = Label (self.root, text= "imsi_val[7]") self.label_imsi_val_8.grid(row=self.imsi_val_8_row) self.imsi_val_8_text = StringVar() Entry(self.root, textvariable=self.imsi_val_8_text, validate="key", validatecommand=vcmd).grid(row=7, column=1) self.label_imsi_val_9 = Label (self.root, text= "imsi_val[8]") self.label_imsi_val_9.grid(row=self.imsi_val_9_row) self.imsi_val_9_text = StringVar() # self.imsi_val_1_text.set('ffff') Entry(self.root, textvariable=self.imsi_val_9_text, validate="key", validatecommand=vcmd).grid(row=8, column=1) self.label_imsi_val_10 = Label (self.root, text= "imsi_val[9]") self.label_imsi_val_10.grid(row=self.imsi_val_10_row) self.imsi_val_10_text = StringVar() Entry(self.root, textvariable=self.imsi_val_10_text, validate="key", validatecommand=vcmd).grid(row=9, column=1) self.label_imsi_val_11 = Label (self.root, text= "imsi_val[10]") self.label_imsi_val_11.grid(row=self.imsi_val_11_row) self.imsi_val_11_text = StringVar() Entry(self.root, textvariable=self.imsi_val_11_text, validate="key", validatecommand=vcmd).grid(row=10, column=1) self.label_imsi_val_12 = Label (self.root, text= "imsi_val[11]") self.label_imsi_val_12.grid(row=self.imsi_val_12_row) self.imsi_val_12_text = StringVar() Entry(self.root, textvariable=self.imsi_val_12_text, validate="key", validatecommand=vcmd).grid(row=11, column=1) self.label_imsi_val_13 = Label (self.root, text= "imsi_val[12]") self.label_imsi_val_13.grid(row=self.imsi_val_13_row) self.imsi_val_13_text = StringVar() Entry(self.root, textvariable=self.imsi_val_13_text, validate="key", validatecommand=vcmd).grid(row=12, column=1) self.label_imsi_val_14 = Label (self.root, text= "imsi_val[13]") self.label_imsi_val_14.grid(row=self.imsi_val_14_row) self.imsi_val_14_text = StringVar() Entry(self.root, textvariable=self.imsi_val_14_text, validate="key", validatecommand=vcmd).grid(row=13, column=1) self.label_imsi_val_15 = Label (self.root, text= "imsi_val[14]") self.label_imsi_val_15.grid(row=self.imsi_val_15_row) self.imsi_val_15_text = StringVar() Entry(self.root, textvariable=self.imsi_val_15_text, validate="key", validatecommand=vcmd).grid(row=14, column=1) self.label_imsi_val_16 = Label (self.root, text= "imsi_val[15]") self.label_imsi_val_16.grid(row=self.imsi_val_16_row) self.imsi_val_16_text = StringVar() Entry(self.root, textvariable=self.imsi_val_16_text, validate="key", validatecommand=vcmd).grid(row=15, column=1) self.buttontext = StringVar() self.buttontext.set("Send") Button(self.root, textvariable=self.buttontext, command=self.send_handler).grid(row=16) self.root.mainloop() def get_imsi_mon_str(self): self.imsi_mon_str += ' ' + self.imsi_mon_start.get_imsi_mon_start_str() return self.imsi_mon_str def reset_all_internal_str(self): self.imsi_mon_str = '/opt/nokiasiemens/bin/dmxsendcli --unit auto -h *,0102,054f,0,00,04,00,2b24 -b' self.imsi_list = imsi_list() self.imsi_mon_start = imsi_mon_start(self.imsi_list) def gen_imsi_list(self): in_imsi_0 = self.imsi_val_1_text.get() in_imsi_1 = self.imsi_val_2_text.get() in_imsi_2 = self.imsi_val_3_text.get() in_imsi_3 = self.imsi_val_4_text.get() in_imsi_4 = self.imsi_val_5_text.get() in_imsi_5 = self.imsi_val_6_text.get() in_imsi_6 = self.imsi_val_7_text.get() in_imsi_7 = self.imsi_val_8_text.get() in_imsi_8 = self.imsi_val_9_text.get() in_imsi_9 = self.imsi_val_10_text.get() in_imsi_10 = self.imsi_val_11_text.get() in_imsi_11 = self.imsi_val_12_text.get() in_imsi_12 = self.imsi_val_13_text.get() in_imsi_13 = self.imsi_val_14_text.get() in_imsi_14 = self.imsi_val_15_text.get() in_imsi_15 = self.imsi_val_16_text.get() imsi_mon_dir_0 = '3' imsi_mon_dir_1 = '00' imsi_mon_dir_2 = '00' imsi_mon_dir_3 = '00' imsi_mon_dir_4 = '00' imsi_mon_dir_5 = '00' imsi_mon_dir_6 = '00' imsi_mon_dir_7 = '00' imsi_mon_dir_8 = '00' imsi_mon_dir_9 = '00' imsi_mon_dir_10 = '00' imsi_mon_dir_11 = '00' imsi_mon_dir_12 = '00' imsi_mon_dir_13 = '00' imsi_mon_dir_14 = '00' imsi_mon_dir_15 = '00' imsi_0 = imsi(in_imsi_0, imsi_mon_dir_0) imsi_1 = imsi(in_imsi_1, imsi_mon_dir_1) imsi_2 = imsi(in_imsi_2, imsi_mon_dir_2) imsi_3 = imsi(in_imsi_3, imsi_mon_dir_3) imsi_4 = imsi(in_imsi_4, imsi_mon_dir_4) imsi_5 = imsi(in_imsi_5, imsi_mon_dir_5) imsi_6 = imsi(in_imsi_6, imsi_mon_dir_6) imsi_7 = imsi(in_imsi_7, imsi_mon_dir_7) imsi_8 = imsi(in_imsi_8, imsi_mon_dir_8) imsi_9 = imsi(in_imsi_9, imsi_mon_dir_9) imsi_10 = imsi(in_imsi_10, imsi_mon_dir_10) imsi_11 = imsi(in_imsi_11, imsi_mon_dir_11) imsi_12 = imsi(in_imsi_12, imsi_mon_dir_12) imsi_13 = imsi(in_imsi_13, imsi_mon_dir_13) imsi_14 = imsi(in_imsi_14, imsi_mon_dir_14) imsi_15 = imsi(in_imsi_15, imsi_mon_dir_15) self.imsi_list.add_imsi(imsi_0) self.imsi_list.add_imsi(imsi_1) self.imsi_list.add_imsi(imsi_2) self.imsi_list.add_imsi(imsi_3) self.imsi_list.add_imsi(imsi_4) self.imsi_list.add_imsi(imsi_5) self.imsi_list.add_imsi(imsi_6) self.imsi_list.add_imsi(imsi_7) self.imsi_list.add_imsi(imsi_8) self.imsi_list.add_imsi(imsi_9) self.imsi_list.add_imsi(imsi_10) self.imsi_list.add_imsi(imsi_11) self.imsi_list.add_imsi(imsi_12) self.imsi_list.add_imsi(imsi_13) self.imsi_list.add_imsi(imsi_14) self.imsi_list.add_imsi(imsi_15) def send_handler(self): self.reset_all_internal_str() self.gen_imsi_list() text_height = 8 text = Text(self.root, height=text_height) text.insert(1.0, self.get_imsi_mon_str()) text.grid(row=self.dmx_output_row) bcn_501_ip = '10.56.116.8' client = paramiko.SSHClient() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(bcn_501_ip, 22, username='******', password='******', timeout=4) stdin, stdout, stderr = client.exec_command(self.imsi_mon_str) for std in stdout.readlines(): print std, client.close() def OnValidate(self, d, i, P, s, S, v, V, W): # print "OnValidate:" # print "d='%s'" % d # print "i='%s'" % i # print "P='%s'" % P # print "s='%s'" % s # print "S='%s'" % S # print "v='%s'" % v # print "V='%s'" % V # print "W='%s'" % W return ((len(s)<=14) & (S>='0') & (S <= '9'))