class searchDialog(Toplevel): def __init__(self, parent, title): self.top = Toplevel(parent) self.top.wm_title(title) self.top.wm_minsize(width=300, height=400) self.top.bind("<Return>", self.searchThreader) self.top.bind("<Escape>", self.close) self.searchy = Text(self.top) self.searchy.config(wrap=WORD) self.search_entry = Entry(self.top) self.close = Button(self.top, text="Close", command=self.close) self.search_button = Button(self.top, text="Search", command=self.searchThreader) self.scrollbar = Scrollbar(self.top) self.scrollbar.pack(side=RIGHT, fill=Y, expand=0) self.searchy.config(yscrollcommand=self.scrollbar.set, state=DISABLED) self.searchy.pack(side=TOP, fill=BOTH, expand=1) self.search_entry.pack(side=LEFT, fill=X, expand=1) self.close.pack(side=RIGHT, fill=BOTH, expand=0) self.search_button.pack(side=RIGHT, fill=BOTH, expand=0) self.linker = HyperlinkManager(self.searchy) def close(self, event=None): global SEARCH SEARCH = None self.top.destroy() def putText(self, text): updateDisplay(text, self.searchy, self.linker) def clearSearch(self): self.searchy.config(state=NORMAL) self.searchy.delete(1.0, END) self.searchy.config(state=DISABLED) def searchThreader(self, event=None, text=None): self.sear = upThread(6, 'search', (self, text)) self.sear.start() def search(self, toSearch=None): if toSearch is None: keyword = self.search_entry.get() self.search_entry.delete(0, END) else: keyword = toSearch self.clearSearch() self.top.wm_title("Search - " + keyword) if keyword.split('@')[0] == '': self.putText( API.GetUserTimeline( screen_name=keyword.split('@')[1] ) ) else: self.putText(API.GetSearch(term=keyword))
def destroy(self): registry.delete(self) Toplevel.destroy(self) # If this is Idle's last window then quit the mainloop # (Needed for clean exit on Windows 98) if not registry.dict: self.quit()
class Reminder_Window(): def start_window(self): self.reminder_window = Toplevel() self.reminder_window.grab_set() self.reminder_window.title('Reminder') self.reminder_window.geometry('400x200') big_font = tkFont.Font(size=10) self.reminder_text_1 = Tkinter.Label(self.reminder_window, text='Remind me', font=big_font) self.reminder_text_2 = Tkinter.Label(self.reminder_window, \ text='day(s) before.', font=big_font) self.reminder_entry = Tkinter.Entry(self.reminder_window, width=3) self.ok_reminder_button = Tkinter.Button(self.reminder_window, text='OK', command=self.on_ok_button_press) self.back_reminder_button = Tkinter.Button(self.reminder_window, \ text='Back', command=self.on_back_button_press) self.reminder_text_1.place(x=x_reminder_text_1_location, \ y=y_reminder_texts_location) self.reminder_text_2.place(x=x_reminder_text_2_location, \ y=y_reminder_texts_location) self.reminder_entry.place(x=x_reminder_entry_location, \ y=y_reminder_entry_location) self.ok_reminder_button.place(x=x_ok_reminder_button_location, \ y=y_ok_back_reminder_button_locations) self.back_reminder_button.place(x=x_back_reminder_button_location, \ y=y_ok_back_reminder_button_locations) self.reminder_window.mainloop() def on_ok_button_press(self): entry_reminder_value = self.reminder_entry.get() try: int_entry_reminder_value = int(entry_reminder_value) #print 0 > int_entry_reminder_value, int_entry_reminder_value < 50 if 0 > int_entry_reminder_value or int_entry_reminder_value > 50: print 'hi' tkMessageBox.showinfo("Error", \ 'Invalid Entry. Please enter a number from 0-50') self.reminder_window.grab_set() self.reminder_window.lift() else: self.num_of_days_before_to_remind_int = int_entry_reminder_value self.reminder_window.destroy() except ValueError: tkMessageBox.showinfo("Error", \ 'Invalid Entry. Please enter a number from 0-50') self.reminder_window.grab_set() self.reminder_window.lift() def on_back_button_press(self): self.num_of_days_before_to_remind_int = 0 self.reminder_window.destroy()
def startAdvCnf_tk(self): """ open advnaced config window """ top = Toplevel(name='advCnfTop') app = AdvCnf_tk(self, top) app.mainloop() # please destroy me or I'll continue to run in background top.destroy()
class SplashScreen: root = None win = None img = 'images/splash-screen' flag = 0 def __init__(self, root): self.root = root self.width = 500 self.height = 300 self.flag = config.preferences.show_splash def show(self): self.root.withdraw() if self.flag: img_file = os.path.join(app.config.sk_share_dir, self.img + '.png') from sk1sdk.tkpng import load_icon load_icon(self.root, img_file, self.img) scrnWt = self.root.winfo_screenwidth() scrnHt = self.root.winfo_screenheight() winXPos = (scrnWt / 2) - (self.width / 2) winYPos = (scrnHt / 2) - (self.height / 2) self.win = Toplevel() self.win.overrideredirect(1) self.win.configure(background='black') self.banner = Label(self.win, image=self.img, cursor='watch', borderwidth=0) self.banner.pack() self.verlb = Label(self.win, text='version %s' % (config.version, ), bg='white') self.verlb.place(x=10, y=240) self.verlb['font'] += ' bold' self.txtlb = Label(self.win, text='Start...', bg='white') self.txtlb.place(x=10, y=265) self.progress_bar = SS_ProgressBar(self.win) self.progress_bar.pack(fill=X, side=TOP) geom = (self.width, self.height, winXPos, winYPos) self.win.geometry('%dx%d+%d+%d' % geom) self.win.update() def hide(self): if self.flag and self.win: self.win.withdraw() self.win.destroy() def set_val(self, val, txt=''): self.progress_bar.set_val(val) if txt: self.txtlb['text'] = txt self.win.update()
class SplashScreen: root = None win = None img = 'images/splash-screen' flag = 0 def __init__(self, root): self.root = root self.width = 500 self.height = 300 self.flag = config.preferences.show_splash def show(self): self.root.withdraw() if self.flag: img_file = os.path.join(app.config.sk_share_dir, self.img + '.png') from sk1sdk.tkpng import load_icon load_icon(self.root, img_file, self.img) scrnWt = self.root.winfo_screenwidth() scrnHt = self.root.winfo_screenheight() winXPos = (scrnWt / 2) - (self.width / 2) winYPos = (scrnHt / 2) - (self.height / 2) self.win = Toplevel() self.win.overrideredirect(1) self.win.configure(background='black') self.banner = Label(self.win, image=self.img, cursor='watch', borderwidth=0) self.banner.pack() self.verlb = Label(self.win, text='version %s' % (config.version,), bg='white') self.verlb.place(x=10, y=240) self.verlb['font'] += ' bold' self.txtlb = Label(self.win, text='Start...', bg='white') self.txtlb.place(x=10, y=265) self.progress_bar = SS_ProgressBar(self.win) self.progress_bar.pack(fill=X, side=TOP) geom = (self.width, self.height, winXPos, winYPos) self.win.geometry('%dx%d+%d+%d' % geom) self.win.update() def hide(self): if self.flag and self.win: self.win.withdraw() self.win.destroy() def set_val(self, val, txt=''): self.progress_bar.set_val(val) if txt: self.txtlb['text'] = txt self.win.update()
class HelpWindow(object): def __init__(self,master, title): self.top=Toplevel(master) self.value = '' self.top.geometry("300x300+300+300") self.l=Label(self.top,text=title) self.l.pack() self.b=Button(self.top,text='Ok',command=self.cleanup) self.b.pack() self.b.focus() def cleanup(self): self.top.destroy()
class RobView(View): GUI_WIDTH = 800 GUI_HEIGHT = 400 def __init__(self, tkRoot, app, masterComp, parentNode, logger): BaseView.__init__(self, tkRoot, app, logger) # master (upper level view) component on which this view was issued self.masterComp = masterComp self.parentNode = parentNode self.window = Toplevel(self.tkRoot) self.window.title("%s" % parentNode.keyForIsObject) # self.window.bind("<<close-window>>", self.__onClose) # doesn't work self.window.protocol("WM_DELETE_WINDOW", self.__onClose) text = ScrolledText(self.window, width = RobView.GUI_WIDTH, height = RobView.GUI_HEIGHT, background='white') text.pack(fill = Y) # information from ROB (DataChannel) IS object (criteria results) # .valueOfIsObject is a bit misleading since it's criteria results # checks based on particular values (attributes) within the IS object m = ("ROB '%s':\n\n%s" % (parentNode.keyForIsObject, parentNode.valueOfIsObject)) text.insert(END, m) text.configure(state = DISABLED) # disable edit now, not before insert # need to store this view under full name (not only under # self.masterComp.name as the other views), since there may be # a number of views named e.g. 'DataChannel0' self.app.addActiveView(self.parentNode.keyForIsObject, self) def createContent(self): self.__setWindowGeometry() def __setWindowGeometry(self): offsetX = View.ANOTHER_GUI_OFF * self.app.activeViewsCount() x = conf.GUI_OFF_X + conf.GUI_WIDTH + offsetX geom = "%sx%s+%s+%s" % (RobView.GUI_WIDTH, RobView.GUI_HEIGHT, x, conf.GUI_OFF_Y) self.window.geometry(geom) def __onClose(self): self.app.removeActiveView(self.parentNode.keyForIsObject) self.window.destroy()
class conDialog(Toplevel): def __init__(self, parent, title): self.top = Toplevel(parent) self.top.wm_title(title) self.top.wm_minsize(width=200, height=250) self.parent = parent self.logger = Text(self.top, width=50, height=15) self.logger.pack(fill=BOTH, expand=1) self.logger.config(wrap=WORD) self.close = Button(self.top, text="Close", command=self.close) self.close.pack(fill=X, expand=0) self.close.focus() self.logger.tag_config('backlog', foreground="grey") self.logger.tag_config('ERR', foreground="IndianRed1") for e in range(len(ERR)): if len(ERR[e][1]) > 1: self.logger.insert(INSERT, str(ERR[e][0] + "\n"), ERR[e][1]) else: self.logger.insert(INSERT, str(ERR[e] + '\n'), 'backlog') self.logger.config(state=DISABLED) # destroys this Toplevel widget and sets the CON variable to None def close(self): self.top.destroy() global CON CON = None # method that places the text inside the log thats in the console # also stores the messages in the backlog (ERR) def placeText(self, message): self.logger.config(state=NORMAL) ERR.append(message) if len(message[1]) > 1: self.logger.insert(INSERT, str(message[0] + "\n"), message[1]) else: self.logger.insert(INSERT, message + "\n") self.logger.config(state=DISABLED)
def test_open_and_close(self): # open calls create_widgets, which needs default_command self.dialog.default_command = None toplevel = Toplevel(self.root) text = Text(toplevel) self.dialog.open(text) self.assertEqual(self.dialog.top.state(), 'normal') self.dialog.close() self.assertEqual(self.dialog.top.state(), 'withdrawn') self.dialog.open(text, searchphrase="hello") self.assertEqual(self.dialog.ent.get(), 'hello') toplevel.update_idletasks() toplevel.destroy()
class Tooltip_Helper: """ Class to help show tooltips on Tkinter Canvases. """ def __init__(self, canvas): """ |canvas|: the canvas on which tooltips will be shown. """ self._canvas = canvas self._tip = None def show_tooltip(self, x, y, text, background=TOOLTIP_BACKGROUND): """ Shows a tooltip containing the given |text| close to the point (|x|, |y|) on the canvas. """ x += self._canvas.winfo_rootx() + 10 y += self._canvas.winfo_rooty() + 10 geometry = '+%d+%d' % (x, y) if not self._tip: self._tip = Toplevel(self._canvas) self._tip.wm_overrideredirect(1) self._tip.wm_geometry(geometry) try: # for Mac OS self._tip.tk.call('::tk::unsupported::MacWindowStyle', 'style', self._tip._w, 'help', 'noActivates') except TclError: pass self.label = Label(self._tip, text=text, justify=LEFT, background=background, relief=SOLID, borderwidth=1, font=DEFAULT_FONT) self.label.pack() else: self._tip.geometry(geometry) self.label.config(text=text, background=background) def hide_tooltip(self): """ Hides the previously added tooltip, if any. """ if self._tip: self._tip.destroy() self._tip = None
class _WorkingDialog: def __init__(self, parent, title, action=None): self.action = action self.top = Toplevel(parent) Label(self.top, text=title).pack() if action: b = Button(self.top, text="Cancel", command=self.cancel) b.pack(pady=5) def cancel(self): self.top.destroy() if self.action: self.action() def __del__(self): self.top.destroy()
def load(): """ Handle the load key on the main window. """ def save_select(): """ Select key hit. Set fname and exit if a field is high-lighted. """ sel = mylist.curselection() if not sel: return fname.append(olist[int(sel[0])]) top.quit() olist = sorted(os.listdir(getdir())) if len(olist) == 0: showwarning('Error', 'No files to load') return top = Toplevel() top.geometry('200x180+800+200') fname = [] top.title('Sudoku Loader') tpart = Frame(top) tpart.pack(side=Tkinter.TOP) bpart = Frame(top) bpart.pack(side=Tkinter.BOTTOM) scrollbar = Scrollbar(tpart) scrollbar.pack(side=Tkinter.RIGHT, fill=Tkinter.Y) mylist = Listbox(tpart, yscrollcommand=scrollbar.set) for line in olist: mylist.insert(Tkinter.END, line) mylist.pack(side=Tkinter.LEFT, fill=Tkinter.BOTH) scrollbar.config(command=mylist.yview) picker = Button(bpart, text='SELECT', command=save_select) picker.pack(pady=5) top.mainloop() if fname: retvec = [] fyle = '%s%s%s' % (getdir(), os.path.sep, fname[0]) top.destroy() with open(fyle, 'r') as infile: inline = infile.readline() while inline: retvec.append(inline.split(':')) inline = infile.readline() return retvec
def new_function(*args, **kwargs): """ Create a queue, create a queuefun from original_function and make the new queuefun the target of a thread, passing the thread target original_function's args and kwargs. Then instantiate a new Tk Toplevel Frame called master and a new waitWidget with the queue and master. Start master's mainloop which exits when the original_function's results are fed to the queue. Destroy master and return the original_function's results. """ queue = Queue.Queue() queuefun = setqueue(original_function, queue) thread = Thread(target=queuefun, args=args, kwargs=kwargs) thread.start() master = Toplevel() waitBox = waitWidget(queue, master) waitBox.mainloop() master.destroy() return queue.get()
class Tooltip_Helper: """ Class to help show tooltips on Tkinter Canvases. """ def __init__(self, canvas): """ |canvas|: the canvas on which tooltips will be shown. """ self._canvas = canvas self._tip = None def show_tooltip(self, x, y, text, background=TOOLTIP_BACKGROUND): """ Shows a tooltip containing the given |text| close to the point (|x|, |y|) on the canvas. """ x += self._canvas.winfo_rootx() + 10 y += self._canvas.winfo_rooty() + 10 geometry = '+%d+%d' % (x, y) if not self._tip: self._tip = Toplevel(self._canvas) self._tip.wm_overrideredirect(1) self._tip.wm_geometry(geometry) try: # for Mac OS self._tip.tk.call('::tk::unsupported::MacWindowStyle', 'style', self._tip._w, 'help', 'noActivates') except TclError: pass self.label = Label(self._tip, text=text, justify=LEFT, background=background, relief=SOLID, borderwidth=1, font=DEFAULT_FONT) self.label.pack() else: self._tip.geometry(geometry) self.label.config(text=text, background=background) def hide_tooltip(self): """ Hides the previously added tooltip, if any. """ if self._tip: self._tip.destroy() self._tip = None
def ask_title_and_create_window(self): toplevel = Toplevel() label = Label(toplevel, text="Title:") label.pack(anchor=W) entry = Entry(toplevel, width=15) entry.pack(anchor=W, fill=X) entry.bind("<Return>", lambda event: (self.new_window(entry.get()), toplevel.destroy())) entry.focus() return "break"
def excel_popup(field): sub_window = Toplevel(background="#333", padx=15, pady=15) sub_window.title("Aya's Finder: Import data from Excel file") sub_window.wm_iconbitmap(r"images\Dna-Helix.ico") row_col = StringVar() row_col.set("row") Radiobutton(sub_window, variable=row_col, value="row", text="Row").grid(row=0, column=0) Radiobutton(sub_window, variable=row_col, value="col", text="Column").grid(row=0, column=1) file_name_var = StringVar() sheet_name_var = StringVar() num_var = IntVar() Label(sub_window, justify="left", width="17", text="File name").grid(row=1, column=0) Label(sub_window, justify="left", width="17", text="Sheet name").grid(row=2, column=0) Label(sub_window, justify="left", width="17", text="Row/Column number").grid(row=3, column=0) Entry(sub_window, width="32", textvariable=file_name_var).grid(row=1, column=1) Entry(sub_window, width="7", textvariable=num_var).grid(row=3, column=1) sheets = OptionMenu(sub_window, sheet_name_var, '') sheets.config(width=32) sheets.grid(row=2, column=1) def get(): file_name = file_name_var.get() sheet_name = sheet_name_var.get() num = num_var.get() try: if row_col.get() == "row": field.delete(1.0, END) field.insert(INSERT, get_from_excel(file_name, sheet_name, row_num=num)) else: field.delete(1.0, END) field.insert(INSERT, get_from_excel(file_name, sheet_name, col_num=num)) sub_window.destroy() except Exception: pass def browser(): try: name = askopenfilename(parent=sub_window) file_name_var.set(name) sheets.set_menu('---', *get_excel_sheets(file_name_var.get())) sub_window.focus() except IOError: pass Button(sub_window, text="OK", command=get).grid(row=5, column=0) Button(sub_window, text="Cancel", command=lambda: sub_window.destroy()).grid(row=5, column=1) Button(sub_window, text="browse", command=browser).grid(row=1, column=3)
def ask_title_and_create_window(self): toplevel = Toplevel() label = Label(toplevel, text="Title:") label.pack(anchor=W) entry = Entry(toplevel, width=15) entry.pack(anchor=W, fill=X) entry.bind( "<Return>", lambda event: (self.new_window(entry.get()), toplevel.destroy())) entry.focus() return "break"
def nuevoPais(self): t = Toplevel(self) t.wm_title("Pais") Label(t, text="Nombre").grid(row=0, column=1) E2 = Entry(t) E2.grid(row=1, column=1) button1 = Button(t, text="Cancelar", command=lambda: t.destroy()) button2 = Button(t, text="Guardar", command=lambda: self.nuevaEntradaPais(E2.get(), t)) button3 = Button(t, text="Borrar", command=lambda: self.BorrarPais(E2.get(), t)) button3.config(state="disabled") button1.grid(row=2, column=0) button2.grid(row=2, column=1) button3.grid(row=2, column=2)
def enter_file(cur_file,label): print(cur_file.get()) def read_file(): try: with open(cur_file.get()) as f: label.config(text=f.read()) fl_enter.destroy() except: label.config(text="No such file") fl_enter=Toplevel(top) qu_butts=[("Read",read_file),("Quit",lambda : fl_enter.destroy())] pack([Button(fl_enter,text=txt,command=f) for txt,f in qu_butts]) pack([Entry(fl_enter,textvariable=cur_file)]) fl_enter.mainloop()
class LBChoice(object): '''This is a listbox for returning projects to be unarchived.''' def __init__(self, list_=None, master=None, title=None): '''Must have master, title is optional, li is too.''' self.master = master if self.master is not None: self.top = Toplevel(self.master) else: return self.v = None if list_ is None or not isinstance(list_, list): self.list = [] else: self.list = list_[:] self.top.transient(self.master) self.top.grab_set() self.top.bind("<Return>", self._choose) self.top.bind("<Escape>", self._cancel) if title: self.top.title(title) lf = Frame(self.top) #Sets up the list. lf.pack(side=TOP) scroll_bar = Scrollbar(lf) scroll_bar.pack(side=RIGHT, fill=Y) self.lb = Listbox(lf, selectmode=SINGLE) self.lb.pack(side=LEFT, fill=Y) scroll_bar.config(command=self.lb.yview) self.lb.config(yscrollcommand=scroll_bar.set) self.list.sort() for item in self.list: self.lb.insert(END, item) #Inserts items into the list. bf = Frame(self.top) bf.pack(side=BOTTOM) Button(bf, text="Select", command=self._choose).pack(side=LEFT) Button(bf, text="New", command=self._new).pack(side=LEFT) Button(bf, text="Cancel", command=self._cancel).pack(side=LEFT) def _choose(self, event=None): try: first = self.lb.curselection()[0] self.v = self.list[int(first)] except IndexError: self.v = None self.top.destroy() def _new(self, event=None): self.v = "NEW" self.top.destroy() def _cancel(self, event=None): self.top.destroy() def return_value(self): self.master.wait_window(self.top) return self.v
class LBChoice(object): '''This is a listbox for returning projects to be unarchived.''' def __init__(self, list_=None, master=None, title=None): '''Must have master, title is optional, li is too.''' self.master = master if self.master is not None: self.top = Toplevel(self.master) else: return self.v = None if list_ is None or not isinstance(list_, list): self.list = [] else: self.list = list_[:] self.top.transient(self.master) self.top.grab_set() self.top.bind("<Return>", self._choose) self.top.bind("<Escape>", self._cancel) if title: self.top.title(title) lf = Frame(self.top) #Sets up the list. lf.pack(side=TOP) scroll_bar = Scrollbar(lf) scroll_bar.pack(side=RIGHT, fill=Y) self.lb = Listbox(lf, selectmode=SINGLE) self.lb.pack(side=LEFT, fill=Y) scroll_bar.config(command=self.lb.yview) self.lb.config(yscrollcommand=scroll_bar.set) self.list.sort() for item in self.list: self.lb.insert(END, item) #Inserts items into the list. bf = Frame(self.top) bf.pack(side=BOTTOM) Button(bf, text="Select", command=self._choose).pack(side=LEFT) Button(bf, text="New", command=self._new).pack(side=LEFT) Button(bf, text="Cancel", command=self._cancel).pack(side=LEFT) def _choose(self, event=None): try: first = self.lb.curselection()[0] self.v = self.list[int(first)] except IndexError: self.v = None self.top.destroy() def _new(self, event=None): self.v = "NEW" self.top.destroy() def _cancel(self, event=None): self.top.destroy() def return_value(self): self.master.wait_window(self.top) return self.v
def editarParroquia(self): t = Toplevel(self) t.wm_title("Estudio") Label(t, text="Nombre").grid(row=0, column=1) E2 = Entry(t) E2.insert(END, self.selectorParroquial.get()) E2.grid(row=1, column=1) nombreOld = self.selectorParroquial.get() button1 = Button(t, text="Cancelar", command=lambda: t.destroy()) button2 = Button(t, text="Guardar", command=lambda: self.actualizarParroquia(nombreOld, E2.get(), t)) button3 = Button(t, text="Borrar", command=lambda: self.BorrarParroquial(E2.get(), t)) button1.grid(row=2, column=0) button2.grid(row=2, column=1) button3.grid(row=2, column=2)
def reset_holidays_gui(self): confirm_top = Toplevel() confirm_top.title("Are you sure you wish to continue?") confirm_top.resizable(0, 0) # Warning to user warning_label = Label(confirm_top, text="WARNING: This will remove all holidays from the application\nAre you sure you wish to continue?") warning_label.grid() buttons = Frame(confirm_top) ok_button = Button(buttons, text="OK", command=lambda: [self.reset(), confirm_top.destroy()]) ok_button.grid(row=0, column=1) cancel_button = Button(buttons, text="Cancel", command=confirm_top.destroy) cancel_button.grid(row=0, column=0) buttons.grid(row=1)
def Winning(self, color): self.someoneWin = True window = Toplevel(self.master, background="#f0e5df") window.attributes('-topmost', True) window.title("we have a winner!") window.geometry("300x200") message = Label(window, text="The winner is \n" + str(color), background="#f0e5df", font=("Courier", 20)) message.place(x=150, y=80, anchor="center") resetButton = Button(window, text="Reset Game", command=lambda: ((self.ResetGame()), (window.destroy()), (self.master.attributes('-topmost', True))), height=2, width=15) resetButton.place(x=150, y=160, anchor="center") center(window)
class MapFrame(Frame): def __init__(self,parent,mapping,active=False,copy=None,*args,**kwargs): Frame.__init__(self,parent,*args,**kwargs) self.active = active self.mapping = mapping self.mapVar = StringVar(self) self.mapVar.trace("w",lambda a,b,c:self.copyMapping()) self.copy = copy self.subsetframes = {} if self.mapping.isEmpty(): title = "No elements to map yet" message = "Please add some elements before mapping." tkMessageBox.showinfo(title,message,parent=self.master) return self.mapButton = Button(self,text="Map",command=self.popUp) self.mapButton.grid() self.grid() def formatKey(self,key): if len(key) > 60: key = key[:21] + '...' + key[-19:] return key def popUp(self): self.pop = Toplevel() self.pop.title("Name mapping") self.frame = Frame(self.pop,padx=5,pady=5) self.listFrame = ScrolledFrame(self.frame) self.similars = self.getSimilarItems() row = 0 Label(self.frame,text="From: ").grid(row=row,column=0,sticky="W") Label(self.frame,text="To: ").grid(row=row,column=2,sticky="W") self.buildList() self.listFrame.grid(sticky='W', row=1,column=0,columnspan=4) Button(self.frame,text="Save",command=self.onSave)\ .grid(sticky='W',row=2,column=0) Label(self.frame,text="Copy From: ").grid(sticky='W',row=2,column=1) OptionMenu(self.frame,self.mapVar,*self.similars.keys()).grid(sticky='W',row=2,column=2) self.frame.pack() self.frame.update() def getSimilarItems(self): ret = {"":None} if self.copy: ret = dict([(str(i),i) for i in self.mapping.getCopySources()]) return ret def buildList(self): c = 0 for i,key in enumerate(self.mapping.keys()): Label(self.listFrame.interior(),text=self.formatKey(key))\ .grid(row=i+c,column=0,pady=1,padx=3) ssf = SubsetFrame(self.listFrame.interior(),self.mapping.getSubset(key),limit=1) self.subsetframes[key] = ssf ssf.grid(sticky="w",row=i,column=1) def onSave(self): self.pop.destroy() for key,ssf in self.subsetframes.items(): self.mapping[key] = ssf.subset chimera.triggers.activateTrigger('configUpdated', None) def copyMapping(self): copyFrom = self.similars[self.mapVar.get()].mapping self.mapping.copyFrom(copyFrom) self.buildList()
class KeyboardEntry: """Mixin class that can be used to add the ability to type values for widget. When the cursor enters the widget the focus is set to the widget and the widget that had the focus previousy is saved in .lastFocus. When the cursor leaves the widget focus is restored to self.lastFocus. key_cb(event) is called upon KeyRelease events. If this is the first keytroke an undecorated window is created next to the cursor and handleKeyStroke(event) is called. This method should be subclassed to modify the way the string is typed in (see thumbwheel.py for an example of handling numbers only). When the Return key is pressed, the entry window is destroyed and if the typed striong is not empty self.callSet(self.typedValue) is called. If the cursor moves out of the widget before Rrturn is pressed the value in the entry window is discarded and the entry window is destroyed. """ def __init__(self, widgets, callSet): # callSet is a function taking one argument (string) which will be # when the Returnm key is hit (if the typed string is not empty) # widgets is a list of Tkinter wigets for which <Enter>, <Leave> # <Return> and <KeyRelease> are handled. These widgets has to exist # before thsi constructor can be called assert callable(callSet) self.callSet = callSet for w in widgets: w.bind("<Enter>", self.enter_cb) w.bind("<Leave>", self.leave_cb) w.bind("<Return>", self.return_cb) w.bind("<KeyRelease>", self.key_cb) self.typedValue = '' # string accumulating valuescharacters typed self.lastFocus = None # widget to which the focus will be restored # when the mouse leaves the widget self.topEntry = None # top level for typing values self.typedValueTK = None #Tk label used as entry for value def key_cb(self, event=None): # call back function for keyboard events (except for Return) # handle numbers to set value key = event.keysym if key == 'Return': return #print 'Key:', key if len(self.typedValue) == 0 and self.topEntry is None: # create Tk label showing typed value x = event.x y = event.y #print 'create entry' self.topEntry = Toplevel() self.topEntry.overrideredirect(1) w = event.widget if event.x >= 0: self.topEntry.geometry('+%d+%d' % (w.winfo_rootx() + event.x + 10, w.winfo_rooty() + event.y)) else: self.topEntry.geometry('+%d+%d' % (w.winfo_rootx() + 10, w.winfo_rooty())) self.typedValueTK = Label(master=self.topEntry, text='', relief='sunken', bg='yellow') self.typedValueTK.pack() self.handleKeyStroke(event) def leave_cb(self, event=None): # make sure widget gets keyboard events # print 'leave', event.widget if self.topEntry: self.typedValueTK.destroy() self.topEntry.destroy() self.topEntry = None self.typedValue = '' if self.lastFocus: #print 'restoring focus' if widgetsOnBackWindowsCanGrabFocus is False: lActiveWindow = self.lastFocus.focus_get() if lActiveWindow is not None \ and ( lActiveWindow.winfo_toplevel() != self.lastFocus.winfo_toplevel() ): return self.lastFocus.focus_set() self.lastFocus = None event.widget.config(cursor='') def enter_cb(self, event=None): # make sure widget gets keyboard events #print 'enter', event.widget if widgetsOnBackWindowsCanGrabFocus is False: lActiveWindow = event.widget.focus_get() if lActiveWindow is not None \ and ( lActiveWindow.winfo_toplevel() != event.widget.winfo_toplevel() ): return if self.lastFocus is None: #print 'setting focus' self.lastFocus = self.focus_lastfor() event.widget.focus_set() event.widget.config(cursor='xterm') def return_cb(self, event): # return should destroy the topEntry #print "return_cb" if self.typedValueTK is not None: self.typedValueTK.destroy() if self.topEntry is not None: self.topEntry.destroy() self.topEntry = None if len(self.typedValue): #print 'setting to', self.type(self.typedValue) self.callSet(self.typedValue) self.typedValue = '' ## TO BE SUBCLASSED def handleKeyStroke(self, event): # by default we handle delete character keys key = event.keysym if key == 'BackSpace' or key == 'Delete': self.typedValue = self.typedValue[:-1] self.typedValueTK.configure(text=self.typedValue)
class AboutPopUp(): ''' there is a lot of work to do here also, but is a quite good and functional starting point... first put as child of Toplevel then change to grid ''' def __init__(self, **kwargs): ''' (under development)''' master = None title = 'AboutPopUp' licence = None if 'master' in kwargs.keys(): master = kwargs['master'] if 'title' in kwargs.keys(): title = kwargs['title'] if 'licence' in kwargs.keys(): licence = kwargs['licence'] self.im_smlogo = PhotoImage(file="./lib/gui/img/small_logo2.ppm") self.im_logo2 = PhotoImage(file="./lib/gui/img/logo2.ppm") self.master = master self._title_ = title self._licence_ = licence self.set_self_vertex() self.create_content() def set_self_vertex(self): ws, hs, w_main, h_main, x_main, y_main = self.master.MAINVERTEX # calculate the greatness w_pop = w_main h_pop = h_main * 14 / 21 x_pop = x_main + w_main + 30 y_pop = y_main + h_main - h_pop - 140 #print w_pop, h_pop, x_pop, y_pop self._vertex_ = [w_pop, h_pop, x_pop, y_pop] def create_content(self): self.pop = Toplevel(self.master, bg="white") self.pop.grab_set() # when you show the popup self.pop.wm_title(' ' * 5 + self._title_) self.pop.geometry('{:d}x{:d}+{:d}+{:d}'.format(*self._vertex_)) leftcolumn = Frame(self.pop, bg="white") Label(leftcolumn, bg="white").pack(side="top", fill="both", pady=30) Label(leftcolumn, bg="white", image=self.im_logo2).pack(side="top", fill="both", padx=10) #side= LEFT, leftcolumn.pack(side="left", fill='both', padx=1) rightcolumn = Frame(self.pop, bg="white") firstrow = Frame(rightcolumn, bg="white") Frame(rightcolumn, bg="white").pack(side="top", pady=10, padx=0) Label(firstrow, text="GROTOLAM", fg="Gray13", bg="white", font="Verdana 13 bold").pack(side="left", pady=20) Label(firstrow, text='', bg="white").pack(side="left", padx=40) firstrow.pack(side="top", padx=0) secrow = Frame(rightcolumn, bg="white") Label(secrow, text="v " + __version__.split()[2], fg="Gray13", bg="white", font="Verdana 10").pack(side="left") Label(secrow, text='', bg="white").pack(side="left", padx=75) secrow.pack(side="top", padx=0) # lets create space to do some stuff ... Frame(rightcolumn, bg="white").pack(side="top", pady=20, padx=0) thirdrow = Frame(rightcolumn, bg="white") Label(thirdrow, text="2018 Python version by", fg="Gray13", bg="white", font="Verdana 10").pack(side="left") Label(thirdrow, text='', bg="white").pack(side="left", padx=16) thirdrow.pack(side="top", padx=0) fourthrow = Frame(rightcolumn, bg="white") Label(fourthrow, text="Hernan Chavez Thielemann", fg="Gray13", bg="white", font="Verdana 10").pack(side="left") Label(fourthrow, text='', bg="white").pack(side="left", padx=1) fourthrow.pack(side="top", padx=0) fifthrow = Frame(rightcolumn, bg="white") Label(fifthrow, bg="white", image=self.im_smlogo).pack(side="left", fill="both", padx=10) fifthrow.pack(side="top", padx=0) sixthrow = Frame(rightcolumn, bg="white") href = Label(sixthrow, bg="white", font="Verdana 10", text="Small web page", fg="blue", cursor="hand2") f = Font(href, href.cget("font")) f.configure(underline=True) href.configure(font=f) href.pack(side="left") href.bind("<Button-1>", self.callback) Label(sixthrow, text='', bg="white").pack(side="left", padx=40) sixthrow.pack(side="top", padx=0) lastrow = Frame(rightcolumn, bg="white") self.bottom_button_row(lastrow) rightcolumn.pack(side="right", fill='both', padx=5) def callback(self, event): open_new(r"http://www.polito.it/small") def bottom_button_row(self, _row_): b2 = Button(_row_, text='Close', bg="white", command=self.exit_pop) b2.pack(side="right", padx=10, pady=4) b1 = Button(_row_, text='Licence', bg="white", command=self._licence_) b1.pack(side="right", padx=10, pady=20) _row_.pack(side="bottom") def openlicence(self): print 'opening licence file' def exit_pop(self): self.pop.grab_release() # to return to normal self.pop.destroy()
def help_about(self): """Shows an 'about' modal dialog. Callback method called by tk. """ about_win = Toplevel(self.root) # Set up dialog lbl = Label(about_win, text="Video Poker") lbl.grid(row=0, column=0, padx=10, pady=(10, 0), sticky=W + N) lbl = Label(about_win, text="by Paul Griffiths") lbl.grid(row=1, column=0, padx=10, pady=(0, 7), sticky=W + N) lbl = Label(about_win, text="Written in Python, with tkinter.") lbl.grid(row=2, column=0, padx=10, pady=7, sticky=W + N) lbl = Label(about_win, text="Copyright 2013 Paul Griffiths") lbl.grid(row=4, column=0, padx=10, pady=(7, 0), sticky=W + N) lbl = Label(about_win, text="Email: [email protected]") lbl.grid(row=5, column=0, padx=10, pady=(0, 21), sticky=W + N) lbl = Label(about_win, text="This program is free software: you can " + "redistribute it and/or modify it under the terms") lbl.grid(row=6, column=0, columnspan=2, padx=10, pady=0, sticky=W + N) lbl = Label(about_win, text="of the GNU General Public License as " + "published by the Free Software Foundation, either") lbl.grid(row=7, column=0, columnspan=2, padx=10, pady=(0, 0), sticky=W + N) lbl = Label(about_win, text="version 3 of the License, or " + "(at your option) any later version.") lbl.grid(row=8, column=0, columnspan=2, padx=10, pady=(0, 21), sticky=W + N) lbl = Label(about_win, text="This program is distributed in " + "the hope that it will be useful, but WITHOUT ANY WARRANTY;") lbl.grid(row=9, column=0, columnspan=2, padx=10, pady=0, sticky=W + N) lbl = Label(about_win, text="without even the implied " + "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR") lbl.grid(row=10, column=0, columnspan=2, padx=10, pady=(0, 0), sticky=W + N) lbl = Label(about_win, text="PURPOSE. See the " + "GNU General Public License for more details.") lbl.grid(row=11, column=0, columnspan=2, padx=10, pady=(0, 21), sticky=W + N) lbl = Label(about_win, text="You should have received a " + "copy of the GNU General Public License along with this") lbl.grid(row=12, column=0, columnspan=2, padx=10, pady=(0, 0), sticky=W + N) lbl = Label(about_win, text="program. If not, see " + "<http://www.gnu.org/licenses/>.") lbl.grid(row=13, column=0, columnspan=2, padx=10, pady=(0, 21), sticky=W + N) img = PhotoImage(file="{0}27.gif".format(self.gifdir)) lbl = Label(about_win, image=img) lbl.grid(row=0, column=1, rowspan=5, padx=10, pady=10, sticky=N + E) btn = Button(about_win, text="OK", command=about_win.quit) btn.grid(row=14, column=0, columnspan=2, padx=0, pady=(0, 10), ipadx=30, ipady=3) # Show dialog about_win.transient(self.root) about_win.parent = self.root about_win.protocol("WM_DELETE_WINDOW", about_win.destroy) about_win.geometry("+{0}+{1}".format(self.root.winfo_rootx() + 50, self.root.winfo_rooty() + 50)) about_win.title("About Video Poker") about_win.focus_set() about_win.grab_set() about_win.mainloop() about_win.destroy()
def destroy(self): for sp in self.scale_plots: sp.destroy() return Toplevel.destroy(self)
class StockClass: """ Interface for stock entry. """ def __init__(self, master): """ Create, pack, and bind entry boxes and buttons for stock entry. """ self.master = master self.frame = ttk.Frame(self.master) self.master.title("Williams Chemicals - Update Stock Records") # instructions self.instructionFrame = ttk.Frame(self.master) self.instructionFrame.pack() ttk.Label(self.instructionFrame, text="Enter the Medicine information below") \ .pack(pady=20) # entry boxes and column headers self.entryFrame = ttk.Frame(self.master) self.entryFrame.pack(padx=10) # column headings self.col1 = ttk.Label(self.entryFrame, text="Drug Name") self.col1.grid(row=0, column=0) self.col2 = ttk.Label(self.entryFrame, text="Quantity") self.col2.grid(row=0, column=1) self.col3 = ttk.Label(self.entryFrame, text="Price") self.col3.grid(row=0, column=2) self.col4 = ttk.Label(self.entryFrame, text="Total") self.col4.grid(row=0, column=3) self.col5 = ttk.Label(self.entryFrame, text="Expiring Date") self.col5.grid(row=0, column=4) self.col6 = ttk.Label(self.entryFrame, text="Category") self.col6.grid(row=0, column=5) # entry boxes self.drugBox = ttk.Entry(self.entryFrame, name="drug") self.drugBox.grid(row=1, column=0) self.qtyBox = ttk.Entry(self.entryFrame, name="qty") self.qtyBox.grid(row=1, column=1) self.priceBox = ttk.Entry(self.entryFrame, name="price") self.priceBox.grid(row=1, column=2) self.totalBox = ttk.Entry(self.entryFrame, name="total") self.totalBox.grid(row=1, column=3) self.expDateBox = ttk.Entry(self.entryFrame, name="expDate") self.expDateBox.grid(row=1, column=4) self.categoryBox = ttk.Entry(self.entryFrame, name="category") self.categoryBox.grid(row=1, column=5) # drug entry buttons self.entryBtnFrame = ttk.Frame(self.master) self.entryBtnFrame.pack() self.newEntryBtn = ttk.Button(self.entryBtnFrame, text="Enter Drug", command=self.add_stock) self.newEntryBtn.pack(side=LEFT) # Imported quit button Quitter(self.entryBtnFrame).pack(side=LEFT) ######################################################################### # CURRENT STOCK DISPLAY # ######################################################################### # title heading self.frameHeading = ttk.Frame(self.master) self.frameHeadingTitle = ttk.Label(self.frameHeading, text="Current Stock", font=("Arial", "12", "bold")) self.frameHeading.pack() self.frameHeadingTitle.pack(pady=10) # database to output here self.showInventoryFrame = ttk.Frame(self.master) self.showInventoryFrame.pack(expand=1, fill=BOTH, padx=10, pady=10) # imported table-like multi list box self.listBox = MultiListbox(self.showInventoryFrame, (("Drug Name", 30), ("Quantity", 10), ("Price", 10), ("Total", 10), ("Expiring Date", 15), ("Category", 40))) self.listBox.pack(expand=1, fill=BOTH) # stock display buttons self.inventoryBtnFrame = ttk.Frame(self.master) self.inventoryBtnFrame.pack(fill=BOTH, padx=10, pady=20) self.fetchStock = ttk.Button(self.inventoryBtnFrame, text="Fetch Inventory", command=self.get_inven) self.fetchStock.pack(side=RIGHT) self.updateStock = ttk.Button(self.inventoryBtnFrame, text="Update Medicine", command=self.change_inven) self.updateStock.pack(side=RIGHT) self.deleteInven = ttk.Button(self.inventoryBtnFrame, text="Delete Entry", command=self.clear_entry) self.deleteInven.pack(side=RIGHT) self.clearInven = ttk.Button(self.inventoryBtnFrame, text="Clear Inventory", command=self.del_inven) self.clearInven.pack(side=RIGHT) #refresh list self.get_inven() def add_stock(self): # new_cat = ["%s," % self.categoryBox.get()] new_cat = self.categoryBox.get() record = (self.drugBox.get(), self.qtyBox.get(), self.priceBox.get(), self.totalBox.get(), self.expDateBox.get(), new_cat,) sql.session.insert_drug(record) # clear the entry boxes to prepare them for new data self.drugBox.delete(0, END) self.qtyBox.delete(0, END) self.priceBox.delete(0, END) self.totalBox.delete(0, END) self.expDateBox.delete(0, END) self.categoryBox.delete(0, END) # refresh the list self.get_inven() def get_inven(self): stock = sql.session.get_all() # print stock self.listBox.delete(0, END) self.update_listbox(stock) def update_listbox(self, db_table): for row in db_table: self.listBox.insert(END, (row[0], int(row[1]), float(row[2]), int(row[3]), row[4], row[5])) self.listBox.selection_set(0) def clear_entry(self): """ Deletes an entry from the database. Gets the highlighted selection, makes a list of all the separate words, 'pops' the stock name entry, finds the stock name in the file, deletes the drug along with its details, then updates the inventory screen. """ # popup window try: ans = askokcancel("Verify delete", "Are you sure you want to delete entry?", parent=self.master) if ans: # get index of selection self.getSelection = self.listBox.curselection() # get tuple from selection self.selectedEntry = self.listBox.get(self.getSelection) # # use regex to compile information self.getSelection = str(self.getSelection) regex = re.compile('[0-9]') self.selected_index = regex.findall(self.getSelection) list_item_position = int(self.selected_index[0]) + 1 sql.session.delete_drug(list_item_position) # show confirmation and call get_inven to update the records showinfo(title="Drug removed", message="The Medicine has been removed from your inventory.", parent=self.master) self.get_inven() # tell user to make a selection first except TclError: showerror(title="Error !", message="Please make a selection in order to delete", parent=self.master) def change_inven(self): """ Allows modification of a database entry. Calls the update_drug function """ try: # check if a selection was made # get index of selection self.getSelection = self.listBox.curselection() # get tuple from selection self.selectedEntry = self.listBox.get(self.getSelection) # lets unpack tuple (self.drug, self.qty, self.price, self.total, self.expDate, self.category) = self.selectedEntry # ---New 'edit medicine' window self.edit_window = Toplevel() self.edit_window.title("Edit selected entry") # Edit medicine window widgets ttk.Label(self.edit_window, text="Drug Name").grid(row=0, column=0) ttk.Label(self.edit_window, text="Quantity").grid(row=0, column=1) ttk.Label(self.edit_window, text="Price").grid(row=0, column=2) ttk.Label(self.edit_window, text="Total").grid(row=0, column=3) ttk.Label(self.edit_window, text="Expiring Date").grid(row=0, column=4) ttk.Label(self.edit_window, text="Category").grid(row=0, column=5) self.oldDrug = ttk.Entry(self.edit_window, name="drug") self.oldDrug.grid(row=1, column=0) self.oldQty = ttk.Entry(self.edit_window, name="qty") self.oldQty.grid(row=1, column=1) self.oldPrice = ttk.Entry(self.edit_window, name="price") self.oldPrice.grid(row=1, column=2) self.oldTotal = ttk.Entry(self.edit_window, name="total") self.oldTotal.grid(row=1, column=3) self.oldExpDate = ttk.Entry(self.edit_window, name="expDate") self.oldExpDate.grid(row=1, column=4) self.oldCat = ttk.Entry(self.edit_window, name="category") self.oldCat.grid(row=1, column=5) self.update = ttk.Button(self.edit_window, text="Update", command=self.update_drug).grid(row=2, column=2) self.cancel = ttk.Button(self.edit_window, text="Cancel", command=self.cancel_drug_update).grid(row=2, column=3) # edit this.medicine data self.oldDrug.insert(END, self.drug) self.oldQty.insert(END, self.qty) self.oldPrice.insert(END, self.price) self.oldTotal.insert(END, self.total) self.oldExpDate.insert(END, self.expDate) self.oldCat.insert(END, self.category) # tell user to make a selection first except TclError: showerror(title="Error !", message="Please make a selection in order to update", parent=self.master) def update_drug(self): """ Change the values of a database entry. Called by change_inven Button. """ self.newDrug = self.oldDrug.get() self.newQty = self.oldQty.get() self.newPrice = self.oldPrice.get() self.newTotal = self.oldTotal.get() self.newExpDate = self.oldExpDate.get() self.newCat = self.oldCat.get() # # use regex to compile information self.getSelection = str(self.getSelection) regex = re.compile('[0-9]') self.selected_index = regex.findall(self.getSelection) list_item_position = int(self.selected_index[0]) + 1 self.newRecord = (self.newDrug, self.newQty, self.newPrice, self.newTotal, self.newExpDate, self.newCat, list_item_position) sql.session.update_stock(self.newRecord) # call the get_inven() function to "refresh" list self.get_inven() self.edit_window.destroy() def cancel_drug_update(self): """ Verify canceling of stock update. """ self.edit_window.destroy() def del_inven(self): """ Deletes all entries in database. """ # popup window ans = askokcancel("Verify Delete Action", "Are you 'REALLY' sure you want to clear your 'WHOLE' inventory ?", parent=self.master) if ans: sql.session.delete_all_stock() self.get_inven() showinfo(title="Inventory cleared", message="Your inventory database has been deleted.", parent=self.master)
def showOne(self): Ventana2 = Toplevel(self.master) try: Ventana2.configure(height=210, width=428, bg="#FFFFFF") Ventana2.resizable(1, 1) Ventana2.title("Buscar") frameAux = Frame(Ventana2, height=210, width=428, bg="#4a4a4a") frameAux.place(x=0, y=0) if sys.platform.startswith('win32'): r = "image\\BuscarBosch.png" ruta = "image\\Back.png" ruta2 = "image\\SearchOne.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): r = "image/BuscarBosch.png" ruta = "image/Back.png" ruta2 = "image/SearchOne.png" l = Image.open(r) re = ImageTk.PhotoImage(l) labelFont = Label(frameAux, image=re, borderwidth=0) labelFont.image = re labelFont.place(x=0, y=0) labelText1 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Serie", fg="#FFFFFF", anchor=W) labelText1.config(font=("Tahoma", 11)) labelText1.place(x=15, y=25) labelText11 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText11.config(font=("Tahoma", 11)) labelText11.place(x=210, y=25) labelText2 = Label(frameAux, height=1, width=24, bg="#696969", text="Gravedad", fg="#FFFFFF", anchor=W) labelText2.config(font=("Tahoma", 11)) labelText2.place(x=15, y=50) labelText22 = Label(frameAux, height=1, width=24, bg="#696969", fg="#FFFFFF", anchor=W) labelText22.config(font=("Tahoma", 11)) labelText22.place(x=210, y=50) labelText3 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Fecha", fg="#FFFFFF", anchor=W) labelText3.config(font=("Tahoma", 11)) labelText3.place(x=15, y=75) labelText33 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText33.config(font=("Tahoma", 11)) labelText33.place(x=210, y=75) labell = Label(frameAux, height=1, width=25, bg="#4a4a4a", text="Ingresa el numero de serie", fg="#FFFFFF", anchor=W) #labell.place(x=15,y=135) labell.config(font=("Tahoma", 11)) listbox3 = Entry(frameAux, width=24, justify=RIGHT, bg="#696969", fg="#FFFFFF", borderwidth=0) listbox3.place(x=210, y=125) listbox3.config(font=("Tahoma", 11)) load = Image.open(ruta) render = ImageTk.PhotoImage(load) backbutton = Button( frameAux, image=render, bg="#8d8e8c", borderwidth=0, activebackground="#696969", command=lambda: self.Switch(self.master, Ventana2)) backbutton.image = render backbutton.place(x=245, y=155) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) searchButton = Button( frameAux, image=render2, bg="#8d8e8c", borderwidth=0, activebackground="#c4c4c4", command=lambda: self.load1(listbox3, labelText11, labelText22, labelText33)) searchButton.image = render2 searchButton.place(x=324, y=155) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar")
class ui: def __init__(self, r): self.__root = r # root of program self.__load_icon = ImageTk.PhotoImage(file=constants.PATH + r'/ico/load.png') self.__master_file = "" # file to merge into self.__convert_list = [] # holds list of files to be converted self.__sub_list = [] # holds list of files to compare against master self.__convert_opts = None # Top level for additional convert options self.__nth_number = None # Entry box for holding nth number for convert option self.__lbl_file = None # Label which holds name of master file in top left corner self.__convert_lbox = None # Listbox for holding list of files to convert self.__sub_lbox = None # Listbox for holding list of files to compare against master file self.__match_rule = IntVar() # the rule on how to merge files into master self.__column_rule = IntVar() # which column to use for comparing self.__column_rule.set(1) # initial value is the first column self.__column_match_rule = IntVar() # which column to compare for a match self.__column_match_rule.set(1) # initial value is the first column # public window dimensions self.width = self.__root.winfo_screenwidth() self.height = self.__root.winfo_screenheight() # upper left side of screen self.__master_frame = Frame(self.__root, width=constants.WIDTH/3, borderwidth=1, relief=SOLID, height=constants.HEIGHT/4) self.__master_frame.grid_propagate(False) self.__master_frame.grid(row=0, column=0, padx=5, pady=5) # lower left side of screen self.__convert_frame = Frame(self.__root, width=constants.WIDTH/3, borderwidth=1, relief=SOLID, height=constants.HEIGHT - constants.HEIGHT/4 - 20) self.__convert_frame.pack_propagate(False) self.__convert_frame.grid(row=1, column=0, padx=5, pady=5) # right side of screen self.__sub_frame = Frame(self.__root, width=constants.WIDTH - constants.WIDTH/3 - 20, borderwidth=1, relief=SOLID, height=constants.HEIGHT - 10) self.__sub_frame.grid_propagate(False) self.__sub_frame.grid(row=0, column=1, padx=5, pady=5, columnspan=2, rowspan=2) def setup_gui(self): """ Top level function which is called from main(). Sets window title and dimensions, then calls three sub routines which created and setup the rest of the GUI """ self.__root.title('db_swapper') x = (self.width - constants.WIDTH) / 2 y = (self.height - constants.HEIGHT) / 2 self.__root.geometry('%dx%d+%d+%d' % (constants.WIDTH, constants.HEIGHT, x, y)) self.create_master_frame() self.create_convert_frame() self.create_sub_frame() def create_master_frame(self): """ Initialize the GUI for the upper left """ load_btn = Button(self.__master_frame, image=self.__load_icon, width=20, height=20, command=self.import_master_file) load_btn.grid(row=1, column=1, padx=5, pady=5) Label(self.__master_frame, text="Master List").\ grid(row=1, column=2, padx=5, pady=5) self.__lbl_file = Label(self.__master_frame, bg="white", relief=SUNKEN, width=26) self.__lbl_file.grid(row=2, column=1, padx=5, pady=5, columnspan=3) # adding these weights allows the GUI to align itself within the frame self.__master_frame.grid_rowconfigure(0, weight=1) self.__master_frame.grid_columnconfigure(3, weight=1) self.__master_frame.grid_rowconfigure(3, weight=1) self.__master_frame.grid_columnconfigure(0, weight=1) def create_convert_frame(self): """ Initialize the GUI for the lower left side of the program """ Label(self.__convert_frame, text="Files to split").\ pack(side=TOP) self.__convert_lbox = Listbox(self.__convert_frame, width=29, height=12, selectmode=EXTENDED) self.__convert_lbox.pack(side=TOP) convert = Button(self.__convert_frame, text="Convert", command=self.choose_convert) remove = Button(self.__convert_frame, text="Remove Item", command=lambda: self.remove_item(self.__convert_lbox, self.__convert_list)) load = Button(self.__convert_frame, image=self.__load_icon, width=27, height=20, command=lambda: self.import_and_append_file(self.__convert_lbox, self.__convert_list)) convert.pack(side=LEFT, padx=(10,5), pady=5) remove.pack(side=LEFT, padx=(0,5)) load.pack(side=LEFT) def create_sub_frame(self): """ Initialize the GUI for the right side of the program """ self.__sub_lbox = Listbox(self.__sub_frame, width = 30, height = 23, selectmode=EXTENDED) self.__sub_lbox.grid(row=0, column=0, rowspan=20, padx=5, pady=5) Label(self.__sub_frame, justify=LEFT, text = "To use db_swapper first load a\nmaster list, the database you wish\nto" " merge files into. Then add\nany sub files to compare against\nand hit" " 'merge'. Use convert to\nsplit a large file into smaller files\n" "using the popup options").\ grid(row=1, column=1, rowspan=20, columnspan=4, sticky=N+W) Label(self.__sub_frame, text="Merge into master if a matched\nsub item is:", justify=LEFT).\ grid(row=11, column=1, sticky=W, rowspan=3, columnspan=4) Radiobutton(self.__sub_frame, text="Less", variable=self.__match_rule, value=constants.LESS).\ grid(row=14, column=1, sticky=W) Radiobutton(self.__sub_frame, text="Greater", variable=self.__match_rule, value=constants.GREATER).\ grid(row=14, column=2, sticky=W) Radiobutton(self.__sub_frame, text="Equal", variable=self.__match_rule, value=constants.EQUAL).\ grid(row=14, column=3, sticky=W) Label(self.__sub_frame, text="Column to match with:", justify=LEFT).\ grid(row=15, column=1, sticky=W, columnspan=4) OptionMenu(self.__sub_frame, self.__column_match_rule,1,2,3,4,5,6,7,8,9,10).\ grid(row=15, column=3, sticky=E) Label(self.__sub_frame, text="Column to compare to:", justify=LEFT).\ grid(row=16, column=1, sticky=W, columnspan=4) OptionMenu(self.__sub_frame, self.__column_rule,1,2,3,4,5,6,7,8,9,10).\ grid(row=16,column=3,sticky=E) # Merge button Button(self.__sub_frame, text="Merge", width=24, command=self.merge_files).\ grid(row=19, column=1, padx=(0,5), columnspan=4, sticky=W) # Load button for merge frame Button(self.__sub_frame, image=self.__load_icon, width=73, height=35, command=lambda: self.import_and_append_file(self.__sub_lbox, self.__sub_list)).\ grid(row=18, column=1, padx=(0,0), sticky=W, columnspan=2) # Remove button for merge frame Button(self.__sub_frame, text="Remove Item", width=10, height=2, command=lambda: self.remove_item(self.__sub_lbox, self.__sub_list)).\ grid(row=18, column=2, padx=(40,0), sticky=W, columnspan=2) def choose_convert(self): """ Creates a window that prompts the user for what type of file conversion to use. The user may either elect to split a file based upon it's matching first column, or split a file based on every Nth item, which is entered in this window. """ self.__convert_opts = Toplevel() self.__convert_opts.title("Conversion method") # hard coded dimensions x = (self.width - 250) / 2 y = (self.height - 100) / 2 self.__convert_opts.geometry('%dx%d+%d+%d' % (250, 100, x, y)) Label(self.__convert_opts, text="Which method to split by?").grid(row=0, column=0, columnspan=4) Button(self.__convert_opts, text="First Column", command=self.convert_files).\ grid(row=1, column=0, sticky=W, padx=5, pady=5) Button(self.__convert_opts, text="By every Nth Entry", command=self.convert_files_nth).\ grid(row=2, column=0, sticky=W, padx=5) self.__nth_number = Entry(self.__convert_opts) self.__nth_number.grid(row=2,column=1) def import_master_file(self): """ Method called with the user chooses to import a master file, opens a dialog for the user to browse and select a file, then displays the file chosen within a label and sets the internal variable __master_file """ file_types = [('Semicolon Separated Text Files', ('*.csv', '*.txt')), ('All Files', '*')] dlg = tkFileDialog.Open(filetypes=file_types) fl = dlg.show() if fl != '': self.__master_file = fl segments = self.__master_file.rpartition('/') self.__lbl_file.config(text=segments[2]) def import_and_append_file(self, lbox, lbox_list): """ Method to prompt a user for a selection of files, and append those files to a list box and internal list. Takes a Listbox and list object, and inserts the selected filenames into the Listbox and the full path filenames into the list """ file_types = [('Semicolon Separated Files', ('*.csv', '*.txt')), ('All Files', '*')] files = list(tkFileDialog.askopenfilenames(filetypes=file_types)) if files is not None: for file in files: lbox.insert(END, file.rpartition('/')[2]) lbox_list.append(file) def remove_item(self, lbox, lbox_list): """ Removes any items currently selected in a listbox passed. Also ensures to remove that item from the internal list passed. """ indexes = list(lbox.curselection()) # Remove in reversed order so the indices do not change as we delete for idx in reversed(indexes): lbox.delete(idx) del lbox_list[idx] def convert_files(self): """ Splits a large csv file into smaller csv files based upon their first column """ logger.info('Converting file(s) based upon first column') self.__convert_opts.destroy() if not self.__convert_list: logger.error('No files to convert') return # loop through each file in the Listbox for item in self.__convert_list: with open(item, 'rb') as file: # open the file and create a reader master_reader = csv.reader(file, delimiter=constants.DELIMITER) curr = None # keeps track of current running subject segment = [] # rows are appended to this list as long as the subject remains the same for row in master_reader: # if curr is empty, start a new subject if curr is None: curr = row[0] if curr != row[0]: # sometimes the csv file contains a header sep, if so then ignore it if 'sep=' in curr: curr = None segment=[] continue # create a csv file with the name of the subject with open(constants.PATH + '/' + curr + '.csv', 'wb') as write_out: # write out the delimiter helper, then write the segment list write_out.write('sep='+constants.DELIMITER + '\n') writer = csv.writer(write_out, delimiter=constants.DELIMITER) for seg in segment: writer.writerow(seg) segment = [] curr = row[0] # if row doesn't match previous curr, it becomes the new curr segment.append(row) # append this row to the start of the new curr else: segment.append(row) # if segments has data for a subject at the end of the loop, write the data to the subject if list is not None: with open(constants.PATH + '/' + curr + '.csv', 'wb') as write_out: write_out.write('sep='+constants.DELIMITER + '\n') writer = csv.writer(write_out, delimiter=constants.DELIMITER) for seg in segment: writer.writerow(seg) logger.info('FINISHED, split files can be found in installation directory') def convert_files_nth(self): if not self.__convert_list: logger.error('No files to convert') return # if the text in the entry box cannot be converted, display error try: num = int(self.__nth_number.get()) except: logger.error('Invalid number of entries given: \'%s\'' % self.__nth_number.get()) self.__convert_opts.destroy() return self.__convert_opts.destroy() logger.info('Converting file(s) based upon every nth item') for item in self.__convert_list: with open(item, 'rb') as file: master_reader = csv.reader(file, delimiter=constants.DELIMITER) count = 0 parts = 0 segment = [] for row in master_reader: if('sep=' in '\t'.join(row)): continue count += 1 segment.append(row) if(count == num): with open(constants.PATH + '/%spart%d' % ((item.rpartition('/')[2])[:-4], parts) + '.csv', 'wb') as write_out: write_out.write('sep='+constants.DELIMITER + '\n') writer = csv.writer(write_out, delimiter=constants.DELIMITER) for seg in segment: writer.writerow(seg) segment = [] parts += 1 count = 0 if count != 0: with open(constants.PATH + '/%spart%d' % ((item.rpartition('/')[2])[:-4], parts) + '.csv', 'wb') as write_out: write_out.write('sep='+constants.DELIMITER + '\n') writer = csv.writer(write_out, delimiter=constants.DELIMITER) for seg in segment: writer.writerow(seg) logger.info('FINISHED, split files can be found in installation directory') def merge_files(self): """ Merges small files into a master file based upon a matching criteria. all files in __sub_list are compared to __master_file. """ compare_col = self.__column_rule.get() - 1 match_col = self.__column_match_rule.get() - 1 rule = self.__match_rule.get() if rule == 0: logger.error('Rule not selected, select LESS, GREATER, or EQUAL') return if self.__master_file == "": logger.error('No master file selected') return if self.__sub_list is None: logger.error('No sub files selected') return s = "" if rule == constants.LESS: s = "LESS than" elif rule == constants.GREATER: s = "GREATER than" elif rule == constants.EQUAL: s = "EQUAL to" logger.info('beginning merge, using column #%d for finding matching rows' % match_col) logger.info('Checking column #%d to decide whether to overwrite rows' % compare_col) logger.info('overwriting will occur if child row is %s parent row' % s) # move master file into a list for comparing and overwriting master_list = [] with open(self.__master_file, 'rb') as m_file: master_reader = csv.reader(m_file, delimiter=constants.DELIMITER) for row in master_reader: master_list.append(row) # run each sub file through the master list to swap changed = False for sub_file in self.__sub_list: sub_list = [] with open(sub_file, 'rb') as file: sub_reader = csv.reader(file, delimiter=constants.DELIMITER) for sr in sub_reader: sub_list.append(sr) row_num = 1 non_decimal = re.compile(r'[^\d.]+') for row in master_list: for sub_row in sub_list: if str(sub_row[match_col]).lower() == str(row[match_col]).lower() and \ (not 'sep=' in str(sub_row[match_col])): ms_val = int(float(non_decimal.sub('',row[compare_col]))) sb_val = int(float(non_decimal.sub('',sub_row[compare_col]))) if rule == constants.LESS and sb_val < ms_val or \ rule == constants.GREATER and sb_val > ms_val or \ rule == constants.EQUAL and sb_val == ms_val: changed = True logger.info('row #%d: SWAPPING %s in master list for %s in %s' % (row_num, ','.join(row), ','.join(sub_row), sub_file.rpartition('/')[2])) master_list[(row_num-1)] = sub_row row_num+= 1 # write back master list into master file with new changes if changed: with open((self.__master_file.rpartition('/')[2])[:-4] + '_swapped.csv', 'wb') as m_file: master_writer = csv.writer(m_file, delimiter=constants.DELIMITER) for row in master_list: master_writer.writerow(row) logger.info('FINISHED, swapped file located in installation directory')
def destroy(self): self.area.focus_set() Toplevel.destroy(self)
class Oscilloscope(object) : def __init__(self,parent): self.parent = parent self.model=GeneratorXY() self.view=View(parent,self.model) self.menuFrame=Frame(parent) self.lissajouTimaFrame=Frame(parent) self.lissajouTopLevel = None self.lissajou = None self.model.attach(self.view) self.time = Time(self.lissajouTimaFrame,self.model,self.view) self.lissajouButton = Button(self.lissajouTimaFrame, text = "XY Curve", command=lambda:self.createLissajou(self.model),pady = 18) self.controlY=Controller(parent,self.view,None,self.model.getSignalY(),self.model) self.controlX=Controller(parent,self.view,None,self.model.getSignalX(),self.model) self.menubar=MenuBar(parent,self.menuFrame,self.model,self.controlX,self.controlY,self.view) self.parent.protocol('WM_DELETE_WINDOW', lambda:self.menubar.exit()) self.save = self.menubar.getSave() self.parent.bind('<Control-o>', lambda x:self.save.load()) self.parent.bind('<Control-s>', lambda x:self.save.saving()) self.parent.bind('<Control-q>', lambda x:self.menubar.exit()) self.parent.bind('<Control-d>', lambda x:self.save.savingAs()) self.parent.bind('<Control-b>', lambda x:self.view.setColor("bg")) self.parent.bind('<Control-g>', lambda x:self.view.setColor("grid")) self.parent.bind('<Control-x>', lambda x:self.view.setColor(self.model.getSignalX())) self.parent.bind('<Control-y>', lambda x:self.view.setColor(self.model.getSignalY())) self.parent.bind('<Control-a>', lambda x:self.menubar.about()) self.parent.bind('<Control-l>', lambda x:self.createLissajou(self.model)) def test(self) : save = self.menubar.getSave() save.load() def createLissajou(self,model) : if self.lissajou == None: self.lissajouTopLevel = Toplevel(self.parent) self.lissajouTopLevel.protocol('WM_DELETE_WINDOW', lambda:self.deleteLissajou()) self.lissajouTopLevel.wm_attributes("-topmost", True) self.lissajouTopLevel.title("XY Curve") self.lissajou = Lissajou (self.lissajouTopLevel,self.model) self.model.attach(self.lissajou) self.controlX.setLissajou(self.lissajou) self.controlY.setLissajou(self.lissajou) self.lissajou.packing() def deleteLissajou(self): self.lissajou = None self.controlX.setLissajou(self.lissajou) self.controlY.setLissajou(self.lissajou) self.lissajouTopLevel.destroy() def packing(self) : self.menuFrame.pack(fill='x',side='top') self.menubar.packing() self.view.packing() self.lissajouTimaFrame.pack(fill='x') self.lissajouButton.pack(side="right") self.time.packing() self.controlX.packing() self.controlY.packing()
def hideWindow(self): Toplevel.destroy(self)
class ToolUi(): def __init__(self): self.tk = Tk() self.tk.geometry("500x500") self.text_boxes = dict() self.header_frame = None self.analysis_frame = None self.info_label = None self.info_label_text = StringVar() self.report_dialog = None def destroy_main(self): self.tk.destroy() def override_x_callback(self, callback): self.tk.protocol('WM_DELETE_WINDOW', callback) def set_window_title(self, title): self.tk.winfo_toplevel().title(title) def set_info_label_text(self, text): self.info_label_text.set(text) def render_window_frames(self): self.header_frame = Frame(self.tk) self.header_frame.pack(fill="x", pady=10) self.analysis_frame = Frame(self.tk) self.analysis_frame.pack(fill="x") def render_header(self, title, buttons): Label(self.tk, text=title, font=("Helvetica", 20)).pack() Message(self.tk, textvariable=self.info_label_text, fg="red", justify=LEFT, width=500).pack() self.render_window_frames() for i in xrange(len(buttons)): Button(self.header_frame, text=buttons[i]['title'], command=buttons[i]['callback']).pack(side=LEFT) @staticmethod def display_popup(title, message): tkMessageBox.showinfo(title, message) @staticmethod def display_yes_no_message(title, message): return tkMessageBox.askyesno(title, message) def display_messagebox_yesno(self, title, message): self.set_info_label_text( "Please wait while the tool analyzes your passwords.") return tkMessageBox.askyesno(title, message) def render_frames(self, frames): for frame in frames: t = ToggledFrame(self.analysis_frame, text=frame['title'], relief="raised", borderwidth=1) t.pack(fill="x", expand=1, pady=5, padx=2, anchor="n") self.text_boxes[frame['textbox_name']] = ScrolledText(t.sub_frame, wrap=WORD) self.text_boxes[frame['textbox_name']].tag_configure( TEXTBOX_STYLE_INFO, foreground='green') self.text_boxes[frame['textbox_name']].tag_configure( TEXTBOX_STYLE_HEADING, font=('Verdana', 10), foreground='orange') self.text_boxes[frame['textbox_name']].pack() self.tk.mainloop() def text_box_insert(self, text_box, message, text_style=None): if not text_style: self.text_boxes[text_box].insert(INSERT, message) else: self.text_boxes[text_box].insert(INSERT, message, text_style) def clear_text_boxes(self): for text_box in self.text_boxes: self.text_boxes[text_box].delete(1.0, END) def preview_report(self, report_data, callback): self.report_dialog = Toplevel() self.report_dialog.title("Preview Report") Button(self.report_dialog, text="Send Report", command=callback).pack() self.text_boxes[report_data['text_box']] = ScrolledText( self.report_dialog) self.text_boxes[report_data['text_box']].pack() def close_report_dialog(self): self.report_dialog.destroy()
def no_click(): popup = Toplevel() popup.resizable(False,False) ttk.Label(popup, text='请选择文件!').pack(pady=25) center_window(popup, 300, 100) popup.after(2500,lambda:popup.destroy())
class View(BaseView): TEXT_LABEL_OFFSET = 50 BOX_START_X = 30 BOX_START_Y = 45 BOX_WIDTH = 100 BOX_HEIGHT = 45 BOX_VERTICAL_OFFSET = 15 ANOTHER_GUI_OFF = 30 GUI_WIDTH = 170 def __init__(self, tkRoot, app, masterComp, parentNode, logger): BaseView.__init__(self, tkRoot, app, logger) # master (upper level view) component on which this view was issued self.masterComp = masterComp self.parentNode = parentNode # open detailed window - will go into View class, create Canvas in this window self.window = Toplevel(self.tkRoot) # self.window.bind("<<close-window>>", self.__onClose) # doesn't work self.window.protocol("WM_DELETE_WINDOW", self.__onClose) self.window.title("%s" % self.masterComp.name) self.canvas = Canvas(self.window, bg=BaseView.CANVAS_BG_COLOR) self.canvas.pack(expand=YES, fill=BOTH) self.app.addActiveView(self.masterComp.name, self) def createContent(self): self.__setWindowGeometry() self.__setScrollableView() self.__createBoxes() def __setScrollableView(self): """Sets a scrollbar and scroll area corresponding to number of boxes the views needs to accommodate. """ oneBoxSpace = View.BOX_HEIGHT + View.BOX_VERTICAL_OFFSET vertNeeded = len( self.parentNode.children) * oneBoxSpace + View.BOX_START_Y if (View.BOX_START_Y + vertNeeded) < conf.GUI_HEIGHT: return self.logger.debug("View needs to be scrollable, setting ...") self._setScrollBar(vertNeeded) def _setScrollBar(self, verticalSpace): """Derived class RosView calls this method.""" self.canvas.config(scrollregion=(0, 0, 200, verticalSpace)) self.canvas.config(highlightthickness=0) # no pixels to border sbar = Scrollbar(self.canvas) sbar.config(command=self.canvas.yview) # xlink sbar and canv self.canvas.config(yscrollcommand=sbar.set) # move one moves other sbar.pack(side=RIGHT, fill=Y) # pack first=clip last self.canvas.pack(side=LEFT, expand=YES, fill=BOTH) # canvas clipped first def __createBoxes(self): # always be the same as self.masterComp.name (title and label must agree) group = self.parentNode.name # self.masterComp.name self.canvas.create_text(View.BOX_START_X + View.TEXT_LABEL_OFFSET, View.BOX_START_Y - View.BOX_VERTICAL_OFFSET, text=group, font=self.bigFont) nodeKeys = self.parentNode.children.keys() nodeKeys.sort() # sort the keys alphabetically for i in range(len(nodeKeys)): node = self.parentNode.children[nodeKeys[i]] x0 = View.BOX_START_X y0 = (View.BOX_START_Y + (i * (View.BOX_HEIGHT + View.BOX_VERTICAL_OFFSET))) x1 = x0 + View.BOX_WIDTH y1 = y0 + View.BOX_HEIGHT box = RenderableBox(self.masterComp.name, self.canvas, node) dch = DoubleClickHandler(box, self) idBox = box.create(x0, y0, x1, y1, node.state.color) idText = box.text(x0 + View.TEXT_LABEL_OFFSET, y0 + View.BOX_HEIGHT / 2, node.name, self.boxTitleFont) # bind both IDs - box and text in the box self.canvas.tag_bind(idBox, "<Double-1>", dch) self.canvas.tag_bind(idText, "<Double-1>", dch) # could even perhaps be list and not a dictionary self.compStore.append(box) def openDetailedView(self, comp): # check if view which is to be open has not been opened already if self.app.isViewActive(comp.name): m = ("View '%s' is already among active windows, " "not created." % comp.name) self.logger.warn(m) tkMessageBox.showwarning("Quit", m, parent=self.window) return try: rootNode = self.parentNode.children[comp.name] except KeyError: self.logger.error("Could not access child node for '%s'" % comp.name) else: V = rootNode.viewerForChildren v = V(self.tkRoot, self.app, comp, rootNode, self.logger) v.createContent() self.logger.debug("View created: name '%s' root node: " "'%s'" % (comp.name, rootNode.name)) def __onClose(self): self.app.removeActiveView(self.masterComp.name) self.window.destroy() def __setWindowGeometry(self): offsetX = View.ANOTHER_GUI_OFF * self.app.activeViewsCount() x = conf.GUI_OFF_X + conf.GUI_WIDTH + offsetX geom = "%sx%s+%s+%s" % (View.GUI_WIDTH, conf.GUI_HEIGHT, x, conf.GUI_OFF_Y) self.window.geometry(geom)
def help_about(self): """Shows an 'about' modal dialog. Callback method called by tk. """ about_win = Toplevel(self.root) # Set up dialog lbl = Label(about_win, text="Video Poker") lbl.grid(row=0, column=0, padx=10, pady=(10, 0), sticky=W + N) lbl = Label(about_win, text="by Charles Raymond Smith") lbl.grid(row=1, column=0, padx=10, pady=(0, 7), sticky=W + N) lbl = Label(about_win, text="Adapted from video poker by Paul Griffiths") lbl.grid(row=2, column=0, padx=10, pady=(0, 7), sticky=W + N) lbl = Label(about_win, text="Written in Python, with tkinter.") lbl.grid(row=3, column=0, padx=10, pady=7, sticky=W + N) lbl = Label(about_win, text="Copyright 2017 Charles Raymond Smith") lbl.grid(row=4, column=0, padx=10, pady=(7, 0), sticky=W + N) lbl = Label(about_win, text="Email: [email protected]") lbl.grid(row=5, column=0, padx=10, pady=(0, 21), sticky=W + N) lbl = Label(about_win, text="This program is free software: you can " + "redistribute it and/or modify it under the terms") lbl.grid(row=6, column=0, columnspan=2, padx=10, pady=0, sticky=W + N) lbl = Label(about_win, text="of the GNU General Public License as " + "published by the Free Software Foundation, either") lbl.grid(row=7, column=0, columnspan=2, padx=10, pady=(0, 0), sticky=W + N) lbl = Label(about_win, text="version 3 of the License, or " + "(at your option) any later version.") lbl.grid(row=8, column=0, columnspan=2, padx=10, pady=(0, 21), sticky=W + N) lbl = Label(about_win, text="This program is distributed in " + "the hope that it will be useful, but WITHOUT ANY WARRANTY;") lbl.grid(row=9, column=0, columnspan=2, padx=10, pady=0, sticky=W + N) lbl = Label(about_win, text="without even the implied " + "warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR") lbl.grid(row=10, column=0, columnspan=2, padx=10, pady=(0, 0), sticky=W + N) lbl = Label(about_win, text="PURPOSE. See the " + "GNU General Public License for more details.") lbl.grid(row=11, column=0, columnspan=2, padx=10, pady=(0, 21), sticky=W + N) lbl = Label(about_win, text="You should have received a " + "copy of the GNU General Public License along with this") lbl.grid(row=12, column=0, columnspan=2, padx=10, pady=(0, 0), sticky=W + N) lbl = Label(about_win, text="program. If not, see " + "<http://www.gnu.org/licenses/>.") lbl.grid(row=13, column=0, columnspan=2, padx=10, pady=(0, 21), sticky=W + N) img = PhotoImage(file="{0}27.gif".format(self.gifdir)) lbl = Label(about_win, image=img) lbl.grid(row=0, column=1, rowspan=5, padx=10, pady=10, sticky=N + E) btn = Button(about_win, text="OK", command=about_win.quit) btn.grid(row=14, column=0, columnspan=2, padx=0, pady=(0, 10), ipadx=30, ipady=3) # Show dialog about_win.transient(self.root) about_win.parent = self.root about_win.protocol("WM_DELETE_WINDOW", about_win.destroy) about_win.geometry("+{0}+{1}".format(self.root.winfo_rootx() + 50, self.root.winfo_rooty() + 50)) about_win.title("About Video Poker") about_win.focus_set() about_win.grab_set() about_win.mainloop() about_win.destroy()
class CFGEditor(object): """ A dialog window for creating and editing context free grammars. C{CFGEditor} places the following restrictions on what C{CFG}s can be edited: - All nonterminals must be strings consisting of word characters. - All terminals must be strings consisting of word characters and space characters. """ # Regular expressions used by _analyze_line. Precompile them, so # we can process the text faster. ARROW = SymbolWidget.SYMBOLS['rightarrow'] _LHS_RE = re.compile(r"(^\s*\w+\s*)(->|("+ARROW+"))") _ARROW_RE = re.compile("\s*(->|("+ARROW+"))\s*") _PRODUCTION_RE = re.compile(r"(^\s*\w+\s*)" + # LHS "(->|("+ARROW+"))\s*" + # arrow r"((\w+|'[\w ]*'|\"[\w ]*\"|\|)\s*)*$") # RHS _TOKEN_RE = re.compile("\\w+|->|'[\\w ]+'|\"[\\w ]+\"|("+ARROW+")") _BOLD = ('helvetica', -12, 'bold') def __init__(self, parent, cfg=None, set_cfg_callback=None): self._parent = parent if cfg is not None: self._cfg = cfg else: self._cfg = ContextFreeGrammar(Nonterminal('S'), []) self._set_cfg_callback = set_cfg_callback self._highlight_matching_nonterminals = 1 # Create the top-level window. self._top = Toplevel(parent) self._init_bindings() self._init_startframe() self._startframe.pack(side='top', fill='x', expand=0) self._init_prodframe() self._prodframe.pack(side='top', fill='both', expand=1) self._init_buttons() self._buttonframe.pack(side='bottom', fill='x', expand=0) self._textwidget.focus() def _init_startframe(self): frame = self._startframe = Frame(self._top) self._start = Entry(frame) self._start.pack(side='right') Label(frame, text='Start Symbol:').pack(side='right') Label(frame, text='Productions:').pack(side='left') self._start.insert(0, self._cfg.start().symbol()) def _init_buttons(self): frame = self._buttonframe = Frame(self._top) Button(frame, text='Ok', command=self._ok, underline=0, takefocus=0).pack(side='left') Button(frame, text='Apply', command=self._apply, underline=0, takefocus=0).pack(side='left') Button(frame, text='Reset', command=self._reset, underline=0, takefocus=0,).pack(side='left') Button(frame, text='Cancel', command=self._cancel, underline=0, takefocus=0).pack(side='left') Button(frame, text='Help', command=self._help, underline=0, takefocus=0).pack(side='right') def _init_bindings(self): self._top.title('CFG Editor') self._top.bind('<Control-q>', self._cancel) self._top.bind('<Alt-q>', self._cancel) self._top.bind('<Control-d>', self._cancel) #self._top.bind('<Control-x>', self._cancel) self._top.bind('<Alt-x>', self._cancel) self._top.bind('<Escape>', self._cancel) #self._top.bind('<Control-c>', self._cancel) self._top.bind('<Alt-c>', self._cancel) self._top.bind('<Control-o>', self._ok) self._top.bind('<Alt-o>', self._ok) self._top.bind('<Control-a>', self._apply) self._top.bind('<Alt-a>', self._apply) self._top.bind('<Control-r>', self._reset) self._top.bind('<Alt-r>', self._reset) self._top.bind('<Control-h>', self._help) self._top.bind('<Alt-h>', self._help) self._top.bind('<F1>', self._help) def _init_prodframe(self): self._prodframe = Frame(self._top) # Create the basic Text widget & scrollbar. self._textwidget = Text(self._prodframe, background='#e0e0e0', exportselection=1) self._textscroll = Scrollbar(self._prodframe, takefocus=0, orient='vertical') self._textwidget.config(yscrollcommand = self._textscroll.set) self._textscroll.config(command=self._textwidget.yview) self._textscroll.pack(side='right', fill='y') self._textwidget.pack(expand=1, fill='both', side='left') # Initialize the colorization tags. Each nonterminal gets its # own tag, so they aren't listed here. self._textwidget.tag_config('terminal', foreground='#006000') self._textwidget.tag_config('arrow', font='symbol') self._textwidget.tag_config('error', background='red') # Keep track of what line they're on. We use that to remember # to re-analyze a line whenever they leave it. self._linenum = 0 # Expand "->" to an arrow. self._top.bind('>', self._replace_arrows) # Re-colorize lines when appropriate. self._top.bind('<<Paste>>', self._analyze) self._top.bind('<KeyPress>', self._check_analyze) self._top.bind('<ButtonPress>', self._check_analyze) # Tab cycles focus. (why doesn't this work??) def cycle(e, textwidget=self._textwidget): textwidget.tk_focusNext().focus() self._textwidget.bind('<Tab>', cycle) prod_tuples = [(p.lhs(),[p.rhs()]) for p in self._cfg.productions()] for i in range(len(prod_tuples)-1,0,-1): if (prod_tuples[i][0] == prod_tuples[i-1][0]): if () in prod_tuples[i][1]: continue if () in prod_tuples[i-1][1]: continue print prod_tuples[i-1][1] print prod_tuples[i][1] prod_tuples[i-1][1].extend(prod_tuples[i][1]) del prod_tuples[i] for lhs, rhss in prod_tuples: print lhs, rhss s = '%s ->' % lhs for rhs in rhss: for elt in rhs: if isinstance(elt, Nonterminal): s += ' %s' % elt else: s += ' %r' % elt s += ' |' s = s[:-2] + '\n' self._textwidget.insert('end', s) self._analyze() # # Add the producitons to the text widget, and colorize them. # prod_by_lhs = {} # for prod in self._cfg.productions(): # if len(prod.rhs()) > 0: # prod_by_lhs.setdefault(prod.lhs(),[]).append(prod) # for (lhs, prods) in prod_by_lhs.items(): # self._textwidget.insert('end', '%s ->' % lhs) # self._textwidget.insert('end', self._rhs(prods[0])) # for prod in prods[1:]: # print '\t|'+self._rhs(prod), # self._textwidget.insert('end', '\t|'+self._rhs(prod)) # print # self._textwidget.insert('end', '\n') # for prod in self._cfg.productions(): # if len(prod.rhs()) == 0: # self._textwidget.insert('end', '%s' % prod) # self._analyze() # def _rhs(self, prod): # s = '' # for elt in prod.rhs(): # if isinstance(elt, Nonterminal): s += ' %s' % elt.symbol() # else: s += ' %r' % elt # return s def _clear_tags(self, linenum): """ Remove all tags (except C{arrow} and C{sel}) from the given line of the text widget used for editing the productions. """ start = '%d.0'%linenum end = '%d.end'%linenum for tag in self._textwidget.tag_names(): if tag not in ('arrow', 'sel'): self._textwidget.tag_remove(tag, start, end) def _check_analyze(self, *e): """ Check if we've moved to a new line. If we have, then remove all colorization from the line we moved to, and re-colorize the line that we moved from. """ linenum = int(self._textwidget.index('insert').split('.')[0]) if linenum != self._linenum: self._clear_tags(linenum) self._analyze_line(self._linenum) self._linenum = linenum def _replace_arrows(self, *e): """ Replace any C{'->'} text strings with arrows (char \\256, in symbol font). This searches the whole buffer, but is fast enough to be done anytime they press '>'. """ arrow = '1.0' while 1: arrow = self._textwidget.search('->', arrow, 'end+1char') if arrow == '': break self._textwidget.delete(arrow, arrow+'+2char') self._textwidget.insert(arrow, self.ARROW, 'arrow') self._textwidget.insert(arrow, '\t') arrow = '1.0' while 1: arrow = self._textwidget.search(self.ARROW, arrow+'+1char', 'end+1char') if arrow == '': break self._textwidget.tag_add('arrow', arrow, arrow+'+1char') def _analyze_token(self, match, linenum): """ Given a line number and a regexp match for a token on that line, colorize the token. Note that the regexp match gives us the token's text, start index (on the line), and end index (on the line). """ # What type of token is it? if match.group()[0] in "'\"": tag = 'terminal' elif match.group() in ('->', self.ARROW): tag = 'arrow' else: # If it's a nonterminal, then set up new bindings, so we # can highlight all instances of that nonterminal when we # put the mouse over it. tag = 'nonterminal_'+match.group() if tag not in self._textwidget.tag_names(): self._init_nonterminal_tag(tag) start = '%d.%d' % (linenum, match.start()) end = '%d.%d' % (linenum, match.end()) self._textwidget.tag_add(tag, start, end) def _init_nonterminal_tag(self, tag, foreground='blue'): self._textwidget.tag_config(tag, foreground=foreground, font=CFGEditor._BOLD) if not self._highlight_matching_nonterminals: return def enter(e, textwidget=self._textwidget, tag=tag): textwidget.tag_config(tag, background='#80ff80') def leave(e, textwidget=self._textwidget, tag=tag): textwidget.tag_config(tag, background='') self._textwidget.tag_bind(tag, '<Enter>', enter) self._textwidget.tag_bind(tag, '<Leave>', leave) def _analyze_line(self, linenum): """ Colorize a given line. """ # Get rid of any tags that were previously on the line. self._clear_tags(linenum) # Get the line line's text string. line = self._textwidget.get(`linenum`+'.0', `linenum`+'.end') # If it's a valid production, then colorize each token. if CFGEditor._PRODUCTION_RE.match(line): # It's valid; Use _TOKEN_RE to tokenize the production, # and call analyze_token on each token. def analyze_token(match, self=self, linenum=linenum): self._analyze_token(match, linenum) return '' CFGEditor._TOKEN_RE.sub(analyze_token, line) elif line.strip() != '': # It's invalid; show the user where the error is. self._mark_error(linenum, line) def _mark_error(self, linenum, line): """ Mark the location of an error in a line. """ arrowmatch = CFGEditor._ARROW_RE.search(line) if not arrowmatch: # If there's no arrow at all, highlight the whole line. start = '%d.0' % linenum end = '%d.end' % linenum elif not CFGEditor._LHS_RE.match(line): # Otherwise, if the LHS is bad, highlight it. start = '%d.0' % linenum end = '%d.%d' % (linenum, arrowmatch.start()) else: # Otherwise, highlight the RHS. start = '%d.%d' % (linenum, arrowmatch.end()) end = '%d.end' % linenum # If we're highlighting 0 chars, highlight the whole line. if self._textwidget.compare(start, '==', end): start = '%d.0' % linenum end = '%d.end' % linenum self._textwidget.tag_add('error', start, end) def _analyze(self, *e): """ Replace C{->} with arrows, and colorize the entire buffer. """ self._replace_arrows() numlines = int(self._textwidget.index('end').split('.')[0]) for linenum in range(1, numlines+1): # line numbers start at 1. self._analyze_line(linenum) def _parse_productions(self): """ Parse the current contents of the textwidget buffer, to create a list of productions. """ productions = [] # Get the text, normalize it, and split it into lines. text = self._textwidget.get('1.0', 'end') text = re.sub(self.ARROW, '->', text) text = re.sub('\t', ' ', text) lines = text.split('\n') # Convert each line to a CFG production for line in lines: line = line.strip() if line=='': continue productions += parse_cfg_production(line) #if line.strip() == '': continue #if not CFGEditor._PRODUCTION_RE.match(line): # raise ValueError('Bad production string %r' % line) # #(lhs_str, rhs_str) = line.split('->') #lhs = Nonterminal(lhs_str.strip()) #rhs = [] #def parse_token(match, rhs=rhs): # token = match.group() # if token[0] in "'\"": rhs.append(token[1:-1]) # else: rhs.append(Nonterminal(token)) # return '' #CFGEditor._TOKEN_RE.sub(parse_token, rhs_str) # #productions.append(Production(lhs, *rhs)) return productions def _destroy(self, *e): if self._top is None: return self._top.destroy() self._top = None def _ok(self, *e): self._apply() self._destroy() def _apply(self, *e): productions = self._parse_productions() start = Nonterminal(self._start.get()) cfg = ContextFreeGrammar(start, productions) if self._set_cfg_callback is not None: self._set_cfg_callback(cfg) def _reset(self, *e): self._textwidget.delete('1.0', 'end') for production in self._cfg.productions(): self._textwidget.insert('end', '%s\n' % production) self._analyze() if self._set_cfg_callback is not None: self._set_cfg_callback(self._cfg) def _cancel(self, *e): try: self._reset() except: pass self._destroy() def _help(self, *e): # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._parent, 'Help: Chart Parser Demo', (_CFGEditor_HELP).strip(), width=75, font='fixed') except: ShowText(self._parent, 'Help: Chart Parser Demo', (_CFGEditor_HELP).strip(), width=75)
class CreateIssueUI: #This method will initialize the UI and workflow to create an issues def __init__(self, ifn, iid, pv, pvt, tht, tnt): #create a dictionaty to hold all of the issue data self.issue_dictionary = { "file name" : ifn, "issue index" : iid, "project name" : pv, "project version" : pvt, "HW setup" : tht, "tester" : tnt, "issue summary" : "summary", "issue description" : "description", "issue time" : "time", "issue GPS" : "GPS" } #create the Top level that will be the create issue main window self.create_issue_window = Toplevel() self.create_issue_window.title("Create issue") #issue summary label and text field self.issue_summary_label = Label(self.create_issue_window, text = "Summary") self.issue_summary_label.grid(row = 1) self.issue_summary_text = Text(self.create_issue_window, height = 1, width = 50) self.issue_summary_text.insert(END, "Write issue summary here") self.issue_summary_text.grid(row = 1, column = 1) #create issue description label and text field self.issue_description_label = Label(self.create_issue_window, text = "Summary") self.issue_description_label.grid(row = 2) self.issue_description_text = Text(self.create_issue_window, height = 5, width = 50) self.issue_description_text.insert(END, "Write issue description here") self.issue_description_text.grid(row = 2, column = 1) #Get the time stamps for the created issue now = datetime.datetime.now() self.issue_datetime_text = Text(self.create_issue_window, height = 1, width = 30) self.issue_datetime_text.insert(END, str(now)) self.issue_datetime_text.grid(row = 3) #Get GPS coordinates from the system g = geocoder.ip('me') print(g.latlng) GPScoord = str(g.latlng) #Get GPS coordinates (This will be done later) self.issue_GPS_text = Text(self.create_issue_window, height = 1, width = 30) self.issue_GPS_text.insert(END, GPScoord) self.issue_GPS_text.grid(row = 3, column = 1) #define the button that will save a created issue and close the window self.save_close_issue_button = Button(self.create_issue_window, text = "Save and Close", command = lambda: self.save_issue_method(self.issue_dictionary)) self.save_close_issue_button.grid(row = 5) #define the button that will discard an issue and close the window self.save_close_issue_button = Button(self.create_issue_window, text = "Discard", command = self.create_issue_window.destroy) self.save_close_issue_button.grid(row = 5, column = 1) #This method will save the current data as an new line in the def save_issue_method(self, issue_dict): #set the latest issue values to the dictionary issue_dict["issue time"] = self.issue_datetime_text.get("1.0", "end-1c") issue_dict["issue summary"] = self.issue_summary_text.get("1.0", "end-1c") issue_dict["issue description"] = self.issue_description_text.get("1.0", "end-1c") issue_dict["issue GPS"] = self.issue_GPS_text.get("1.0", "end-1c") #open file for appending a new new issue at the end f = open(issue_dict["file name"], "a") # Write the "Issue ID ||| Time&Date ||| Summary ||| Description ||| GPS coordinates ||| Project ||| project version ||| HW ||| Tester" values in the file f.write("%d ||| %s ||| %s ||| %s ||| %s ||| %s ||| %s ||| %s ||| %s \n" %(issue_dict["issue index"], issue_dict["issue time"], issue_dict["issue summary"], issue_dict["issue description"], issue_dict["issue GPS"], issue_dict["project name"], issue_dict["project version"], issue_dict["HW setup"], issue_dict["tester"] )) f.close() self.create_issue_window.destroy()
class DATAin: def __init__(self, maestro): # Atributo de conteo''' self.botonClics = 0 self.bandDATA = 3 self.operacion="" self.cliente = '' self.Producto = '' self.alturaDATA = 0 self.anchoDATA = 0 self.largoDATA = 0 self.Datos = [] for i in range (7): self.Datos.append('') self.consoleSQL = PSQLmerma1() #gg = Tkk.Notebook(maestro) self.top = Toplevel(maestro) self.top.title('Introduce medidas de la caja') self.top.update_idletasks() # w = self.top.winfo_screenwidth() # h = self.top.winfo_screenheight() # size = tuple(int(_) for _ in self.top.geometry().split('+')[0].split('x')) # x = w/2 - size[0]/2 # y = h/2 - size[1]/2 # print size + (x, y) # self.top.geometry("+150+60") #self.top.iconbitmap('/home/pi/Desktop/ProgGUI/GUI/resources/ICO/IconoBCT.ico') #MARCO3 ESEL LINEZO DONDE SE DIBUJAN LAS PESTAÑAS self.marco3 = TTK.Notebook(self.top) # CREAMOS EL MARCO PARA CADA UNA DE LAS PESTAÑAS self.page1 = TTK.Frame(self.marco3) self.page2 = TTK.Frame(self.marco3) self.page3 = TTK.Frame(self.marco3) self.page4 = TTK.Frame(self.marco3) self.page5 = TTK.Frame(self.marco3) # AGREGAMOS EL MARCO A LAS PESTAÑAS Y SU NOMBRE self.marco3.add(self.page1, text='Dimensiones de la caja') self.marco3.add(self.page2, text='Descripción de la caja') self.marco3.add(self.page3, text='Descripción de la prueba') self.marco3.add(self.page4, text='Datos del cliente') self.marco3.add(self.page5, text='Resumen de datos') self.marco3.grid() # AGREGAGOS CONTENIDO A PESTAÑA 1 self.IMGcaja = PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/caja.png') self.IMGancho= PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/anchoSelect.png') self.IMGlargo= PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/largoSelect.png') self.IMGalto = PhotoImage(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/altoSelect.png') self.cajaLB = Label(self.page1, image = self.IMGcaja) self.cajaLB.grid(row = 0, column = 4, rowspan = 5, columnspan = 3) self.txtLB = 'Seleccione un botón e ingrese \n las medidas en cm' self.LB = Label(self.page1, font =('Helvetica', 15), text = self.txtLB) self.LB.grid(row = 0, column = 0, columnspan = 4) self.CBdata = Text(self.page1, state="disabled", width=40, height=2, font=("Helvetica",15)) self.CBdata.grid(row = 1, column = 0, columnspan = 4) self.anchoL = Label(self.page1, font =('Helvetica', 15), text = "") self.anchoL.grid(row =4, column = 4, sticky = 's') self.BTNancho = Button(self.page1, width=5, height=1, font=("Helvetica",15), text = 'Ancho', command =lambda: self.selectCB('an')) self.BTNancho.grid(row = 5, column = 4) self.largoL = Label(self.page1, font =('Helvetica', 15), text = "") self.largoL.grid(row =4, column = 5, sticky = 's') self.BTNlargo = Button(self.page1, width=5, height=1, font=("Helvetica",15), text = 'Largo', command =lambda: self.selectCB('la')) self.BTNlargo.grid(row = 5, column = 5) self.altoL = Label(self.page1, font =('Helvetica', 15), text = "") self.altoL.grid(row =4, column = 6, sticky = 's') self.BTNalto = Button(self.page1, width=5, height=1, font=("Helvetica",15), text = 'Alto', command =lambda: self.selectCB('al')) self.BTNalto.grid(row = 5, column = 6) boton1 = self.crearBoton(1) boton2 = self.crearBoton(2) boton3 = self.crearBoton(3) boton4 = self.crearBoton(4) boton5 = self.crearBoton(5) boton6 = self.crearBoton(6) boton7 = self.crearBoton(7) boton8 = self.crearBoton(8) boton9 = self.crearBoton(9) boton0 = self.crearBoton(0,ancho=7) botonErase = self.crearBoton(u"\u232B",escribir=False) botonErase['background'] = "red" botonErase.grid(row = 2, column = 3) botonEnter = self.crearBoton(u"\u21B5",escribir=False) botonEnter['background'] = "green" botonEnter.grid(row = 3, column = 3) botondot = self.crearBoton('.') #Ubicación de los botones botones=[boton7, boton8, boton9, boton4, boton5, boton6, boton1, boton2, boton3, boton0] contador=0 for fila in range(2,5): for columna in range(3): botones[contador].grid(row=fila,column=columna) contador+=1 #Ubicar el último botón al final botones[contador].grid(row=5,column=0,columnspan=2) botondot.grid(row = 5, column = 2) # AGREGAGOS CONTENIDO A PESTAÑA 2 Label(self.page2, font =('Helvetica', 15), text = 'Seleccione:')\ .grid(row = 0, column = 0,columnspan = 5) Label(self.page2, font =('Helvetica', 15), text = 'Estilo de caja')\ .grid(row = 1, column = 0) self.listCaja = Combobox(self.page2, state="readonly", values = ["Caja troquelada", "Caja est" + u"\xe1" + "ndar"], font =('Helvetica', 15)) self.listCaja.grid(row = 2, column = 0) Label(self.page2, font =('Helvetica', 15), text = ' ')\ .grid(row = 2, column = 1) Label(self.page2, font =('Helvetica', 15), text = 'Tipo de flauta')\ .grid(row = 1, column = 2) self.listFlauta = Combobox(self.page2, state="readonly", values = ["Corrugado sencillo B", "Corrugado sencillo C", "Corrugado sencillo E", "Doble corrugado BC", "Doble corrugado EB"], font =('Helvetica', 15)) self.listFlauta.grid(row = 2, column = 2) Label(self.page2, font =('Helvetica', 15), text = ' ')\ .grid(row = 2, column = 3) Label(self.page2, font =('Helvetica', 15), text = 'Dirección de la flauta')\ .grid(row = 1, column = 4) self.listFlautaD= Combobox(self.page2, state="readonly", values = ["Horizontal", "Vertical"], font =('Helvetica', 15)) self.listFlautaD.grid(row = 2, column = 4) Label(self.page2, font =('Helvetica', 15), text = ' ')\ .grid(row = 3, column = 0, columnspan = 3) Label(self.page2, font =('Helvetica', 15), text = 'Grado del material')\ .grid(row = 4, column = 0) self.listGradoM= Combobox(self.page2, state="readonly", values = ["No aplica", "20 ECT", "21 ECT", "23 ECT", "26 ECT", "29 ECT", "32 ECT", "44 ECT", "48 ECT", "50 ECT", "61 ECT", "71 ECT"], font =('Helvetica', 15)) self.listGradoM.grid(row = 5, column = 0) Label(self.page2, font =('Helvetica', 15), text = 'Tipo de unión')\ .grid(row = 4, column = 2) self.listUnion= Combobox(self.page2, state="readonly", values = ["Pegado", "Grapado", "Armado automático"], font =('Helvetica', 15)) self.listUnion.grid(row = 5, column = 2) # AGREGAMOS CONTEIDO A PAGE3 Label(self.page3, font =('Helvetica', 15), text = 'Método de cierre')\ .grid(row = 0, column = 0) self.listCierre= Combobox(self.page3, state="readonly", values = ["Conforme a la TAPPI T 804", "Otro", "No aplica"], font =('Helvetica', 15)) self.listCierre.grid(row = 1, column = 0) Label(self.page3, font =('Helvetica', 15), text = ' ')\ .grid(row = 0, column = 1) Label(self.page3, font =('Helvetica', 15), text = 'Orientación de la prueba')\ .grid(row = 0, column = 2) self.listOrientaC= Combobox(self.page3, state="readonly", values = ["Arriba a abajo", "Extremo a extremo", "Lado a lado"], font =('Helvetica', 15)) self.listOrientaC.grid(row = 1, column = 2) self.IMGbct = Image.open(file = '/home/pi/Desktop/InterfazG-BCT/resources/img/cajaDATA/CajaBIedit.png') self.cajaBCT = Label(self.page3, image = self.IMGbct) self.cajaBCT.grid(row = 2, column = 0, columnspan = 3) # AGREGAMOS CONTENIDO A PAGE 4 self.txtLB = 'Ingresar datos o buscar por número de pedido' self.state = TTK.Label(self.page4, font =('Helvetica', 15), text = self.txtLB) self.state.grid(row = 0, column = 0, columnspan = 12) boton1 = self.crearBotonP4(1) boton2 = self.crearBotonP4(2) boton3 = self.crearBotonP4(3) boton4 = self.crearBotonP4(4) boton5 = self.crearBotonP4(5) boton6 = self.crearBotonP4(6) boton7 = self.crearBotonP4(7) boton8 = self.crearBotonP4(8) boton9 = self.crearBotonP4(9) boton0 = self.crearBotonP4(0) botonQ = self.crearBotonP4('Q') botonW = self.crearBotonP4('W') botonE = self.crearBotonP4('E') botonR = self.crearBotonP4('R') botonT = self.crearBotonP4('T') botonY = self.crearBotonP4('Y') botonU = self.crearBotonP4('U') botonI = self.crearBotonP4('I') botonO = self.crearBotonP4('O') botonP = self.crearBotonP4('P') botonA = self.crearBotonP4('A') botonS = self.crearBotonP4('S') botonD = self.crearBotonP4('D') botonF = self.crearBotonP4('F') botonG = self.crearBotonP4('G') botonH = self.crearBotonP4('H') botonJ = self.crearBotonP4('J') botonK = self.crearBotonP4('K') botonL = self.crearBotonP4('L') botonNN= self.crearBotonP4('Ñ') botonZ = self.crearBotonP4('Z') botonX = self.crearBotonP4('X') botonC = self.crearBotonP4('C') botonV = self.crearBotonP4('V') botonB = self.crearBotonP4('B') botonN = self.crearBotonP4('N') botonM = self.crearBotonP4('M') botondot = self.crearBotonP4('.') botonguion = self.crearBotonP4('-') botonguionb = self.crearBotonP4(',') botonErase = self.crearBotonP4(u"\u232B",escribir=False) botonErase['background'] = "red" botonErase.grid(row = 3, column = 11) botonEnter = self.crearBotonP4(u"\u21B5",escribir=False,alto=2) botonEnter['background'] = "green" botonEnter.grid(row = 1, column = 11, rowspan = 2, sticky = 's') botonSpace = Button(self.page4, text=u"\u2423", width=5, height=1, font=("Helvetica",15), command=lambda:self.clickP4(' ',True)) botonSpace.grid(row = 4, column = 11) #Ubicación de los botones botones= [boton1, boton2, boton3, boton4, boton5, boton6, boton7, boton8, boton9, boton0, botonQ, botonW, botonE, botonR, botonT, botonY, botonU, botonI, botonO, botonP, botonA, botonS, botonD, botonF, botonG, botonH, botonJ, botonK, botonL, botonNN, botonZ, botonX, botonC, botonV, botonB, botonN, botonM, botondot, botonguion, botonguionb] contador=0 for fila in range(1,5): for columna in range(10): botones[contador].grid(row=fila,column=columna) contador+=1 self.ChkSe = IntVar() self.RBCliente = Radiobutton(self.page4, text = 'Cliente',font =('Helvetica', 15), variable = self.ChkSe, value = 1) self.RBCliente.grid(row = 5, column = 2, columnspan = 2, sticky = 'w') self.RBProducto = Radiobutton(self.page4, text = 'Producto',font =('Helvetica', 15), variable = self.ChkSe, value = 2) self.RBProducto.grid(row = 5, column = 4, columnspan = 2, sticky = 'w') self.RBBuscar = Radiobutton(self.page4, text = 'Buscar por pedido',font =('Helvetica', 15), variable = self.ChkSe, value = 3) self.RBBuscar.grid(row = 5, column = 6, columnspan = 3, sticky = 'w') self.CBdata2 = Text(self.page4, state="disabled", width=40, height=1, font=("Helvetica",15)) self.CBdata2.grid(row = 6, column = 0, columnspan = 12) self.clienteL = TTK.Label(self.page4, font =('Helvetica', 15), text = 'Cliente:') self.clienteL.grid(row = 7, column = 0, columnspan = 11, sticky = 'w') self.ProductoL = TTK.Label(self.page4, font =('Helvetica', 15), text = 'Producto:') self.ProductoL.grid(row = 8, column = 0, columnspan = 11, sticky = 'w') # AGREGAMOS CONTENIDO A PAGE 5 Label(self.page5, font =('Helvetica', 15), text = '* *').grid(row = 0, # text = '123456789_123456789_123456789_123465789_123456789_123456789_123456789_123456789_12', #text = '____________________________').grid(row = 0, column = 0, columnspan = 3) Label(self.page5, font =('Helvetica', 15), text = '_________________________________________').grid(row = 0, column = 0,) Label(self.page5, font =('Helvetica', 15), text = '_________________________________________').grid(row = 0, column = 1) # Label(self.page5, # font =('Helvetica', 15), # text = '___________________________').grid(row = 0, # column = 2) Label(self.page5, font =('Helvetica', 15), text = 'Verifique los datos ingresado:').grid(row = 0, column = 0, columnspan = 2) self.StxtCliente = StringVar(value = '*') self.txtCliente = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Cliente:') self.txtCliente.grid(row = 1, column = 0, sticky = 'w') self.txtClienteL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtCliente) self.txtClienteL.place(x = 79, y = 28) self.StxtProducto = StringVar(value = '*') self.txtProducto = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Producto: ') self.txtProducto.grid(row = 2, column = 0, columnspan = 2, sticky = "w") self.txtProductoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtProducto) self.txtProductoL.place(x = 99, y = 56) self.StxtLargo = StringVar(value = '*') self.txtLargo = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Largo:') self.txtLargo.grid(row = 3, column = 0, sticky = "w") self.txtLargoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtLargo) self.txtLargoL.place(x= 69, y = 84) self.StxtAlto = StringVar(value = '*') self.txtAlto = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Alto:') self.txtAlto.place(x = 310, y = 84) self.txtAltoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtAlto) self.txtAltoL.place(x = 363, y = 84) self.StxtAncho = StringVar(value = '*') self.txtAncho = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Ancho: ') self.txtAncho.place(x= 590, y = 84) self.txtAnchoL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtAncho) self.txtAnchoL.place(x= 666, y = 84) self.StxtStlCj = StringVar(value = '*') self.txtStlCj = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Estilo caja:') self.txtStlCj.grid(row = 4, column = 0, sticky = "w") self.txtStlCjL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtStlCj) self.txtStlCjL.place(x= 110, y = 112) self.StxtTpFlt = StringVar(value = '*') self.txtTpFlt = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Tipo de flauta:') self.txtTpFlt.grid(row = 4, column = 1, sticky = "w") self.txtTpFltL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtTpFlt) self.txtTpFltL.place(x= 594, y = 112) self.StxtDrccnFlt = StringVar(value = '*') self.txtDrccnFlt = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Dirección de la flauta: ') self.txtDrccnFlt.grid(row = 5, column = 0, sticky = "w") self.txtDrccnFltL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtDrccnFlt) self.txtDrccnFltL.place(x= 216, y = 140) self.StxtGrdMtrl = StringVar(value = '*') self.txtGrdMtrl = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Grado del material: ') self.txtGrdMtrl.grid(row = 5, column = 1, sticky = "w") self.txtGrdMtrlL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtGrdMtrl) self.txtGrdMtrlL.place(x= 640, y = 140) self.StxtTpUnn = StringVar(value = '*') self.txtTpUnn = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Tipo de unión: ') self.txtTpUnn.grid(row = 6, column = 0, sticky = "w") self.txtTpUnnL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtTpUnn) self.txtTpUnnL.place(x= 138, y = 168) self.StxtMtdCrr = StringVar(value = '*') self.txtMtdCrr = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Método de cierre: ') self.txtMtdCrr.grid(row = 6, column = 1, sticky = "w") self.txtMtdCrrL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtMtdCrr) self.txtMtdCrrL.place(x= 623, y = 168) self.StxtOrntcn = StringVar(value = '*') self.txtOrntcn = Label(self.page5, font = ('Helvetica', 15, 'italic'), text = '*Orientación de la prueba: ') self.txtOrntcn.grid(row = 7, column = 0, sticky = "w") self.txtOrntcnL = Label(self.page5, font = ('Helvetica', 15), textvariable = self.StxtOrntcn) self.txtOrntcnL.place(x= 243, y = 197) cc = Button(self.page5, font = ('Helvetica', 15, "bold"), text = 'Cerrar', bg = "red", command = self.cerrarB)#.place(x = 20, y = 20) cc.grid(row = 8, column = 0, columnspan = 2) # OBTENER LO QUE CONTIENEN CADA LISTA self.listCaja.bind("<<ComboboxSelected>>", self.getList) self.listCierre.bind("<<ComboboxSelected>>", self.getList) self.listFlauta.bind("<<ComboboxSelected>>", self.getList) self.listFlautaD.bind("<<ComboboxSelected>>", self.getList) self.listGradoM.bind("<<ComboboxSelected>>", self.getList) self.listOrientaC.bind("<<ComboboxSelected>>", self.getList) self.listUnion.bind("<<ComboboxSelected>>", self.getList) self.top.protocol("WM_DELETE_WINDOW", self.cerrar) def motion(self, event): self.posy.set(event.y) self.posx.set(event.x) def selectCB(self,selecc): if selecc == 'al': self.LB['text'] = 'Usted selecciono alto' self.cajaLB['image'] = self.IMGalto self.bandDATA = 0 elif selecc == 'an': self.LB['text'] = 'Usted selecciono ancho' self.cajaLB['image'] = self.IMGancho self.bandDATA = 1 elif selecc == 'la': self.LB['text'] = 'Usted selecciono largo' self.cajaLB['image'] = self.IMGlargo self.bandDATA = 2 def crearBoton(self, valor, escribir=True, ancho=5, alto=1): return Button(self.page1, text=valor, width=ancho, height=alto, font=("Helvetica",15), command=lambda:self.click(valor,escribir)) def crearBotonP4(self, valor, escribir=True, ancho=5, alto=1): return Button(self.page4, text=valor, width=ancho, height=alto, font=("Helvetica",15), command=lambda:self.clickP4(valor,escribir)) def conteo(self): self.botonClics += 1 self.btnCLK['text'] = 'Clics totales = ' + str(self.botonClics) def click(self, texto, escribir): if not escribir: if texto==u"\u21B5" and self.operacion!="" and self.bandDATA != 3: if self.bandDATA == 0: try: self.alturaDATA = float(self.operacion) self.LB['text'] = 'Usted ingreso ' + str(self.alturaDATA) + 'cm en altura' self.altoL['text'] = str(self.alturaDATA) + 'cm' self.StxtAlto.set(str(self.alturaDATA) + 'cm') self.changeTXT(self.StxtAlto, str(self.alturaDATA) + 'cm', self.txtAlto, 'Alto:') except ValueError: self.LB['text'] = 'Atención \n El dato ingresado no es un número válido,\n favor de verificar' elif self.bandDATA == 1: try: self.anchoDATA = float(self.operacion) self.LB['text'] = 'Usted ingreso ' + str(self.anchoDATA) + 'cm en ancho' self.changeTXT(self.StxtAncho, str(self.anchoDATA) + 'cm', self.txtAncho, 'Ancho:') self.anchoL['text'] = str(self.anchoDATA) + 'cm' except ValueError: self.LB['text'] = 'Atención \n El dato ingresado no es un número válido,\n favor de verificar' elif self.bandDATA == 2: try: self.largoDATA = float(self.operacion) self.LB['text'] = 'Usted ingreso ' + str(self.largoDATA ) + 'cm en largo' self.changeTXT(self.StxtLargo, str(self.largoDATA ) + 'cm', self.txtLargo, 'Largo:') self.largoL['text'] = str(self.largoDATA ) + 'cm' except ValueError: self.LB['text'] = 'Atención \n El dato ingresado no es un número válido,\n favor de verificar' print 'Hola desde borrar' self.operacion = '' self.limpiarPantalla() elif texto==u"\u232B": self.operacion="" self.limpiarPantalla() #Mostrar texto else: self.operacion+=str(texto) self.mostrarEnPantalla(texto) return def clickP4(self, texto, escribir): self.ChkSel = int(self.ChkSe.get()) print self.ChkSel if not escribir: if texto==u"\u21B5" and self.operacion!="" and self.ChkSel != 0: print 'gg' if self.ChkSel == 1: self.cliente = self.operacion self.clienteL['text'] = 'Cliente: ' + str(self.cliente) self.changeTXT(self.StxtCliente, str(self.cliente), self.txtCliente, 'Cliente:') elif self.ChkSel == 2: self.Producto = self.operacion self.ProductoL['text'] = 'Producto: ' + str(self.Producto) self.changeTXT(self.StxtProducto, str(self.Producto), self.txtProducto, 'Producto:') elif self.ChkSel == 3: self.top.iconify() self.consoleSQL.consulta('pedido', str(self.operacion)) try: self.cliente = self.consoleSQL.cliente self.clienteL['text'] = 'Cliente: ' + str(self.cliente) self.changeTXT(self.StxtCliente, str(self.cliente), self.txtCliente, 'Cliente:') self.Producto = self.consoleSQL.producto self.ProductoL['text'] = 'Producto: ' + str(self.Producto) self.changeTXT(self.StxtProducto, str(self.Producto), self.txtProducto, 'Producto:') except: tkMessageBox.showerror('Atención','No se encontró el pedido favor de verificar') self.operacion = '' self.limpiarPantalla(2) elif texto==u"\u232B": self.operacion="" self.limpiarPantalla(2) elif self.ChkSel == 0: self.top.iconify() tkMessageBox.showerror("Atención", 'Debe seleccionar una opción') #Mostrar texto else: self.operacion+=str(texto) self.mostrarEnPantalla(texto, 2) self.top.deiconify() return def changeTXT(self, StringVarTXT, setStr, LabelTXT, txtLabel): StringVarTXT.set(setStr) LabelTXT['text'] = txtLabel LabelTXT['font'] = ('Helvetica', 15, "bold") def limpiarPantalla(self, cb = 1): if cb ==2: self.CBdata2.configure(state="normal") self.CBdata2.delete("1.0", END) self.CBdata2.configure(state="disabled") else: self.CBdata.configure(state="normal") self.CBdata.delete("1.0", END) self.CBdata.configure(state="disabled") return def mostrarEnPantalla(self, valor, cb = 1): if cb == 2: self.CBdata2.configure(state="normal") self.CBdata2.insert(END, valor) self.CBdata2.configure(state="disabled") else: self.CBdata.configure(state="normal") self.CBdata.insert(END, valor) self.CBdata.configure(state="disabled") return def getList(self, event): self.CheckList(self.listCaja, 0, self.StxtStlCj, 'Estilo caja: ', self.txtStlCj) self.CheckList(self.listFlauta, 1, self.StxtTpFlt, 'Tipo de flauta: ', self.txtTpFlt) self.CheckList(self.listFlautaD, 2, self.StxtDrccnFlt, 'Dirección de la flauta: ', self.txtDrccnFlt) self.CheckList(self.listGradoM, 3, self.StxtGrdMtrl, 'Grado del material: ', self.txtGrdMtrl) self.CheckList(self.listUnion, 4, self.StxtTpUnn, 'Tipo de unión: ', self.txtTpUnn) self.CheckList(self.listCierre, 5, self.StxtMtdCrr, 'Método de cierre: ', self.txtMtdCrr) self.CheckList(self.listOrientaC, 6, self.StxtOrntcn, 'Orientación de la prueba: ', self.txtOrntcn) #hola def CheckList(self, lista, num_list, StrVarL, txt, labelTXT,): gg = lista.get() print gg if gg != '': self.Datos[num_list] = lista.get() if num_list == 0: if self.Datos[0] == (u'Caja est\xe1ndar'): self.Datos[0] = str('Caja estándar') elif num_list == 4: if self.Datos[4] == (u'Armado autom\xe1tico'): self.Datos[4] = ('Armado automático') StrVarL.set(self.Datos[num_list]) labelTXT['text'] = txt labelTXT['font'] = ('Helvetica', 15, "bold") def cerrar(self): self.top.iconify() tkMessageBox.showinfo("Atención", "Si desea salir, debe hacerlo desde el botón ubicado en la pestaña de Resumen de datos.") self.top.deiconify() def cerrarB(self): self.top.iconify() respuesta=tkMessageBox.askyesno("Atención", "Usted esta a punto de salir, ¿Los datos ingresados son los correctos?") if respuesta==True: self.top.destroy() try: self.top.deiconify() except: print "Ventana cerrada" #ventana = Tk() #final = DATAin(ventana) #ventana.mainloop()
def showAll(self): Ventana2 = Toplevel(self.master) try: Poss = [0, 50] maxi = self.buscMax() if int(maxi) < Poss[1]: Poss[1] = int(maxi) Ventana2.configure(height=45, width=25, bg="#4a4a4a") Ventana2.resizable(0, 0) frameAux = Frame(Ventana2, bg="#4a4a4a", borderwidth=0) frameAux.pack(fill=BOTH) scrolly = Scrollbar(frameAux, orient=VERTICAL) self.listbox1 = Listbox(frameAux, width=90, background="#4a4a4a", borderwidth=0, fg="#FFFFFF", highlightcolor="#4d86a1", highlightbackground="#4d86a1", yscrollcommand=scrolly.set) self.listbox1.config(font=("", 11)) self.listbox1.pack(side=LEFT) scrolly.pack(side=RIGHT, fill=Y) scrolly.configure(command=self.yview) self.load50(Poss) if sys.platform.startswith('win32'): ruta = "image\\GoBack.png" ruta2 = "image\\GoOn.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/GoBack.png" ruta2 = "image/GoOn.png" load = Image.open(ruta) render = ImageTk.PhotoImage(load) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) backbutton1 = Button(Ventana2, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "-")) backbutton1.image = render backbutton1.pack(side=LEFT) backbutton2 = Button(Ventana2, image=render2, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "+")) backbutton2.image = render2 backbutton2.pack(side=LEFT) backbutton3 = Button( Ventana2, height=2, width=10, text="Back", command=lambda: self.Switch(self.master, Ventana2)) backbutton3.pack(side=RIGHT) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar")
class ListBoxChoice(object): def __init__(self, master=None, title=None, message=None, clist=[], newmessage=None): self.master = master self.value = None self.newmessage = newmessage self.list = clist[:] self.modalPane = Toplevel(self.master) self.modalPane.transient(self.master) self.modalPane.grab_set() self.modalPane.bind("<Return>", self._choose) self.modalPane.bind("<Escape>", self._cancel) if title: self.modalPane.title(title) if message: Label(self.modalPane, text=message).pack(padx=5, pady=5) listFrame = Frame(self.modalPane) listFrame.pack(side=TOP, padx=5, pady=5) scrollBar = Scrollbar(listFrame) scrollBar.pack(side=RIGHT, fill=Y) self.listBox = Listbox(listFrame, selectmode=SINGLE) self.listBox.pack(side=LEFT, fill=Y) scrollBar.config(command=self.listBox.yview) self.listBox.config(yscrollcommand=scrollBar.set) self.list.sort() for item in self.list: self.listBox.insert(END, item) if newmessage is not None: newFrame = Frame(self.modalPane) newFrame.pack(side=TOP, padx=5) Label(newFrame, text=newmessage).pack(padx=5, pady=5) self.entry = Entry(newFrame, width=30) self.entry.pack(side=TOP, padx=5) self.entry.bind("<Return>", self._choose_entry) buttonFrame = Frame(self.modalPane) buttonFrame.pack(side=BOTTOM) chooseButton = Button(buttonFrame, text="Choose", command=self._choose_entry) chooseButton.pack() cancelButton = Button(buttonFrame, text="Cancel", command=self._cancel) cancelButton.pack(side=RIGHT) def _choose_entry(self, event=None): if self.newmessage is None: self._choose() return v = self.entry.get().strip() if v == None or v == "": self._choose() return self.value = v self.modalPane.destroy() def _choose(self, event=None): try: firstIndex = self.listBox.curselection()[0] self.value = self.list[int(firstIndex)] except IndexError: self.value = None self.modalPane.destroy() def _cancel(self, event=None): self.modalPane.destroy() def returnValue(self): self.master.wait_window(self.modalPane) return self.value
class Docview: def __init__(self, master, fn, **kwargs): self.file = fn self.widget = None self.text = Text() self.frame = master self.location = kwargs.get('location', None) self.wait = kwargs.get('wait', None) self.find = kwargs.get('find', None) self.delete_img = PhotoImage(file='delete.pbm') self.up_img = PhotoImage(file='1uparrow.pbm') self.down_img = PhotoImage(file='1downarrow.pbm') self.upbutn = Button() self.dnbutn = Button() self.deletebutn = Button() self.entry = None self.doc = '' def Search(self, pattern): ''' normal top-down search :param pattern: :return: ''' try: self.text.tag_remove('hilight', '1.0', 'end') ind = self.text.search(pattern, '1.0', stopindex="end", nocase=True) self.text.mark_set("insert", ind) self.text.see("insert") nchar = len(pattern) self.text.tag_add('hilight', ind, ind + "+{}c".format(nchar)) except: pass def RecursiveSearch(self, pattern, upward=False): ''' Search forward from current position. Search backward if upward is True. :param pattern: search pattern :param upward: reverse search if true :return: Null ''' if len(pattern) == 0: ind = '1.0' if upward else 'end' self.text.mark_set("insert", ind) self.text.see("insert") return try: insert = self.text.index("insert") if upward: point = insert + "-1c" ind = self.text.search(pattern, point, stopindex="1.0", backwards=True, nocase=True) else: point = insert + "+1c" ind = self.text.search(pattern, point, stopindex="end", nocase=True) self.text.mark_set("insert", ind) self.text.see("insert") self.text.tag_remove('hilight', '1.0', 'end') nchar = len(pattern) self.text.tag_add('hilight', ind, ind + "+{}c".format(nchar)) self.text.update() except: pass def SearchUp(self): pattern = str(self.entry.get()) self.RecursiveSearch(pattern, True) def SearchDn(self): pattern = str(self.entry.get()) self.RecursiveSearch(pattern, False) def FindEntry(self, event): '''triggered by keyrelease event in find entry box''' pattern = str(self.entry.get()) nchar = len(pattern) self.text.tag_remove('hilight', '1.0', 'end') if nchar == 0: return try: ind = self.text.search(pattern, "1.0", stopindex="end", nocase=True) self.text.mark_set("insert", ind) self.text.see("insert") self.text.tag_add('hilight', ind, ind + "+{}c".format(nchar)) self.text.update() except: pass def DeleteSearch(self): self.entry.delete(0, 'end') self.text.tag_remove('hilight', '1.0', 'end') def Popup(self): if not self.doc: with open(self.file, 'r') as fh: self.doc = fh.read() if self.widget: # widget already open if self.frame: self.widget.lift(aboveThis=self.frame) return #print 'length of doc ', len(self.doc) self.widget = Toplevel() if self.find: self.sframe = Frame(self.widget) self.sframe.pack() self.upbutn = Button(self.sframe, width=17, command=self.SearchUp, image=self.up_img) self.upbutn.pack(side='left') self.dnbutn = Button(self.sframe, width=17, command=self.SearchDn, image=self.down_img) self.dnbutn.pack(side='left') self.entry = Entry(self.sframe, width=50) self.entry.bind('<KeyRelease>', self.FindEntry) self.entry.pack(side='left') self.deletebutn = Button(self.sframe, width=17, command=self.DeleteSearch) self.deletebutn.config(image=self.delete_img) self.deletebutn.pack(side='left') width = max([len(line) for line in self.doc.split('\n')]) height = min([self.doc.count('\n') + 1, 40]) self.text = Text(self.widget, width=width, height=height) self.text.tag = self.text.tag_configure('hilight', background='#ffff00') self.text.insert("1.0", self.doc) self.text.pack() if self.location and self.frame: dx, dy = self.location w = self.text.winfo_width() h = self.text.winfo_height() x = self.frame.winfo_x() y = self.frame.winfo_y() loc = "%dx%d+%d+%d" % (600, 400, x + dx, y + dy) self.widget.geometry(loc) if self.wait: self.widget.focus_set() self.widget.grab_set() if self.frame: self.widget.transient(master=self.frame) self.widget.wait_window(self.widget) if self.frame: self.widget.lift(aboveThis=self.frame) self.widget.protocol("WM_DELETE_WINDOW", self.Kill) def Kill(self): self.widget.destroy() self.widget = None
def startPVstring_tk(self): top = Toplevel() app = PVstring_tk(self, top) app.mainloop() # please destroy me or I'll continue to run in background top.destroy()
class ChessBoard(Frame): def __init__(self, master=None, title="Chess"): Frame.__init__(self, master) self.master = master self.master.title(title) self.white = ["ROOK", "KNIGHT", "BISHOP", "QUEEN", "KING", "BISHOP.", "KNIGHT.", "ROOK."] self.black = [w.lower() for w in self.white] self.white_pawn = PhotoImage(file="White_Pawn.gif") self.black_pawn = PhotoImage(file="Black_Pawn.gif") self.black_pieces = [PhotoImage(file="Black_Rook.gif"), PhotoImage(file="Black_Knight.gif"), PhotoImage(file="Black_Bishop.gif"), PhotoImage(file="Black_Queen.gif"), PhotoImage(file="Black_King.gif"), PhotoImage(file="Black_Bishop1.gif"), PhotoImage(file="Black_Knight1.gif"), PhotoImage(file="Black_Rook1.gif")] self.white_pieces = [PhotoImage(file="White_Rook.gif"), PhotoImage(file="White_Knight.gif"), PhotoImage(file="White_Bishop.gif"), PhotoImage(file="White_Queen.gif"), PhotoImage(file="White_King.gif"), PhotoImage(file="White_Bishop1.gif"), PhotoImage(file="White_Knight1.gif"), PhotoImage(file="White_Rook1.gif")] self.piece = "" self.piece_color = "" self.original_row = int() self.original_col = int() self.image = () self.locations = () self.button_location = {} self.black_king_locations = [] self.white_king_locations = [] self.turn = 1 self.board_setup() self.get_grid_info() self.place_pieces() # self.directions_window() self.bind("<Destroy>", self.exit) self.mainloop() # create the board in the GUI def board_setup(self, _=None): def set_up_GUI(): menuBar = Menu(self) self.master.config(menu=menuBar) fileMenu = Menu(menuBar, tearoff=0) menuBar.add_cascade(label="File", menu=fileMenu) fileMenu.add_command(label="New", command=self.new_game) fileMenu.add_command(label="Exit", command=self.exit) fileMenu.insert_separator(fileMenu.index(END)) self.labelframe = Frame(self.master) self.labelframe.grid(column=0, row=0, sticky="W", padx=13) def label_helper(row, column, labels="ABCDEFGH"): for c in labels: Button(self.labelframe, text=c, state="disabled", bg="Grey", fg="white", justify="center", width=20, bd=8, relief=RAISED).grid(row=row, column=column) column += 1 def row_label_helper(row, column, labels="87654321"): for c in labels: Label(self.labelframe, text=c, padx=15).grid(row=row, column=column) row += 1 # Sets up the black white pattern on the board # Makes the board wait for an event (mouse button press) def row_helper(): for row in range(1, 9): for column in range(1, 9): if row % 2 == 0: bg = "Black" if column % 2 == 0: bg = "White" else: bg = "White" if column % 2 == 0: bg = "Black" b1 = Button(self.labelframe, bg=bg, width=20, height=6, bd=8, relief=RAISED) b1.grid(row=row, column=column, sticky="N") b1.bind("<Button 1>", lambda e=row, i=row, k=column: self.movement(i, k)) set_up_GUI() label_helper(0, 1) row_label_helper(1, 0) row_helper() row_label_helper(1, 9) label_helper(9, 1) # Gets the location of each button def get_grid_info(self): for key in self.labelframe.children.values(): self.locations = int(key.grid_info()['row']), int(key.grid_info()['column']) self.button_location[self.locations] = key @staticmethod def directions_window(): directions_window = Tk() directions_window.title("How To Operate The Board") label = Label(directions_window, text="Left Click to pick a piece \n Right Click to place the piece", height=20, width=50) label.pack() # Clears the board backgrounds removing all green boxes (possible moves) def clear_board(self): for row1 in range(1, 9): for column1 in range(1, 9): if row1 % 2 == 0: bg = "Black" if column1 % 2 == 0: bg = "White" else: bg = "White" if column1 % 2 == 0: bg = "Black" self.button_location[row1, column1]["bg"] = bg # places the text (how the pieces move) and the images of each piece def place_pieces(self): for labels in self.white: self.button_location[8, self.white.index(labels) + 1].config(text=labels, fg="DimGray") x = 0 for images in self.white_pieces: x += 1 self.button_location[8, x].config(image=images, width=144, height=95) for labels in self.black: self.button_location[1, self.black.index(labels) + 1].config(text=labels, fg="OrangeRed") x = 0 for images in self.black_pieces: x += 1 self.button_location[1, x].config(image=images, width=144, height=95) for x in range(1, 9): self.button_location[7, x].config(text="PAWN", fg="DimGray", image=self.white_pawn, width=144, height=95) self.button_location[2, x].config(text="pawn", fg="OrangeRed", image=self.black_pawn, width=144, height=95) # wrapper for the Rook, Bishop and Knight movement @staticmethod def movement_check(error_check): def wrapper(): try: error_check() except KeyError: pass return wrapper # Left clicking on a piece highlights the allowed boxes green depending on these functions # Right clicking on that green box would move the piece def pawn_movement(self, row, col, color): self.clear_board() if color == "DimGray": piece = "OrangeRed" x = -1 y = -2 z = 7 else: piece = "DimGray" x = 1 y = 2 z = 2 # If the pawn reaches the other side, pop up window for new piece if row == 1: self.new_piece_gui(row, col, color) if row == 8: self.new_piece_gui(row, col, color) # Makes sure the spot in front of the piece is empty if self.button_location[row + x, col]["text"] == "": if row == z: if self.button_location[(row + x), col + 1]["fg"] == piece: self.button_location[(row + x), (col + 1)]["bg"] = "Green" self.button_location[(row + x), col]["bg"] = "Green" if self.button_location[(row + y), col]["text"] == "": self.button_location[(row + y), col]["bg"] = "Green" else: if self.button_location[(row + x), col]["text"] == "": self.button_location[(row + x), col]["bg"] = "Green" # If spot diagonal of the pawn is not empty highlights it to "eat" that piece if self.button_location[(row + x), (col + 1)]["fg"] == piece: self.button_location[(row + x), (col + 1)]["bg"] = "Green" if self.button_location[(row + x), (col - 1)]["fg"] == piece: self.button_location[(row + x), (col - 1)]["bg"] = "Green" # 4 For loops for each direction of Rook Movement def rook_movement(self, row, col, color): if color == "DimGray": piece = "OrangeRed" else: piece = "DimGray" for x in range(row + 1, 9): if self.button_location[x, col]["text"] == "": self.button_location[x, col]["bg"] = "Green" elif self.button_location[x, col]["fg"] == piece: self.button_location[x, col]["bg"] = "Green" break else: break for x in range(row - 1, 0, -1): if self.button_location[x, col]["text"] == "": self.button_location[x, col]["bg"] = "Green" elif self.button_location[x, col]["fg"] == piece: self.button_location[x, col]["bg"] = "Green" break else: break for x in range(col + 1, 9): if self.button_location[row, x]["text"] == "": self.button_location[row, x]["bg"] = "Green" elif self.button_location[row, x]["fg"] == piece: self.button_location[row, x]["bg"] = "Green" break else: break for x in range(col - 1, 0, -1): if self.button_location[row, x]["text"] == "": self.button_location[row, x]["bg"] = "Green" elif self.button_location[row, x]["fg"] == piece: self.button_location[row, x]["bg"] = "Green" break else: break def knight_movement(self, row, col, color): self.clear_board() if color == "DimGray": piece = "OrangeRed" else: piece = "DimGray" @self.movement_check def moving_up(): if self.button_location[(row - 2), (col - 1)]["fg"] == piece: self.button_location[(row - 2), (col - 1)]["bg"] = "Green" if self.button_location[(row - 2), (col - 1)]["text"] == "": self.button_location[(row - 2), (col - 1)]["bg"] = "Green" if self.button_location[(row - 1), (col - 2)]["fg"] == piece: self.button_location[(row - 1), (col - 2)]["bg"] = "Green" if self.button_location[(row - 1), (col - 2)]["text"] == "": self.button_location[(row - 1), (col - 2)]["bg"] = "Green" @self.movement_check def moving_right(): if self.button_location[(row - 2), (col + 1)]["fg"] == piece: self.button_location[(row - 2), (col + 1)]["bg"] = "Green" if self.button_location[(row - 2), (col + 1)]["text"] == "": self.button_location[(row - 2), (col + 1)]["bg"] = "Green" if self.button_location[(row - 1), (col + 2)]["fg"] == piece: self.button_location[(row - 1), (col + 2)]["bg"] = "Green" if self.button_location[(row - 1), (col + 2)]["text"] == "": self.button_location[(row - 1), (col + 2)]["bg"] = "Green" @self.movement_check def moving_down(): if self.button_location[(row + 1), (col + 2)]["fg"] == piece: self.button_location[(row + 1), (col + 2)]["bg"] = "Green" if self.button_location[(row + 1), (col + 2)]["text"] == "": self.button_location[(row + 1), (col + 2)]["bg"] = "Green" if self.button_location[(row + 2), (col + 1)]["fg"] == piece: self.button_location[(row + 2), (col + 1)]["bg"] = "Green" if self.button_location[(row + 2), (col + 1)]["text"] == "": self.button_location[(row + 2), (col + 1)]["bg"] = "Green" @self.movement_check def moving_left(): if self.button_location[(row + 2), (col - 1)]["fg"] == piece: self.button_location[(row + 2), (col - 1)]["bg"] = "Green" if self.button_location[(row + 2), (col - 1)]["text"] == "": self.button_location[(row + 2), (col - 1)]["bg"] = "Green" if self.button_location[(row + 1), (col - 2)]["fg"] == piece: self.button_location[(row + 1), (col - 2)]["bg"] = "Green" if self.button_location[(row + 1), (col - 2)]["text"] == "": self.button_location[(row + 1), (col - 2)]["bg"] = "Green" moving_up() moving_right() moving_left() moving_down() def bishop_movement(self, row, col, color): self.clear_board() if color == "DimGray": piece = "OrangeRed" else: piece = "DimGray" @self.movement_check def up_right(): x = row - 1 y = col + 1 while x > 0: if self.button_location[x, y]["text"] == "": self.button_location[x, y]["bg"] = "Green" elif self.button_location[x, y]["fg"] == piece: self.button_location[x, y]["bg"] = "Green" break else: break x -= 1 y += 1 @self.movement_check def up_left(): x = row - 1 y = col - 1 while x > 0: if self.button_location[x, y]["text"] == "": self.button_location[x, y]["bg"] = "Green" elif self.button_location[x, y]["fg"] == piece: self.button_location[x, y]["bg"] = "Green" break else: break x -= 1 y -= 1 @self.movement_check def down_left(): x = row + 1 y = col - 1 while x > 0: if self.button_location[x, y]["text"] == "": self.button_location[x, y]["bg"] = "Green" elif self.button_location[x, y]["fg"] == piece: self.button_location[x, y]["bg"] = "Green" break else: break x += 1 y -= 1 @self.movement_check def down_right(): x = row + 1 y = col + 1 while x > 0: if self.button_location[x, y]["text"] == "": self.button_location[x, y]["bg"] = "Green" elif self.button_location[x, y]["fg"] == piece: self.button_location[x, y]["bg"] = "Green" break else: break x += 1 y += 1 up_right() up_left() down_left() down_right() # Combines the movement of the rook and the bishop def queen_movement(self, row, col, color): self.clear_board() self.bishop_movement(row, col, color) self.rook_movement(row, col, color) def king_movement(self, row, col, color): self.clear_board() if color == "DimGray": piece = "OrangeRed" self.white_castle(col) else: piece = "DimGray" self.black_castle(col) for x in range(-1, 2): for y in range(-1, 2): if self.button_location[(row + x), (col + y)]["text"] == "": self.button_location[(row + x), (col + y)]["bg"] = "Green" elif self.button_location[(row + x), (col + y)]["fg"] == piece: self.button_location[(row + x), (col + y)]["bg"] = "Green" def white_castle(self, col): # Caslteing option # Checks if the king has moved moved = True castleing_left = False castleing_right = False for x in self.white_king_locations: if x == (8, 5): moved = False else: moved = True break # Checks if spots are open to the left or right if moved is False: for x in range(col+1, 8): if self.button_location[(8, x)]["text"] == "": castleing_right = True else: castleing_right = False break for x in range(col-1, 1, -1): if self.button_location[(8, x)]["text"] == "": castleing_left = True else: castleing_left = False break # if spots are open and the king hasn't moved checks to see if the Rook is there # castles if Rook is there. if castleing_right: if self.button_location[8, 8]["text"] == "ROOK.": self.button_location[8, 7]["bg"] = "Green" if castleing_left: if self.button_location[8, 1]["text"] == "ROOK": self.button_location[8, 3]["bg"] = "Green" def black_castle(self, col): # Caslteing option # Checks if the king has moved moved = True castleing_left = False castleing_right = False for x in self.black_king_locations: if x == (1, 5): moved = False else: moved = True break # Checks if spots are open to the left or right if moved is False: for x in range(col+1, 8): if self.button_location[(1, x)]["text"] == "": castleing_right = True else: castleing_right = False break for x in range(col-1, 1, -1): if self.button_location[(1, x)]["text"] == "": castleing_left = True else: castleing_left = False break # if spots are open and the king hasn't moved checks to see if the Rook is there # castles if Rook is there. if castleing_right: if self.button_location[1, 8]["text"] == "rook.": self.button_location[1, 7]["bg"] = "Green" if castleing_left: if self.button_location[1, 1]["text"] == "rook": self.button_location[1, 3]["bg"] = "Green" # Function to get called to castle def move_pieces_castleing(self, row, col): if self.piece == "KING": if self.original_row == 8 and self.original_col == 5: if row == 8 and col == 7: self.button_location[8, 6].config(text="ROOK.", image=self.white_pieces[0], width=144, height=95, fg="DimGray") self.button_location[8, 8].config(text="", image="", height=6, width=20) if row == 8 and col == 3: self.button_location[8, 4].config(text="ROOK", image=self.white_pieces[0], width=144, height=95, fg="DimGray") self.button_location[8, 1].config(text="", image="", height=6, width=20) if self.piece == "king": if self.original_row == 1 and self.original_col == 5: if row == 1 and col == 7: self.button_location[1, 6].config(text="rook.", image=self.black_pieces[0], width=144, height=95, fg="OrangeRed") self.button_location[1, 8].config(text="", image="", height=6, width=20) if row == 1 and col == 3: self.button_location[1, 4].config(text="rook", image=self.black_pieces[0], width=144, height=95, fg="OrangeRed") self.button_location[1, 1].config(text="", image="", height=6, width=20) def movement(self, row, col): if self.button_location[row, col]["bg"] == "Green": self.move_piece(row, col) else: self.decide_movement(row, col) # Takes in the text of the button clicked and goes through the dictionary to get to the correct movement of that # specific piece def decide_movement(self, row, col): movement = { "PAWN": self.pawn_movement, "ROOK": self.rook_movement, "ROOK.": self.rook_movement, "KNIGHT": self.knight_movement, "KNIGHT.": self.knight_movement, "BISHOP": self.bishop_movement, "BISHOP.": self.bishop_movement, "QUEEN": self.queen_movement, "KING": self.king_movement, "pawn": self.pawn_movement, "rook": self.rook_movement, "rook.": self.rook_movement, "knight": self.knight_movement, "knight.": self.knight_movement, "bishop": self.bishop_movement, "bishop.": self.bishop_movement, "queen": self.queen_movement, "king": self.king_movement} try: self.piece = self.button_location[row, col]["text"] self.piece_color = self.button_location[row, col]["fg"] self.original_row = row self.original_col = col self.piece_image = self.button_location[row, col]["image"] if self.turn % 2 == 0: if self.piece_color == "OrangeRed": movement.get(self.piece)(row, col, color=self.piece_color) else: self.clear_board() wrong_turn_window = Toplevel() wrong_turn_window.title("Wrong Turn") wrong_turn_window.lift() label = Label(wrong_turn_window, text="It's Not Your Turn!") label.pack() if self.turn % 2 != 0: if self.piece_color == "DimGray": movement.get(self.piece)(row, col, color=self.piece_color) else: self.clear_board() wrong_turn_window = Toplevel() wrong_turn_window.title("Wrong Turn") wrong_turn_window.lift() label = Label(wrong_turn_window, text="It's Not Your Turn!") label.pack() # for clicking where there is no piece except TypeError: no_piece_window = Toplevel() no_piece_window.title("Wrong Click") no_piece_window.lift() label = Label(no_piece_window, text="There is no piece there") label.pack() # Moves the piece to the new button that was right-clicked and clears the original button of the text and image # Then checks to see if either king is in Check def move_piece(self, row, col): if self.button_location[row, col]["bg"] == "Green": self.button_location[row, col]["text"] = self.piece self.button_location[row, col]["fg"] = self.piece_color self.button_location[row, col].config(image=self.piece_image, width=144, height=95) self.move_pieces_castleing(row, col) self.piece = "" self.piece_color = "" self.button_location[self.original_row, self.original_col]["text"] = "" self.button_location[self.original_row, self.original_col]["fg"] = "white" self.button_location[self.original_row, self.original_col].config(image="", width=20, height=6) self.clear_board() self.king_in_danger() self.clear_board() self.turn += 1 else: self.clear_board() # Checks to see if the king is in Check and a window pops up if the king is def king_in_danger(self): movement = { "PAWN": self.pawn_movement, "ROOK": self.rook_movement, "ROOK.": self.rook_movement, "KNIGHT": self.knight_movement, "KNIGHT.": self.knight_movement, "BISHOP": self.bishop_movement, "BISHOP.": self.bishop_movement, "QUEEN": self.queen_movement, "KING": self.king_movement, "pawn": self.pawn_movement, "rook": self.rook_movement, "rook.": self.rook_movement, "knight": self.knight_movement, "knight.": self.knight_movement, "bishop": self.bishop_movement, "bishop.": self.bishop_movement, "queen": self.queen_movement, "king": self.king_movement, "": self.pass_this} king_row = 1 king_col = 1 king_row1 = 1 king_col1 = 1 # Finds the king for each side for row2 in range(1, 9): for col2 in range(1, 9): piece_text = self.button_location[row2, col2]["text"] piece_row1 = row2 piece_col1 = col2 if piece_text == "KING": king_row = piece_row1 king_col = piece_col1 if piece_text == "king": king_row1 = piece_row1 king_col1 = piece_col1 self.white_king_locations.append((king_row, king_col)) self.black_king_locations.append((king_row1, king_col1)) # Runs each piece's movement in their specific location to see if they put the king in Check done = False for row1 in range(1, 9): if done: break for column1 in range(1, 9): piece_text = self.button_location[row1, column1]["text"] piece_color = self.button_location[row1, column1]["fg"] piece_row = row1 piece_col = column1 movement.get(piece_text)(row=piece_row, col=piece_col, color=piece_color) if self.button_location[king_row, king_col]["bg"] == "Green": check_window = Toplevel() check_window.title("CHECK!") label = Label(check_window, text="CHECK!", height=20, width=50, fg="Blue") label.pack() done = True break if self.button_location[king_row1, king_col1]["bg"] == "Green": check_window = Toplevel() check_window.title("CHECK!") label = Label(check_window, text="CHECK!", height=20, width=50, fg="Red") label.pack() done = True break # GUI to pop up when a pawn reaches the other side def new_piece_gui(self, row, col, color): if color == "DimGray": queen = self.white_pieces[3] rook = self.white_pieces[0] bishop = self.white_pieces[2] knight = self.white_pieces[1] else: queen = self.black_pieces[3] rook = self.black_pieces[0] bishop = self.black_pieces[2] knight = self.black_pieces[1] self.piece_window = Toplevel() self.piece_window.title("Pick Your Piece") queen_label = Label(self.piece_window, text="Queen") rook_label = Label(self.piece_window, text="Rook") bishop_label = Label(self.piece_window, text="Bishop") knight_label = Label(self.piece_window, text="Knight") queen_label.grid(row=0, column=0, pady=10, padx=20) rook_label.grid(row=1, column=0, pady=10, padx=20) bishop_label.grid(row=2, column=0, pady=10, padx=20) knight_label.grid(row=3, column=0, pady=10, padx=20) queen_button = Button(self.piece_window, image=queen, width=144, height=90, bg="white") rook_button = Button(self.piece_window, image=rook, width=144, height=90, bg="black") bishop_button = Button(self.piece_window, image=bishop, width=144, height=90, bg="white") knight_button = Button(self.piece_window, image=knight, width=144, height=90, bg="black") queen_button.config(command=lambda e=row, i=row, j=col, k=color: self.place_queen(i, j, k)) rook_button.config(command=lambda e=row, i=row, j=col, k=color: self.place_rook(i, j, k)) bishop_button.config(command=lambda e=row, i=row, j=col, k=color: self.place_bishop(i, j, k)) knight_button.config(command=lambda e=row, i=row, j=col, k=color: self.place_knight(i, j, k)) queen_button.grid(row=0, column=1) rook_button.grid(row=1, column=1) bishop_button.grid(row=2, column=1) knight_button.grid(row=3, column=1) # Replace Pawn with Queen def place_queen(self, row, col, color): if color == "DimGray": image = self.white_pieces[3] text = "QUEEN" else: image = self.black_pieces[3] text = "queen" self.button_location[row, col].config(text=text, image=image, width=144, height=95) self.piece_window.destroy() self.king_in_danger() self.clear_board() # Replace Pawn wtih Rook def place_rook(self, row, col, color): if color == "DimGray": image = self.white_pieces[0] text = "ROOK" else: image = self.black_pieces[0] text = "rook" self.button_location[row, col].config(text=text, image=image, width=144, height=95) self.piece_window.destroy() self.king_in_danger() self.clear_board() # Replace Pawn with Bishop def place_bishop(self, row, col, color): if color == "DimGray": image = self.white_pieces[2] text = "BISHOP" else: image = self.black_pieces[2] text = "bishop" self.button_location[row, col].config(text=text, image=image, width=144, height=95) self.piece_window.destroy() self.king_in_danger() self.clear_board() # Replace Pawn with Knight def place_knight(self, row, col, color): if color == "DimGray": image = self.white_pieces[1] text = "KNIGHT" else: image = self.black_pieces[1] text = "knight" self.button_location[row, col].config(text=text, image=image, width=144, height=95) self.piece_window.destroy() self.king_in_danger() self.clear_board() # Resets everything def new_game(self): for x in range(1, 9): for y in range(1, 9): self.button_location[x, y].config(text="", image="", width=20, height=6) self.place_pieces() self.turn = 1 def exit(self, _=None): self.quit() self.destroy() def pass_this(self, row, col, color): pass
def destroy(self): Toplevel.destroy(self)
class Dialog: def __init__(self, master, title, class_=None, relx=0.5, rely=0.3): self.master = master self.title = title self.class_ = class_ self.relx = relx self.rely = rely def setup(self): if self.class_: self.root = Toplevel(self.master, class_=self.class_) else: self.root = Toplevel(self.master) self.root.title(self.title) self.root.iconname(self.title) def change_title(self,title): self.title = title self.root.title(self.title) self.root.iconname(self.title) def enable(self): ### enable self.root.protocol('WM_DELETE_WINDOW', self.wm_delete_window) self._set_transient(self.relx, self.rely) self.root.wait_visibility() self.root.grab_set() self.root.mainloop() self.root.destroy() def _set_transient(self, relx=0.5, rely=0.3): widget = self.root widget.withdraw() # Remain invisible while we figure out the geometry widget.transient(self.master) widget.update_idletasks() # Actualize geometry information if self.master.winfo_ismapped(): m_width = self.master.winfo_width() m_height = self.master.winfo_height() m_x = self.master.winfo_rootx() m_y = self.master.winfo_rooty() else: m_width = self.master.winfo_screenwidth() m_height = self.master.winfo_screenheight() m_x = m_y = 0 w_width = widget.winfo_reqwidth() w_height = widget.winfo_reqheight() x = m_x + (m_width - w_width) * relx y = m_y + (m_height - w_height) * rely if x+w_width > self.master.winfo_screenwidth(): x = self.master.winfo_screenwidth() - w_width elif x < 0: x = 0 if y+w_height > self.master.winfo_screenheight(): y = self.master.winfo_screenheight() - w_height elif y < 0: y = 0 widget.geometry("+%d+%d" % (x, y)) widget.deiconify() # Become visible at the desired location def wm_delete_window(self): self.root.quit()
class CFGEditor(object): """ A dialog window for creating and editing context free grammars. ``CFGEditor`` imposes the following restrictions: - All nonterminals must be strings consisting of word characters. - All terminals must be strings consisting of word characters and space characters. """ # Regular expressions used by _analyze_line. Precompile them, so # we can process the text faster. ARROW = SymbolWidget.SYMBOLS['rightarrow'] _LHS_RE = re.compile(r"(^\s*\w+\s*)(->|(" + ARROW + "))") _ARROW_RE = re.compile("\s*(->|(" + ARROW + "))\s*") _PRODUCTION_RE = re.compile(r"(^\s*\w+\s*)" + # LHS "(->|(" + ARROW + "))\s*" + # arrow r"((\w+|'[\w ]*'|\"[\w ]*\"|\|)\s*)*$") # RHS _TOKEN_RE = re.compile("\\w+|->|'[\\w ]+'|\"[\\w ]+\"|(" + ARROW + ")") _BOLD = ('helvetica', -12, 'bold') def __init__(self, parent, cfg=None, set_cfg_callback=None): self._parent = parent if cfg is not None: self._cfg = cfg else: self._cfg = ContextFreeGrammar(Nonterminal('S'), []) self._set_cfg_callback = set_cfg_callback self._highlight_matching_nonterminals = 1 # Create the top-level window. self._top = Toplevel(parent) self._init_bindings() self._init_startframe() self._startframe.pack(side='top', fill='x', expand=0) self._init_prodframe() self._prodframe.pack(side='top', fill='both', expand=1) self._init_buttons() self._buttonframe.pack(side='bottom', fill='x', expand=0) self._textwidget.focus() def _init_startframe(self): frame = self._startframe = Frame(self._top) self._start = Entry(frame) self._start.pack(side='right') Label(frame, text='Start Symbol:').pack(side='right') Label(frame, text='Productions:').pack(side='left') self._start.insert(0, self._cfg.start().symbol()) def _init_buttons(self): frame = self._buttonframe = Frame(self._top) Button(frame, text='Ok', command=self._ok, underline=0, takefocus=0).pack(side='left') Button(frame, text='Apply', command=self._apply, underline=0, takefocus=0).pack(side='left') Button( frame, text='Reset', command=self._reset, underline=0, takefocus=0, ).pack(side='left') Button(frame, text='Cancel', command=self._cancel, underline=0, takefocus=0).pack(side='left') Button(frame, text='Help', command=self._help, underline=0, takefocus=0).pack(side='right') def _init_bindings(self): self._top.title('CFG Editor') self._top.bind('<Control-q>', self._cancel) self._top.bind('<Alt-q>', self._cancel) self._top.bind('<Control-d>', self._cancel) #self._top.bind('<Control-x>', self._cancel) self._top.bind('<Alt-x>', self._cancel) self._top.bind('<Escape>', self._cancel) #self._top.bind('<Control-c>', self._cancel) self._top.bind('<Alt-c>', self._cancel) self._top.bind('<Control-o>', self._ok) self._top.bind('<Alt-o>', self._ok) self._top.bind('<Control-a>', self._apply) self._top.bind('<Alt-a>', self._apply) self._top.bind('<Control-r>', self._reset) self._top.bind('<Alt-r>', self._reset) self._top.bind('<Control-h>', self._help) self._top.bind('<Alt-h>', self._help) self._top.bind('<F1>', self._help) def _init_prodframe(self): self._prodframe = Frame(self._top) # Create the basic Text widget & scrollbar. self._textwidget = Text(self._prodframe, background='#e0e0e0', exportselection=1) self._textscroll = Scrollbar(self._prodframe, takefocus=0, orient='vertical') self._textwidget.config(yscrollcommand=self._textscroll.set) self._textscroll.config(command=self._textwidget.yview) self._textscroll.pack(side='right', fill='y') self._textwidget.pack(expand=1, fill='both', side='left') # Initialize the colorization tags. Each nonterminal gets its # own tag, so they aren't listed here. self._textwidget.tag_config('terminal', foreground='#006000') self._textwidget.tag_config('arrow', font='symbol') self._textwidget.tag_config('error', background='red') # Keep track of what line they're on. We use that to remember # to re-analyze a line whenever they leave it. self._linenum = 0 # Expand "->" to an arrow. self._top.bind('>', self._replace_arrows) # Re-colorize lines when appropriate. self._top.bind('<<Paste>>', self._analyze) self._top.bind('<KeyPress>', self._check_analyze) self._top.bind('<ButtonPress>', self._check_analyze) # Tab cycles focus. (why doesn't this work??) def cycle(e, textwidget=self._textwidget): textwidget.tk_focusNext().focus() self._textwidget.bind('<Tab>', cycle) prod_tuples = [(p.lhs(), [p.rhs()]) for p in self._cfg.productions()] for i in range(len(prod_tuples) - 1, 0, -1): if (prod_tuples[i][0] == prod_tuples[i - 1][0]): if () in prod_tuples[i][1]: continue if () in prod_tuples[i - 1][1]: continue print prod_tuples[i - 1][1] print prod_tuples[i][1] prod_tuples[i - 1][1].extend(prod_tuples[i][1]) del prod_tuples[i] for lhs, rhss in prod_tuples: print lhs, rhss s = '%s ->' % lhs for rhs in rhss: for elt in rhs: if isinstance(elt, Nonterminal): s += ' %s' % elt else: s += ' %r' % elt s += ' |' s = s[:-2] + '\n' self._textwidget.insert('end', s) self._analyze() # # Add the producitons to the text widget, and colorize them. # prod_by_lhs = {} # for prod in self._cfg.productions(): # if len(prod.rhs()) > 0: # prod_by_lhs.setdefault(prod.lhs(),[]).append(prod) # for (lhs, prods) in prod_by_lhs.items(): # self._textwidget.insert('end', '%s ->' % lhs) # self._textwidget.insert('end', self._rhs(prods[0])) # for prod in prods[1:]: # print '\t|'+self._rhs(prod), # self._textwidget.insert('end', '\t|'+self._rhs(prod)) # print # self._textwidget.insert('end', '\n') # for prod in self._cfg.productions(): # if len(prod.rhs()) == 0: # self._textwidget.insert('end', '%s' % prod) # self._analyze() # def _rhs(self, prod): # s = '' # for elt in prod.rhs(): # if isinstance(elt, Nonterminal): s += ' %s' % elt.symbol() # else: s += ' %r' % elt # return s def _clear_tags(self, linenum): """ Remove all tags (except ``arrow`` and ``sel``) from the given line of the text widget used for editing the productions. """ start = '%d.0' % linenum end = '%d.end' % linenum for tag in self._textwidget.tag_names(): if tag not in ('arrow', 'sel'): self._textwidget.tag_remove(tag, start, end) def _check_analyze(self, *e): """ Check if we've moved to a new line. If we have, then remove all colorization from the line we moved to, and re-colorize the line that we moved from. """ linenum = int(self._textwidget.index('insert').split('.')[0]) if linenum != self._linenum: self._clear_tags(linenum) self._analyze_line(self._linenum) self._linenum = linenum def _replace_arrows(self, *e): """ Replace any ``'->'`` text strings with arrows (char \\256, in symbol font). This searches the whole buffer, but is fast enough to be done anytime they press '>'. """ arrow = '1.0' while 1: arrow = self._textwidget.search('->', arrow, 'end+1char') if arrow == '': break self._textwidget.delete(arrow, arrow + '+2char') self._textwidget.insert(arrow, self.ARROW, 'arrow') self._textwidget.insert(arrow, '\t') arrow = '1.0' while 1: arrow = self._textwidget.search(self.ARROW, arrow + '+1char', 'end+1char') if arrow == '': break self._textwidget.tag_add('arrow', arrow, arrow + '+1char') def _analyze_token(self, match, linenum): """ Given a line number and a regexp match for a token on that line, colorize the token. Note that the regexp match gives us the token's text, start index (on the line), and end index (on the line). """ # What type of token is it? if match.group()[0] in "'\"": tag = 'terminal' elif match.group() in ('->', self.ARROW): tag = 'arrow' else: # If it's a nonterminal, then set up new bindings, so we # can highlight all instances of that nonterminal when we # put the mouse over it. tag = 'nonterminal_' + match.group() if tag not in self._textwidget.tag_names(): self._init_nonterminal_tag(tag) start = '%d.%d' % (linenum, match.start()) end = '%d.%d' % (linenum, match.end()) self._textwidget.tag_add(tag, start, end) def _init_nonterminal_tag(self, tag, foreground='blue'): self._textwidget.tag_config(tag, foreground=foreground, font=CFGEditor._BOLD) if not self._highlight_matching_nonterminals: return def enter(e, textwidget=self._textwidget, tag=tag): textwidget.tag_config(tag, background='#80ff80') def leave(e, textwidget=self._textwidget, tag=tag): textwidget.tag_config(tag, background='') self._textwidget.tag_bind(tag, '<Enter>', enter) self._textwidget.tag_bind(tag, '<Leave>', leave) def _analyze_line(self, linenum): """ Colorize a given line. """ # Get rid of any tags that were previously on the line. self._clear_tags(linenum) # Get the line line's text string. line = self._textwidget.get( ` linenum ` + '.0', ` linenum ` + '.end') # If it's a valid production, then colorize each token. if CFGEditor._PRODUCTION_RE.match(line): # It's valid; Use _TOKEN_RE to tokenize the production, # and call analyze_token on each token. def analyze_token(match, self=self, linenum=linenum): self._analyze_token(match, linenum) return '' CFGEditor._TOKEN_RE.sub(analyze_token, line) elif line.strip() != '': # It's invalid; show the user where the error is. self._mark_error(linenum, line) def _mark_error(self, linenum, line): """ Mark the location of an error in a line. """ arrowmatch = CFGEditor._ARROW_RE.search(line) if not arrowmatch: # If there's no arrow at all, highlight the whole line. start = '%d.0' % linenum end = '%d.end' % linenum elif not CFGEditor._LHS_RE.match(line): # Otherwise, if the LHS is bad, highlight it. start = '%d.0' % linenum end = '%d.%d' % (linenum, arrowmatch.start()) else: # Otherwise, highlight the RHS. start = '%d.%d' % (linenum, arrowmatch.end()) end = '%d.end' % linenum # If we're highlighting 0 chars, highlight the whole line. if self._textwidget.compare(start, '==', end): start = '%d.0' % linenum end = '%d.end' % linenum self._textwidget.tag_add('error', start, end) def _analyze(self, *e): """ Replace ``->`` with arrows, and colorize the entire buffer. """ self._replace_arrows() numlines = int(self._textwidget.index('end').split('.')[0]) for linenum in range(1, numlines + 1): # line numbers start at 1. self._analyze_line(linenum) def _parse_productions(self): """ Parse the current contents of the textwidget buffer, to create a list of productions. """ productions = [] # Get the text, normalize it, and split it into lines. text = self._textwidget.get('1.0', 'end') text = re.sub(self.ARROW, '->', text) text = re.sub('\t', ' ', text) lines = text.split('\n') # Convert each line to a CFG production for line in lines: line = line.strip() if line == '': continue productions += parse_cfg_production(line) #if line.strip() == '': continue #if not CFGEditor._PRODUCTION_RE.match(line): # raise ValueError('Bad production string %r' % line) # #(lhs_str, rhs_str) = line.split('->') #lhs = Nonterminal(lhs_str.strip()) #rhs = [] #def parse_token(match, rhs=rhs): # token = match.group() # if token[0] in "'\"": rhs.append(token[1:-1]) # else: rhs.append(Nonterminal(token)) # return '' #CFGEditor._TOKEN_RE.sub(parse_token, rhs_str) # #productions.append(Production(lhs, *rhs)) return productions def _destroy(self, *e): if self._top is None: return self._top.destroy() self._top = None def _ok(self, *e): self._apply() self._destroy() def _apply(self, *e): productions = self._parse_productions() start = Nonterminal(self._start.get()) cfg = ContextFreeGrammar(start, productions) if self._set_cfg_callback is not None: self._set_cfg_callback(cfg) def _reset(self, *e): self._textwidget.delete('1.0', 'end') for production in self._cfg.productions(): self._textwidget.insert('end', '%s\n' % production) self._analyze() if self._set_cfg_callback is not None: self._set_cfg_callback(self._cfg) def _cancel(self, *e): try: self._reset() except: pass self._destroy() def _help(self, *e): # The default font's not very legible; try using 'fixed' instead. try: ShowText(self._parent, 'Help: Chart Parser Demo', (_CFGEditor_HELP).strip(), width=75, font='fixed') except: ShowText(self._parent, 'Help: Chart Parser Demo', (_CFGEditor_HELP).strip(), width=75)
class KeyboardEntry: """Mixin class that can be used to add the ability to type values for widget. When the cursor enters the widget the focus is set to the widget and the widget that had the focus previousy is saved in .lastFocus. When the cursor leaves the widget focus is restored to self.lastFocus. key_cb(event) is called upon KeyRelease events. If this is the first keytroke an undecorated window is created next to the cursor and handleKeyStroke(event) is called. This method should be subclassed to modify the way the string is typed in (see thumbwheel.py for an example of handling numbers only). When the Return key is pressed, the entry window is destroyed and if the typed striong is not empty self.callSet(self.typedValue) is called. If the cursor moves out of the widget before Rrturn is pressed the value in the entry window is discarded and the entry window is destroyed. """ def __init__(self, widgets, callSet): # callSet is a function taking one argument (string) which will be # when the Returnm key is hit (if the typed string is not empty) # widgets is a list of Tkinter wigets for which <Enter>, <Leave> # <Return> and <KeyRelease> are handled. These widgets has to exist # before thsi constructor can be called assert callable(callSet) self.callSet = callSet for w in widgets: w.bind("<Enter>", self.enter_cb) w.bind("<Leave>", self.leave_cb) w.bind("<Return>", self.return_cb) w.bind("<KeyRelease>", self.key_cb) self.typedValue = '' # string accumulating valuescharacters typed self.lastFocus = None # widget to which the focus will be restored # when the mouse leaves the widget self.topEntry = None # top level for typing values self.typedValueTK = None #Tk label used as entry for value def key_cb(self, event=None): # call back function for keyboard events (except for Return) # handle numbers to set value key = event.keysym if key=='Return': return #print 'Key:', key if len(self.typedValue)==0 and self.topEntry is None: # create Tk label showing typed value x = event.x y = event.y #print 'create entry' self.topEntry = Toplevel() self.topEntry.overrideredirect(1) w = event.widget if event.x >= 0: self.topEntry.geometry('+%d+%d'%(w.winfo_rootx() + event.x+10, w.winfo_rooty() + event.y)) else: self.topEntry.geometry('+%d+%d'%(w.winfo_rootx() +10, w.winfo_rooty() )) self.typedValueTK = Label( master=self.topEntry, text='', relief='sunken', bg='yellow') self.typedValueTK.pack() self.handleKeyStroke(event) def leave_cb(self, event=None): # make sure widget gets keyboard events # print 'leave', event.widget if self.topEntry: self.typedValueTK.destroy() self.topEntry.destroy() self.topEntry = None self.typedValue = '' if self.lastFocus: #print 'restoring focus' if widgetsOnBackWindowsCanGrabFocus is False: lActiveWindow = self.lastFocus.focus_get() if lActiveWindow is not None \ and ( lActiveWindow.winfo_toplevel() != self.lastFocus.winfo_toplevel() ): return self.lastFocus.focus_set() self.lastFocus = None event.widget.config(cursor='') def enter_cb(self, event=None): # make sure widget gets keyboard events #print 'enter', event.widget if widgetsOnBackWindowsCanGrabFocus is False: lActiveWindow = event.widget.focus_get() if lActiveWindow is not None \ and ( lActiveWindow.winfo_toplevel() != event.widget.winfo_toplevel() ): return if self.lastFocus is None: #print 'setting focus' self.lastFocus = self.focus_lastfor() event.widget.focus_set() event.widget.config(cursor='xterm') def return_cb(self, event): # return should destroy the topEntry #print "return_cb" if self.typedValueTK is not None: self.typedValueTK.destroy() if self.topEntry is not None: self.topEntry.destroy() self.topEntry = None if len(self.typedValue): #print 'setting to', self.type(self.typedValue) self.callSet(self.typedValue) self.typedValue = '' ## TO BE SUBCLASSED def handleKeyStroke(self, event): # by default we handle delete character keys key = event.keysym if key=='BackSpace' or key=='Delete': self.typedValue = self.typedValue[:-1] self.typedValueTK.configure(text=self.typedValue)
class PromptPopUp_old(): '''the future description: "Neat & tidy prompt pop up to request input" there is a lot of work to do here : make it class clean functions to make it generic add extra parameters such as: buttons title dimensions* >but is a functional starting point< ''' def __init__(self, **kwargs): ''' (under development)''' master = None briefing = '' entries_txt = [] entries_val = [] title = 'PromptPopUp' if 'master' in kwargs.keys(): master = kwargs['master'] if 'briefing' in kwargs.keys(): briefing = kwargs['briefing'] if 'entries_txt' in kwargs.keys(): entries_txt = kwargs['entries_txt'] if 'entries_val' in kwargs.keys(): entries_val = kwargs['entries_val'] if 'title' in kwargs.keys(): title = kwargs['title'] self.master = master self._briefing_ = briefing self._entries_ = entries_txt self._defvals_ = entries_val self._title_ = title self.ent_c = [] self.set_self_vertex() self.create_content() def set_self_vertex(self): from main_gui import MAINVERTEX ws, hs, w_main, h_main, x_main, y_main = MAINVERTEX # calculate the greatness self.entr_maxlen = int(len(max(self._entries_, key=len)) * 2.25 / 3.0) w_pop = w_main - 40 h_pop = h_main * 12 / 21 x_pop = x_main + w_main - 30 y_pop = y_main + h_main - h_pop #print w_pop, h_pop, x_pop, y_pop self._vertex_ = [w_pop, h_pop, x_pop, y_pop] def create_content(self): self.pop = Toplevel(self.master) self.pop.grab_set() # when you show the popup self.pop.wm_title(' ' * 20 + self._title_) self.pop.geometry('{:d}x{:d}+{:d}+{:d}'.format(*self._vertex_)) label0 = Label(self.pop, text=self._briefing_) label0.pack(side="top", fill="both", expand=True, padx=100, pady=20) # just a line bottom_hline_deco(self.pop) # lets create space to do some stuff ... row2fill = Frame(self.pop) for e in range(len(self._entries_)): self.ent_c.append( create_entry(row2fill, self._entries_[e], self._defvals_[e], self.entr_maxlen)) row2fill.pack(side="top", padx=1, pady=5) self.bottom_button_row() self.master.solv_b.config(bg='gray40', width=45) #cyan') #self.master.solv_b.flash() #self.pop.mainloop() def bottom_button_row(self): _br_ = Frame(self.pop) b1 = Button(_br_, text='Save', command=(lambda: self.save_it())) b1.pack(side="right", padx=10, pady=20) b2 = Button(_br_, text='Quit', command=(lambda: self.exit_pop())) b2.pack(side="right", padx=10, pady=4) _br_.pack(side="bottom", expand=True) def save_it(self): self.master._solvatedinfo_ = get_entriesvalue(self.ent_c) self.exit_pop() def exit_pop(self): self.pop.grab_release() # to return to normal self.master.solv_b.config(bg='lightgrey', width=29) self.pop.destroy()
def destroy(self): if self.document: self.document.remove_window(self) Toplevel.destroy(self)
def destroy(self): # close win silently Toplevel.destroy(self) # redef for close ops
class MapUI: def __init__(self, master): def center(win): win.update_idletasks() width = win.winfo_width() height = win.winfo_height() x = (win.winfo_screenwidth() // 4) - (width // 2) + 40 y = (win.winfo_screenheight() // 4) - (height // 2) + 40 win.geometry('{}x{}+{}+{}'.format(width, height, x, y)) def callback(event): event.widget.focus_set() print "clicked at", event.x, event.y if self.add_tasks_flg.get() == 1: # Select number of robots # Define elements of pop up window self.top = Toplevel() self.num_robots = StringVar(self.top) self.num_robots.set("1") # default value w = OptionMenu(self.top, self.num_robots, '1', '2', '3', '4').grid(row=0, column=1) text1 = Message(self.top, text="Number of robots:", width=150).grid(row=0, column=0) self.e = Entry(self.top, width=10) self.e.grid(row=1, column=1) text2 = Message(self.top, text="Task duration:", width=150).grid(row=1, column=0) text3 = Message(self.top, text="(s)", width=60).grid(row=1, column=2) newline = Message(self.top, text=" ").grid(row=2) button = Button(self.top, text='Enter', command=lambda: self.enter_task(event)).grid( row=3, column=1) button_cancel = Button(self.top, text='Cancel', command=self.cancel_task).grid(row=3, column=2) center(self.top) master.title("Map Interface") master.minsize(width=1000, height=750) master.maxsize(width=1000, height=750) master.config(bg=BKG_COLOUR) self.master = master # Canvas for overlaying map self.map_canvas = Canvas(master, width=CANVAS_W, height=CANVAS_H, bg='gray85', highlightthickness=0) self.map_canvas.pack(side='right', padx=50) self.map_canvas.bind("<Button-1>", callback) global CANVAS_PTR CANVAS_PTR = self.map_canvas self.master.update() w = self.map_canvas.winfo_width() h = self.map_canvas.winfo_height() # Overlay a grid for i in range(0, w, SQ_SIZE): if i != 0: self.map_canvas.create_line(i, 0, i, h, dash=1) for i in range(0, h, SQ_SIZE): if i != 0: self.map_canvas.create_line(0, i, w, i, dash=1) # Load in flame icon from flame.gif self.flame_icon = PhotoImage(file="flame.gif") # Load in the drone icon from drone.gif global DRONE_ICON DRONE_ICON = PhotoImage(file="drone.gif") buttons_frame = Canvas(master, width=163, height=230, bg=BUTTONS_BKG_COLOUR, highlightthickness=1, highlightbackground='dim grey') buttons_frame.place(x=40, y=200) # Define UI buttons self.add_tasks_flg = IntVar() self.add_tasks_b = Checkbutton(master, text="Add Tasks", variable=self.add_tasks_flg, highlightbackground=BUTTONS_BKG_COLOUR, background=BUTTONS_BKG_COLOUR) self.add_tasks_b.place(x=77, y=240) self.clear_wp_b = Button(master, text='Clear Tasks', command=self.clear_wp, highlightbackground=BUTTONS_BKG_COLOUR) self.clear_wp_b.config(width=10) self.clear_wp_b.place(x=65, y=270) ''' self.gen_wp_file_b = Button(master, text='Generate Waypoints File', command=self.gen_wp_file, highlightbackground=BKG_COLOUR) self.gen_wp_file_b.config(width=20) self.gen_wp_file_b.place(x=20, y=250) ''' self.land_b = Button(master, text='Land', command=self.land, highlightbackground=BUTTONS_BKG_COLOUR) self.land_b.config(width=10) self.land_b.place(x=65, y=350) # Set up coordinate system conversion and display corners of room: file_obj = open('antenna_locations.txt', 'r') anchors = [] for line in file_obj: cur_anchors = map(float, line.split()) anchors.append(cur_anchors) file_obj.close() anchors = (np.array(anchors)).T # Find largest (abs) x and y values to use a reference for conversion ratio x_vals = anchors[0] largest_x_val = x_vals[np.argmax(abs(x_vals))] y_vals = anchors[1] largest_y_val = y_vals[np.argmax(abs(y_vals))] if largest_x_val > largest_y_val: largest_y_val = largest_x_val else: largest_x_val = largest_y_val global m_per_pixel_x m_per_pixel_x = float(largest_x_val / (CANVAS_W / 2)) global m_per_pixel_y m_per_pixel_y = float(largest_y_val / (CANVAS_H / 2)) # Place antenna (anchors) on UI anchors = anchors.T for cur_anchor in anchors: x_pixel_loc = cur_anchor[0] / m_per_pixel_x + CANVAS_W / 2 y_pixel_loc = -1 * (cur_anchor[1] / m_per_pixel_y) + CANVAS_H / 2 # Draw antenna @ location global ANTENNA_LIST antenna_id = self.map_canvas.create_oval(x_pixel_loc - 15, y_pixel_loc - 15, x_pixel_loc + 15, y_pixel_loc + 15, fill='red') self.master.update() global SQ_SIZE SQ_SIZE = 20 global BKG_COLOUR BKG_COLOUR = 'gray95' global BUTTONS_BKG_COLOUR BUTTONS_BKG_COLOUR = 'grey66' global CANVAS_W CANVAS_W = 700 global CANVAS_H CANVAS_H = 700 global TASK_LIST TASK_LIST = None global m_per_pixel_x m_per_pixel_x = None global m_per_pixel_y m_per_pixel_y = None global NEW_TASK_FLAG NEW_TASK_FLAG = False global ANTENNA_LIST ANTENNA_LIST = None global DRONE_ICON DRONE_ICON = None flame_icon = None ui_wp_list = None #task_list = None add_wp_flag = False task_id = 0 add_tasks_flg = None def add_tasks(self): print "adding tasks" # function imp here self.add_wp_flag = True self.map_canvas.config(cursor='pencil') def clear_wp(self): print "clear tasks" global TASK_LIST TASK_LIST = None for element_id in self.ui_wp_list: self.map_canvas.delete(element_id[0]) self.ui_wp_list = None ''' def gen_wp_file(self): print "generate wp file" # function imp here ''' def land(self): # Send a new task with position (0,0,0) z=0 tells drone to land print("land") def enter_task(self, event): # Determine square (top left corner coords): w_start = event.x - event.x % SQ_SIZE h_start = event.y - event.y % SQ_SIZE #Translate pixel location to physical location x_pixel = event.x y_pixel = event.y # Find out how many pixels from center: x_pixel = x_pixel - CANVAS_W / 2 x_physical = x_pixel * m_per_pixel_x #vertical case, note this is flipped y_pixel = y_pixel - CANVAS_W / 2 y_pixel = -1 * y_pixel y_physical = y_pixel * m_per_pixel_y try: # Add to task list global TASK_LIST if TASK_LIST == None: TASK_LIST = [[ self.task_id, int(self.num_robots.get()), float(self.e.get()), x_physical, y_physical ]] global NEW_TASK_FLAG NEW_TASK_FLAG = True else: TASK_LIST.append([ self.task_id, int(self.num_robots.get()), float(self.e.get()), x_physical, y_physical ]) global NEW_TASK_FLAG NEW_TASK_FLAG = True # Indicate task in UI element_id = self.map_canvas.create_image(event.x, event.y, image=self.flame_icon) if self.ui_wp_list == None: self.ui_wp_list = [[element_id]] else: self.ui_wp_list.append([element_id]) except: print("Invalid Task Entry") self.map_canvas.config(cursor='arrow') self.add_wp_flag = False print(TASK_LIST) self.task_id = self.task_id + 1 self.top.destroy() def cancel_task(self): self.top.destroy()
class tkFileSelector() : def __init__(self,master,start_dir=expanduser("~"),filetypes=[],title="Select a music file.",color_1="#000000",color_2="#00c0c0",highlight_color_items="#c9c9c9") : ''' master == root_window == Tk() use color_1 and color_2 and bg_items and fg_items and highlight_color_items for colors personalisation. filetypes must "Strictly" be a list of extension beginning with an asterix followed by a point and the extension (in lowercase) or an empty list for no filtering. filetypes=["*.mp3","*.wav"] per example. Or insert an, item '*' for all filetype in combination with defined filetypes. for borderwidth and relief settings look at the code ''' # Constrcut GUI for the file selection toplevel. self.toplevel=Toplevel(master,bg=color_1,borderwidth=1,relief="sunken") self.toplevel.resizable(width=False, height=False) self.toplevel.title(title) self.dir_selection_frame=Frame(self.toplevel,bg=color_1,borderwidth=8/2,relief="groove") # Frame container for directory fields. self.dir_name_entry=Entry(self.toplevel,justify="center",width=50,bg=color_2,fg=color_1) # This will contains the current directory relative dirname self.dir_name_separator=Button(self.toplevel,width=1,relief="sunken",bg=color_1,fg=color_2) # An separator self.dir_back_button=Button(self.toplevel,width=6,relief="raised",bg=color_2,fg=color_1,text="Back",command=self.folder_go_back) # Change directory back button. self.canvas_frame=Frame(self.toplevel,borderwidth=8,relief="groove") # Frame for the file selection window canvas and his scrollbar. self.canvas=Canvas(self.canvas_frame,height=20*9,width=18*28,bg=color_2) # File selection window. self.canvas_scrollbar=Scrollbar(self.canvas_frame,orient=HORIZONTAL, bg=color_2,troughcolor=color_1,command=self.canvas.xview) # File selection window scrollbar. self.canvas.configure(xscrollcommand=self.canvas_scrollbar.set) self.file_selection_frame=Frame(self.toplevel,bg=color_1,borderwidth=8/2,relief="groove") # Frame container for filename fields. self.file_name_entry=Entry(self.toplevel,justify="center",width=50,bg=color_2,fg=color_1) # This will contains the basename (relative) of the selected file. self.file_name_separator=Button(self.toplevel,width=1,relief="sunken",bg=color_1,fg=color_2) # An separator. self.file_filter_menubutton = Menubutton(self.file_selection_frame, text='',relief="groove",width=8,bg=color_2,fg=color_1) # Menubutton for filetype filter. self.file_filter_extension="" if filetypes : self.file_filter_menu= Menu(self.file_filter_menubutton,borderwidth=3,relief="groove") # We use a menu for the filetypes filtering. i=0 self.file_filter_var=StringVar(master=None, value=filetypes[i], name=None) # Control varaible for current filetype and initialize with the first filetype item. self.file_filter_menubutton.config(text=filetypes[i]) self.file_filter_extension=filetypes[i][1::] while i < len(filetypes) : # Creating radiobutton to change the filetype filter. self.file_filter_menu.add_radiobutton(label=filetypes[i], variable=self.file_filter_var,value=filetypes[i],background=color_2,command=self.set_filetype_filter ) i += 1 self.file_filter_menubutton.configure(menu= self.file_filter_menu) self.buttons_frame=Frame(self.toplevel,bg=color_2,borderwidth=8,relief="groove",height=50,width=18*3) # Frame container for the buttons. self.button_cancel=Button(self.buttons_frame,bg=color_2,fg=color_1,text="Quit",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_quit) self.button_home=Button(self.buttons_frame,bg=color_2,fg=color_1,text="Home",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_home) self.button_ok=Button(self.buttons_frame,bg=color_2,fg=color_1,text=" OK ",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_ok) self.start_dir=start_dir # Start folder. self.curdir=start_dir # Current folder. self.last_dir=[] # Container for the precedent folders we visit. self.last_dir.append(start_dir) # Append start folder. self.select_filepath="" # Value to return by file selection. self.dir_name_entry.insert(0,"../"+basename(self.curdir)) if not color_2 : self.items_bg="#D9D9D9" else : self.items_bg=color_2 self.items_fg=color_1 self.highlight_color_items=highlight_color_items self.init_icons() self.ls_dir() self.update_canvas() self.dir_selection_frame.grid(row=0,column=0,sticky="WE") self.dir_name_entry.grid(row=0,column=0,in_=self.dir_selection_frame,sticky="NSEW") self.dir_name_separator.grid(row=0,column=1,in_=self.dir_selection_frame,sticky="EW") self.dir_back_button.grid(row=0,column=2,in_=self.dir_selection_frame,sticky="EW") self.canvas_frame.grid(row=1,column=0,sticky="WE") self.canvas.grid(row=0,column=0,in_=self.canvas_frame) self.canvas_scrollbar.grid(row=1,column=0,in_=self.canvas_frame,sticky="WE") self.file_selection_frame.grid(row=2,column=0,sticky="WE") self.file_name_entry.grid(row=0,column=0,in_=self.file_selection_frame,sticky="NSEW") self.file_name_separator.grid(row=0,column=1,in_=self.file_selection_frame,sticky="EW") self.file_filter_menubutton.grid(row=0,column=2,in_=self.file_selection_frame,sticky="NS") self.buttons_frame.grid(row=3,column=0,sticky="NSEW") self.button_cancel.grid(row=0,column=2,padx=32+3,pady=4,in_=self.buttons_frame) self.button_home.grid(row=0,column=4,padx=32+3,pady=4,in_=self.buttons_frame) self.button_ok.grid(row=0,column=6,padx=34+3,pady=4,in_=self.buttons_frame) self.toplevel.wait_window() def init_icons(self) : # Folder and file icons, design by me. self.image_folder=Image.open("/usr/share/ScreenLocker/Images/file_selector/folder_icon.png") self.imagetk_folder=ImageTk.PhotoImage(image=self.image_folder) self.image_file=Image.open("/usr/share/ScreenLocker/Images/file_selector/file_icon.png") self.imagetk_file=ImageTk.PhotoImage(image=self.image_file) def ls_dir(self) : ''' List an directory and split the result in folders and files containers. Finally sort the 2 containers.''' folder_content=listdir(self.curdir) self.cur_folder_entries=len(folder_content) self.cur_folder_list=[] self.cur_files_list=[] folder_content.sort() for v in folder_content : if isdir(self.curdir+"/"+v) : self.cur_folder_list.append(unicode(v,encoding='utf-8')) elif isfile(self.curdir+"/"+v) : self.cur_files_list.append(unicode(v,encoding='utf-8')) self.cur_folder_list.sort() self.cur_files_list.sort() def update_canvas(self) : ''' Generating the content from the File selection window (an canvas)''' self.clear_canvas() i=0 # global folder and file iterator. pos_x=0 # Coordinates for the rows. pos_y=0 # Coordinates in the columns. max_len=0 # Column max folder|filename length. max_len_save=0 # Saved value for filling empty canvas scrollregion. while i < len(self.cur_folder_list) : # Generating the folder items of the current folder exec(u"folder_icon_{0}=Label(self.canvas,text='{1}',image=self.imagetk_folder,relief='flat',width=17,height=17,bg=self.items_bg)".format(str(i),self.cur_folder_list[i].replace("'","\\'"))) exec(u"folder_name_{0}=Label(self.canvas,text='{1}',relief='flat',width={2},font='Monospace 9 bold',justify='left',bg=self.items_bg,fg=self.items_fg)".format(str(i),self.cur_folder_list[i].replace("'","\\'"),int(len(" "+self.cur_folder_list[i])))) if int(len(" "+self.cur_folder_list[i])) > max_len : # Update longest folder name in this column. max_len=int(len(" "+self.cur_folder_list[i])) # Storing the value for max length of the longest folder name in this column. max_len_save=max_len # Value to save for filling if the generating content take minus place as the canvas scrollregion. exec("folder_icon_{0}.bind('<Double-1>',self.select_folder)".format(str(i))) exec("folder_name_{0}.bind('<Double-1>',self.select_folder)".format(str(i))) exec("folder_name_{0}.bind('<Enter>',self.highlight_item_enter)".format(str(i))) exec("folder_name_{0}.bind('<Leave>',self.highlight_item_leave)".format(str(i))) exec("folder_icon_{0}.pack(side='left',fill=BOTH)".format(str(i))) exec("folder_name_{0}.pack(side='right',fill=BOTH)".format(str(i))) exec("self.canvas.create_window(({1},{2}),anchor='nw',window=folder_icon_{0})".format(str(i),pos_x,pos_y)) exec("self.canvas.create_window(({1}+17+1,{2}),anchor='nw',window=folder_name_{0})".format(str(i),pos_x,pos_y)) pos_y += 20 # column increment 17 height of an items + 3 pixels padding. if ( i % 9 == 0) and not i == 0 : # An column can contains 9 items and we change column. pos_y=0 # Column position updating. pos_x += 17 + (max_len*9) # Update the x coordinates according the maximal length of foldername in this column ( (9 pixels == font size) (17 pixels for the folder item icon) ) . max_len=0 i += 1 # Go to the next item. ii=0 # Files iterator. while ii < len(self.cur_files_list) : # Generating the files items of the current folder. if (self.file_filter_extension and self.cur_files_list[ii].lower().endswith(self.file_filter_extension)) or not self.file_filter_extension : # applying filter of no filetype filering. exec(u"file_icon_{0}=Label(self.canvas,text='{1}',image=self.imagetk_file,relief='flat',width=17,height=17,bg=self.items_bg)".format(str(i),self.cur_files_list[ii].replace("'","\\'"))) exec(u"file_name_{0}=Label(self.canvas,text='{1}',relief='flat',width={2},font='Monospace 9 normal',justify='left',bg=self.items_bg,fg=self.items_fg)".format(str(i),self.cur_files_list[ii].replace("'","\\'"),int(len(" "+self.cur_files_list[ii])))) if int(len(" "+self.cur_files_list[ii])) > max_len : # Update longest filename in this column. max_len=int(len(" "+self.cur_files_list[ii])) # Storing the value for max length of the longest filename in this column. max_len_save=max_len # Value to save for filling if the generating content take minus place as the canvas scrollregion. exec("file_icon_{0}.bind('<Double-1>',self.select_file)".format(str(i))) exec("file_name_{0}.bind('<Double-1>',self.select_file)".format(str(i))) exec("file_name_{0}.bind('<Enter>',self.highlight_item_enter)".format(str(i))) exec("file_name_{0}.bind('<Leave>',self.highlight_item_leave)".format(str(i))) exec("file_icon_{0}.pack(side='left',fill=BOTH)".format(str(i))) exec("file_name_{0}.pack(side='right',fill=BOTH)".format(str(i))) exec("self.canvas.create_window(({1},{2}),anchor='nw',window=file_icon_{0})".format(str(i),pos_x,pos_y)) exec("self.canvas.create_window(({1}+17+1,{2}),anchor='nw',window=file_name_{0})".format(str(i),pos_x,pos_y)) pos_y += 20 # column increment 17 height of an items + 3 pixels padding. if ( i % 9 == 0) and not i == 0 : # An column can contains 9 items and we change column. # Note: we check the common file & folder iterator. pos_y=0 # Column position updating. pos_x += 17 + (max_len*9) # Update the x coordinates according the maximal length of filename in this column ( (9 pixels == font size) (17 pixels for the file item icon) ). max_len=0 i += 1 ii += 1 if not pos_x+(max_len_save*9)+17 < 18*28 : # items collection greater than the canvas scrollregion. self.canvas.config(scrollregion=(0,0,pos_x+(max_len_save*9)+17,0)) else : # items collection littler than the canvas scrollregion. self.canvas.config(scrollregion=(0,0,18*28,0)) def clear_canvas(self) : for child in self.canvas.children.values() : child.destroy() def highlight_item_enter(self,event) : event.widget.config(bg=self.highlight_color_items) def highlight_item_leave(self,event) : event.widget.config(bg=self.items_bg) def select_folder(self,event) : if isdir(self.curdir+"/"+event.widget.cget("text").lstrip()) : # event.widget.cget("text") return the selected folder. sea the update_canvas() method. self.select_filepath="" self.file_name_entry.delete(0,END) if self.curdir.startswith('//') : # Bugfix. self.curdir=self.curdir[1::] self.last_dir.append(self.curdir) else : self.last_dir.append(self.curdir) for v in self.last_dir : # Bigfix if self.last_dir.count(v) > 1 : self.last_dir.remove(v) try : # in case of access right this will fail immediatelly listdir(self.curdir+"/"+event.widget.cget("text")) self.curdir=self.curdir+"/"+event.widget.cget("text") self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+event.widget.cget("text")) self.ls_dir() self.update_canvas() except : pass def select_file(self,event) : if isfile(self.curdir+"/"+event.widget.cget("text")) : # Set the value to return and fill the file selection field. self.select_filepath=self.curdir+"/"+event.widget.cget("text") self.file_name_entry.delete(0,END) self.file_name_entry.insert(0,event.widget.cget("text")) def folder_go_back(self) : if len(self.last_dir) > 1 : self.curdir=self.last_dir.pop(-1) # pop the last value from the visited folder folders else : # In case we have yet only 1 folder in the visited folder container. if self.last_dir[0].rfind("/") : # The value of the container is not the root folder ( / ) but not the /home/username folder who can be only visited folder. self.last_dir[0]=self.last_dir[0][0:self.last_dir[0].rfind("/")] self.curdir=self.last_dir[0] elif self.last_dir[0].rfind("/") == 0 : # The value of the container is the root folder. self.last_dir[0]="/" self.curdir=self.last_dir[0] else : # The value is the /home/username directory self.curdir=self.last_dir[0] self.file_name_entry.delete(0,END) self.select_filepath="" self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+basename(self.curdir)) self.ls_dir() self.update_canvas() def set_filetype_filter(self) : '''Change filetype filter.''' self.file_filter_menubutton.config(text=self.file_filter_var.get()) self.file_filter_extension=self.file_filter_var.get()[1::] # Contains the selected filetype ( in form '.'+filetype ). self.file_name_entry.delete(0,END) self.select_filepath="" self.ls_dir() self.update_canvas() def item_selection_ok(self) : '''Return the selected filepath or empty string and destroy File_selector instance''' if self.select_filepath : self.toplevel.destroy() return True def item_selection_quit(self) : '''destroy File_selector instance''' self.toplevel.destroy() return False def item_selection_home(self) : '''Change current directory to the /home/username folder''' self.curdir=expanduser("~") self.select_filepath="" self.file_name_entry.delete(0,END) self.last_dir=[] self.last_dir.append(expanduser("~")) self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+basename(self.curdir)) self.ls_dir() self.update_canvas()