def set_file(self): window = Toplevel(self, bg='#C1CDCD') window.title('set_file_size') window.geometry('400x400') window.resizable(0, 0) # 禁止调整窗口大小 file_num = 16 var = [] for i in range(file_num): var.append(StringVar()) Label(window, text=u"请填写需要生成的测试文件大小,单位M(无需填满):", bg='#C1CDCD').grid(row=0, column=0, columnspan=4, pady=5, padx=15) for j in range(file_num / 2): Label(window, text=u"文件大小" + str(j * 2) + ":", bg='#C1CDCD').grid(row=j + 1, column=0, pady=8, padx=10) Entry(window, width=10, textvariable=var[j * 2]).grid(row=j + 1, column=1, pady=8, padx=10) Label(window, text=u"文件大小" + str(j * 2 + 1) + ":", bg='#C1CDCD').grid(row=j + 1, column=2, pady=8, padx=10) Entry(window, width=10, textvariable=var[j * 2 + 1]).grid(row=j + 1, column=3, pady=8, padx=10) def get_file_list(): v3 = '' self.file_list[:] = [] for k in range(file_num): v = var[k].get() if v == '' or v.isspace() or not v.isdigit(): continue else: self.file_list.append(int(v)) self.file_list = list(set(self.file_list)) if 0 in self.file_list: self.file_list.remove(0) self.file_list.sort() for size in self.file_list: v3 = v3 + str(size) + 'M' + ',' print v3 self.v3.set(v3) window.destroy() Button(window, text=u"确定", width=20, command=get_file_list, bg='#C1CDCD').grid(row=file_num / 2 + 2, column=0, columnspan=4, pady=8, padx=10) window.protocol("WM_DELETE_WINDOW", window.destroy)
def __init__(self, rows, cols, width=500, height=250, side=25, block_buffer=10, title='Grid', background='tan', draw_fingers=False): assert (rows <= MAX_ROWS) assert (cols <= MAX_COLS) tk = Tk() tk.withdraw() top = Toplevel(tk) top.wm_title(title) top.protocol('WM_DELETE_WINDOW', top.destroy) self.width = width self.height = height self.rows = rows self.cols = cols self.canvas = Canvas(top, width=self.width, height=self.height, background=background) self.canvas.pack() self.side = side self.block_buffer = block_buffer self.draw_fingers = draw_fingers self.cells = {} self.robot = [] self.draw_environment()
def select_start_options(self): ''' popup box to select side and difficulty levels ''' print 'select game start options' popup = Toplevel(self.gui, width=300, height=110) popup.title('Choose Game Side and Level') # stays on top of the game canvass popup.transient(self.gui) popup.grab_set() # bind window close events popup.bind('<Escape>', lambda e: self.not_selected_start_options(popup)) popup.protocol("WM_DELETE_WINDOW", lambda : self.not_selected_start_options(popup)) # choose side label1 = Label(popup, text="Side", height=30, width=50) label1.place(x=10, y=5, height=30, width=50) val1 = IntVar() bt_north = Radiobutton(popup, text="White", variable=val1, value=1) bt_north.place(x=60, y=10) bt_south = Radiobutton(popup, text="Black", variable=val1, value=2) bt_south.place(x=120, y=10) # by default, human plays first, meaning play the north side if self.choose_side == 'north': bt_north.select() else: bt_south.select() # choose difficulty level label2 = Label(popup, text="Level", height=30, width=50) label2.place(x=10, y=35, height=30, width=50) val2 = IntVar() bt_level1 = Radiobutton(popup, text="Dumb", variable=val2, value=1) bt_level1.place(x=60, y=40) bt_level2 = Radiobutton(popup, text="Smart", variable=val2, value=2) bt_level2.place(x=120, y=40) bt_level3 = Radiobutton(popup, text="Genius", variable=val2, value=3) bt_level3.place(x=180, y=40) # by default, the game is medium level if self.choose_level == 1: bt_level1.select() elif self.choose_level == 2: bt_level2.select() elif self.choose_level == 3: bt_level3.select() button = Button(popup, text='SET', \ command=lambda: self.selected_start_options(popup, val1, val2)) button.place(x=70, y=70)
def __init__(self, width=500, height=500, title='PRM', background='tan'): tk = Tk() tk.withdraw() top = Toplevel(tk) top.wm_title(title) top.protocol('WM_DELETE_WINDOW', top.destroy) self.width = width self.height = height self.canvas = Canvas(top, width=self.width, height=self.height, background=background) self.canvas.pack()
def initUI(self): # Main Window self.parent.title("gBot") self.style = Style() self.style.theme_use("default") self.pack(fill=BOTH, expand=1) # Debug Window Toplevel1 = Toplevel(self) Toplevel1.title("gBot Debug Console") self.pack(fill=BOTH, expand=1) TL_T1 = Text(Toplevel1, width=50) TL_T1.pack() Toplevel1.state("withdrawn") Toplevel1.protocol('WM_DELETE_WINDOW', lambda:Toplevel1.state("withdrawn")) Toplevel1.attributes("-topmost", True) # Username Input L1 = Label(self, text="G+ User Name") L1.grid(row=0, column=0, sticky=E, ipady=1) E1 = Entry(self, width=30) E1.grid(row=0, column=1, ipady=1, sticky=E) # Password Input L2 = Label(self, text="G+ Password") L2.grid(row=1, column=0, sticky=E, ipady=1) E2 = Entry(self, width=30) E2.grid(row=1, column=1, ipady=1, sticky=E) # Output Path Input L3 = Label(self, text="Output Path") L3.grid(row=2, column=0, sticky=E, pady=1) E3 = Entry(self, width=30) E3.grid(row=2, column=1, ipady=1, sticky=E) E3.insert(0, "%s\links.txt" % (os.getcwd())) # Num Posts L4 = Label(self, text="# Of Posts") L4.grid(row=3, column=0, sticky=E, pady=1) S1 = Spinbox(self, from_=1, to=9999999, width=28) S1.grid(row=3, column=1, ipady=1, sticky=E) # Post Input T1 = Text(self, width=30) T1.grid(row=5, columnspan=2, sticky=W+E, pady=1) # Start button B1 = Button(self, text="Start Posting", command=lambda:self.doPosting(B1,TL_T1,E1.get(),E2.get(),T1.get(1.0,END),E3.get(),S1.get())) B1.grid(row=6,columnspan=2, sticky=W+E) # Debug button B2 = Button(self, text="Debug log", command=lambda:Toplevel1.state("normal")) B2.grid(row=7, columnspan=2, sticky=W+E) self.addDebug(TL_T1,"Started successfully")
def Modules (close = False): if not Modules.singleton: win = Toplevel (takefocus = True) win.protocol ('WM_DELETE_WINDOW', win.withdraw) win.resizable (width = False, height = False) win.withdraw() oApp = GUI (master = win) Modules.singleton = _Modules (oApp = oApp) return Modules.singleton
def PPSel(): if PPSel.singleton == None: win = Toplevel(takefocus=True) win.protocol('WM_DELETE_WINDOW', win.withdraw) win.resizable(width=False, height=False) win.withdraw() oApp = GUI(master=win) PPSel.singleton = _PPSel(oApp=oApp) return PPSel.singleton
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()
def __init__(self, master, main_window): self.master = master self.main_window = main_window top = Toplevel(master) top.title(_("Global Options")) top.transient(master) top.protocol('WM_DELETE_WINDOW', self.close_dlg) top.geometry('%+d%+d' % (master.winfo_rootx() + 100, master.winfo_rooty() + 100)) self.top = top self.build_dlg()
def XMC (master, sample): if XMC.singleton == None: win = Toplevel (takefocus = True) win.protocol ('WM_DELETE_WINDOW', win.withdraw) win.withdraw() oApp = GUI (win, sample) XMC.singleton = _XMC (oApp, sample) if master not in XMC.master: XMC.master.append (master) return XMC.singleton
def show_log(self, order): server_id = self.queue[order]['server_id'].get() logging.info('server_id: {0}'.format(server_id)) t = Toplevel(self) logging.info('toplvl: {0}'.format(repr(t))) t.wm_title("Log for {serv}".format(serv = server_id)) log = Text(t) t.protocol("WM_DELETE_WINDOW", lambda win=t, log=log: self.close_log(win, log)) logging.info('log: {0}'.format(repr(log))) log.pack(side="top", fill="both", padx=10, pady=10) if log.winfo_exists(): logging.info('log exists_show_log') self.refresh_log(log, server_id) logging.info('thread started')
def HIRES(master, oTCON, oXHIRES, sample, cryostat): if HIRES.singleton == None: win = Toplevel(takefocus=True) win.protocol('WM_DELETE_WINDOW', win.withdraw) win.withdraw() oApp = GUI(win, sample) HIRES.singleton = _HIRES(oApp, oTCON, oXHIRES, sample, cryostat) if master not in HIRES.master: HIRES.master.append(master) return HIRES.singleton
def Sample(master): if not Sample.singleton: win = Toplevel(takefocus=True) win.protocol('WM_DELETE_WINDOW', win.withdraw) win.resizable(width=False, height=False) win.withdraw() oApp = GUI(master=win) Sample.singleton = _Sample(oApp) if master not in Sample.master: Sample.master.append(master) return Sample.singleton
def configure_param_lmme_dialog(self): w = Toplevel() w.protocol('WM_DELETE_WINDOW', self.hide_param_dialog) self.param_dlg = w w.withdraw() # cache la fenetre w.rowconfigure(0, weight=1) w.columnconfigure(0, weight=1) prm = ParamModeLMME( w, "Paramètres du calcul modal pour la méthode LMME", relief='sunken', borderwidth=2) prm.grid(row=0, column=0) self.param_mode_iter_simult_lmme = prm Button(w, text="Appliquer", command=self.anything_changed).grid( row=1, column=0) Button(w, text="OK", command=self.hide_param_dialog).grid( row=2, column=0)
def SUS (master, oTCON, oXLIA, oXMC, sample, cryostat): if SUS.singleton == None: win = Toplevel (takefocus = True) win.protocol ('WM_DELETE_WINDOW', win.withdraw) win.withdraw() oApp = GUI (win, sample) SUS.singleton = _SUS ( oApp, oTCON, oXLIA, oXMC, sample, cryostat) if master not in SUS.master: SUS.master.append (master) return SUS.singleton
def create_widgets(self): top = Toplevel(self.root) top.bind("<Return>", self.default_command) top.bind("<Escape>", self.close) top.protocol("WM_DELETE_WINDOW", self.close) top.wm_title(self.title) top.wm_iconname(self.icon) top.resizable(height=False, width=False) self.ttop = top self.top = Frame(top) self.row = 0 self.top.grid(sticky='news') self.create_entries() self.create_option_buttons() self.create_other_buttons() self.create_command_buttons()
def run(): """ Esegue l'emulatore del pdp8 """ CD = pdp8() principale = Tk() principale.title("Pdp8 Emulator : Assembly Editor") emulatore = Toplevel() emulatore.title("Pdp8 Emulator") emulatore.geometry("1015x589") edit = Editor(principale, CD) scrollbar1 = AutoScrollbar(emulatore) scrollbar1.grid(row=0, column=1, sticky=N + S) scrollbar2 = AutoScrollbar(emulatore, orient=HORIZONTAL) scrollbar2.grid(row=1, column=0, sticky=E + W) finestra = Canvas(emulatore, yscrollcommand=scrollbar1.set, xscrollcommand=scrollbar2.set) finestra.grid(row=0, column=0, sticky=N + S + E + W) scrollbar1.config(command=finestra.yview) scrollbar2.config(command=finestra.xview) emulatore.grid_rowconfigure(0, weight=1) emulatore.grid_columnconfigure(0, weight=1) emul = Emulatore(finestra, edit, CD, emulatore) finestra.create_window(0, 0, anchor=NW, window=emul.master) emul.master.update_idletasks() finestra.config(scrollregion=finestra.bbox("all")) principale.protocol("WM_DELETE_WINDOW", edit.exit) emulatore.protocol("WM_DELETE_WINDOW", emul.exit) principale.mainloop() emulatore.mainloop()
def __init__(self, width, height, side=25, title='Grid', background='grey'): tk = Tk() tk.withdraw() top = Toplevel(tk) top.wm_title(title) top.protocol('WM_DELETE_WINDOW', top.destroy) self.width = width self.height = height self.canvas = Canvas(top, width=self.width, height=self.height, background=background) self.canvas.pack() self.side = side self.cells = {}
def create_widgets(self): '''Create basic 3 row x 3 col search (find) dialog. Other dialogs override subsidiary create_x methods as needed. Replace and Find-in-Files add another entry row. ''' top = Toplevel(self.root) top.bind("<Return>", self.default_command) top.bind("<Escape>", self.close) top.protocol("WM_DELETE_WINDOW", self.close) top.wm_title(self.title) top.wm_iconname(self.icon) self.top = top self.row = 0 self.top.grid_columnconfigure(0, pad=2, weight=0) self.top.grid_columnconfigure(1, pad=2, minsize=100, weight=100) self.create_entries() # row 0 (and maybe 1), cols 0, 1 self.create_option_buttons() # next row, cols 0, 1 self.create_other_buttons() # next row, cols 0, 1 self.create_command_buttons() # col 2, all rows
def construct(self): """ Construct the window and the frame used to display the XML :return: """ top = Toplevel() top.withdraw() top.protocol("WM_DELETE_WINDOW", self.view_xml_pane) top.columnconfigure(0, weight=1) top.rowconfigure(0, weight=1) top.title("XML Preview") self._pane = top xml_area = Text(top, borderwidth=2, relief="sunken") xml_area.config(font=("consolas", 12), undo=True, wrap='word', state=DISABLED) xml_area.grid(row=0, column=0, sticky="nsew", padx=2, pady=2) scrollbar = Scrollbar(top, command=xml_area.yview) scrollbar.grid(row=0, column=1, sticky='nsew') xml_area['yscrollcommand'] = scrollbar.set self._text_area = xml_area
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 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 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()
class DrawingWindow: def __init__(self, width, height, x_min, x_max, y_min, y_max, title, parent=None): self.title = title if parent: self.parent = parent self.top = parent.getWindow(title) else: self.tk = Tk() self.tk.withdraw() self.top = Toplevel(self.tk) self.top.wm_title(title) self.top.protocol('WM_DELETE_WINDOW', self.top.destroy) self.window_width = width self.window_height = height self.canvas = Canvas(self.top, width=self.window_width, height=self.window_height, background="white") self.canvas.pack() self.x_scale = width / float( x_max - x_min) # multiply an input value by this to get pixels self.y_scale = height / float(y_max - y_min) self.x_min = x_min self.y_min = y_min self.x_max = x_max self.y_max = y_max def scale_x(self, x): return self.x_scale * (x - self.x_min) def scale_y(self, y): return self.window_height - self.y_scale * (y - self.y_min) def draw_point(self, x, y, color="blue", radius=1): window_x = self.scale_x(x) window_y = self.scale_y(y) return self.canvas.create_rectangle(window_x - radius, window_y - radius, window_x + radius, window_y + radius, fill=color, outline=color) def draw_text(self, x, y, label): return self.canvas.create_text(self.scale_x(x), self.scale_y(y), text=label) # font="Arial 20",fill="#ff0000" def draw_poly(self, verts, color="black", outline="black"): return self.canvas.create_polygon( [(self.scale_x(point.x), self.scale_y(point.y)) for point in verts], fill=color, outline=outline) def draw_rect(self, (x1, y1), (x2, y2), color="black"):
class ContinuousTMPViewer(object): def __init__(self, suction_height, regions, tl_x=0, tl_y=0, width=500, height=150, title='Grid', background='tan'): self.tk = Tk() # tk.geometry('%dx%d+%d+%d'%(width, height, 100, 0)) self.tk.withdraw() self.top = Toplevel(self.tk) self.top.wm_title(title) self.top.protocol('WM_DELETE_WINDOW', self.top.destroy) self.suction_height = suction_height self.regions = regions self.tl_x = tl_x self.tl_y = tl_y self.width = width self.height = height self.canvas = Canvas(self.top, width=self.width, height=self.height, background=background) self.canvas.pack() # self.center() self.move_frame(self.tl_x, self.tl_y) max_width = max( map(get_width, regions.values())) # Really should take width of max minus min self.dist_to_pixel = (self.width - 2 * PIXEL_BUFFER ) / max_width # Maintains aspect ratio self.dist_width = self.width / self.dist_to_pixel self.dist_height = self.height / self.dist_to_pixel self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT self.robot_dist = self.dist_height / 2. self.robot = [] self.blocks = [] self.holding = None self.environment = [] self.draw_environment() def center(self): 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 self.top.geometry("%dx%d+%d+%d" % (size + (x, y))) def move_frame(self, x, y): self.top.update_idletasks() size = tuple( int(_) for _ in self.top.geometry().split('+')[0].split('x')) self.top.geometry("%dx%d+%d+%d" % (size + (x, y))) def scale_x(self, x): # x \in [-self.dist_width/2, self.dist_width/2] return self.dist_to_pixel * (x + self.dist_width / 2.) def scale_y(self, y): # y \in [0, self.dist_height] return self.ground_height - self.dist_to_pixel * y def draw_block(self, x, y, width, height, name='', color='blue'): self.blocks.extend([ self.canvas.create_rectangle(self.scale_x(x - width / 2.), self.scale_y(y), self.scale_x(x + width / 2.), self.scale_y(y + height), fill=color, outline='black', width=2), self.canvas.create_text(self.scale_x(x), self.scale_y(y + height / 2), text=name), ]) # def draw_holding(self, x, width, height, color='blue'): # self.holding = self.canvas.create_rectangle(self.scale_x(x - width / 2.), # self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2 - height), # self.scale_x(x + width / 2.), # self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2), # fill=color, outline='black', width=2) def draw_region(self, region, name='', color='red'): x1, x2 = map(self.scale_x, region) y1, y2 = self.ground_height, self.height self.environment.extend([ self.canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline='black', width=2), self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=name), ]) def draw_environment(self): # TODO: automatically draw in order self.environment = [] for name, region in sorted(self.regions.items(), key=lambda pair: get_width(pair[1]), reverse=True): self.draw_region(region, name=name, color=name) def draw_robot( self, x, y, color='yellow' ): # TODO - could also visualize as top grasps instead of side grasps #y = self.robot_dist self.robot = [ self.canvas.create_rectangle( self.scale_x(x - SUCTION_WIDTH / 2.), self.scale_y(y - self.suction_height / 2.), self.scale_x(x + SUCTION_WIDTH / 2.), self.scale_y(y + self.suction_height / 2.), fill=color, outline='black', width=2), self.canvas.create_rectangle( self.scale_x(x - STEM_WIDTH / 2.), self.scale_y(y + self.suction_height / 2.), self.scale_x(x + STEM_WIDTH / 2.), self.scale_y(y + self.suction_height / 2. + STEM_HEIGHT), fill=color, outline='black', width=2), ] def clear_state(self): for block in self.blocks: self.canvas.delete(block) for part in self.robot: self.canvas.delete(part) if self.holding is not None: self.canvas.delete(self.holding) def clear_all(self): self.canvas.delete('all') def save(self, filename): # TODO: screen recording based on location like I did before # TODO: only works on windows # self.canvas.postscript(file='%s.ps'%filename, colormode='color') #from PIL import ImageGrab try: import pyscreenshot as ImageGrab except ImportError: return None x, y = self.top.winfo_x(), 2 * self.top.winfo_y() width, height = self.top.winfo_width(), self.top.winfo_height( ) # winfo_width, winfo_reqheight path = filename + '.png' ImageGrab.grab((x, y, x + width, y + height)).save(path) return path
def select_start_options(self): ''' popup box to select side and difficulty levels ''' print 'select game start options' popup = Toplevel(self.gui, width=300, height=110) popup.title('Choose Game Side and Level') # stays on top of the game canvass popup.transient(self.gui) popup.grab_set() # bind window close events popup.bind('<Escape>', lambda e: self.not_selected_start_options(popup)) popup.protocol("WM_DELETE_WINDOW", lambda: self.not_selected_start_options(popup)) # choose side label1 = Label(popup, text="Side", height=30, width=50) label1.place(x=10, y=5, height=30, width=50) val1 = IntVar() bt_north = Radiobutton(popup, text="White", variable=val1, value=1) bt_north.place(x=60, y=10) bt_south = Radiobutton(popup, text="Black", variable=val1, value=2) bt_south.place(x=120, y=10) # by default, human plays first, meaning play the north side if self.choose_side == 'north': bt_north.select() else: bt_south.select() # choose difficulty level label2 = Label(popup, text="Level", height=30, width=50) label2.place(x=10, y=35, height=30, width=50) val2 = IntVar() bt_level1 = Radiobutton(popup, text="Dumb", variable=val2, value=1) bt_level1.place(x=60, y=40) bt_level2 = Radiobutton(popup, text="Smart", variable=val2, value=2) bt_level2.place(x=120, y=40) bt_level3 = Radiobutton(popup, text="Genius", variable=val2, value=3) bt_level3.place(x=180, y=40) # by default, the game is medium level if self.choose_level == 1: bt_level1.select() elif self.choose_level == 2: bt_level2.select() elif self.choose_level == 3: bt_level3.select() button = Button(popup, text='SET', \ command=lambda: self.selected_start_options(popup, val1, val2)) button.place(x=70, y=70)
def manualbounds(event): def checkbounds(event): try: b = minmaxT.get(1.0, END) bounds = array([fromstring(x, dtype=float, sep="-") for x in b.replace(" ", "").split()]) if (bounds.shape[1] == 2 and (bounds[:, 0] < bounds[:, 1]).all()): minmaxT.config(bg=Styles.colours["lightGreen"]) return True else: minmaxT.config(bg=Styles.colours["lightRed"]) return False except: minmaxT.config(bg=Styles.colours["lightRed"]) return False return False def submite(event): submit() def submit(): if checkbounds(""): b = minmaxT.get(1.0, END) bounds = array([fromstring(x, dtype=float, sep="-") for x in b.replace(" ", "").split()]) self.params["bounds"][:] = [] for bound in bounds: self.params["bounds"].append(bound.tolist()) boundswindow.destroy() if self.checkall(): self.maingui("model") self.console.log( "Bounds have been successfully set to following dimensions " + str(len(self.params["bounds"]))) else: popupwindow("You have not set correct bounds", 5, "The bounds you have set do not correspond to the format specified, please review the bounds you have entered.")( "") if self.checkall(): self.maingui("model") else: self.console.notready("model") def cancel(event): self.params["bounds"] = orginalbounds boundswindow.destroy() boundswindow = Toplevel() boundswindow.title("Bounds") boundswindow.config(pady=5, padx=5) boundswindow.protocol("WM_DELETE_WINDOW", submit) orginalbounds = None boundswindowheader = header(boundswindow, "Set model bounds:") qB = qbutton(boundswindow, l=popupwindow("How to set bounds?", 8, " The bounds give the model maximum and minimum for each input parameter value. You can set the bounds from a file in CSV file" "where first column is the minimum and second column is the maximum, or through the window presented prior.")) minmax = headersmall(boundswindow, "Minimum,Maximum") tut = Message(boundswindow, width=250, text="For each dimension set the minimum and maximum, seperated by a minus sign. Each dimension split by a newline (enter)") f = Frame(boundswindow) minmaxT = Text(f, width=20, height=10, relief=FLAT, padx=15, pady=15, font=Styles.fonts["bounds"]) minmaxT.bind("<KeyRelease>", checkbounds) if (self.params["bounds"] is not []): orginalbounds = list(self.params["bounds"]) for b in self.params["bounds"]: minmaxT.insert(END, str(b[0]) + " - " + str(b[1]) + "\n") checkbounds("") scroll = Scrollbar(f, command=minmaxT.yview, relief=FLAT) minmaxT.configure(yscrollcommand=scroll.set) minmaxT.grid(row=0, padx=3, column=0) scroll.grid(row=0, column=1) submitboundsbutton = yellowbutton(boundswindow, "Submit", 20, submite) self.isreadyB(submitboundsbutton, 1000) cancelboundsbutton = yellowbutton(boundswindow, "Cancel", 20, cancel) boundswindowheader.grid(row=0, column=0, sticky=W, columnspan=1) qB.grid(row=0, padx=3, column=1, sticky=E) tut.grid(row=1, column=0, columnspan=2) minmax.grid(row=2, padx=3, column=0) f.grid(row=3, column=0, columnspan=2) Label(boundswindow, text="").grid(row=4, column=0, sticky=W, columnspan=2) submitboundsbutton.grid(row=5, padx=3, column=0, columnspan=1) cancelboundsbutton.grid(row=5, padx=3, column=1, columnspan=1)
class App(Frame): results_window = False def __init__(self, *args, **kwargs): Frame.__init__(self, *args, **kwargs) self.__init_main(*args, **kwargs) def __init_main(self, *args, **kwargs): self.root = args[0] self.root.filename = "" self.root.wm_title("RSTool") self.root.protocol("WM_DELETE_WINDOW", self.__delete_root_window) self.root.bind("<Destroy>", self.__destroy_root_window) self.menubar = Menu(self.root) self.filemenu = Menu(self.menubar) self.filemenu.add_command(label="Save as...", command=self.save_to_file) self.filemenu.add_separator() self.filemenu.add_command(label="Exit", command=self.root.destroy) self.menubar.add_cascade(label="File", menu=self.filemenu) self.root.config(menu=self.menubar) self.tests = [ Frequency, BlockFrequency, Runs, LongestRunOfOnes, Rank, DiscreteFourierTransform, Universal, Serial, ApproximateEntropy, CumulativeSums, RandomExcursions, RandomExcursionsVariant, ] self.slowtests = [ NonOverlappingTemplateMatching, # Slow OverlappingTemplateMatching, # Slow LinearComplexity # Slow ] # self.run_RandomWalkPlot = IntVar(self.root) rcounter = 0 # Create and pack the title row: title = "NYUAD\nCenter for Cyber Security\nRandomness Testing Tool\nv0.9.0" self.l1 = Label(self.root, text=title) self.l1.grid(column=0, row=rcounter, columnspan=2, sticky=N) # self.l1.pack() rcounter += 1 # Create and pack the "Open File" button and bind the loadFile method: self.b1 = Button(self.root, text="Open File", command=self.loadFile) self.b1.grid(column=0, row=rcounter, columnspan=1, pady=5) # rcounter += 1 # self.b1.pack() # Create and pack the filename: self.l2 = Label(self.root, text=self.root.filename) self.l2.grid(column=1, row=rcounter, columnspan=2, sticky=W, padx=(5, 10)) # self.l1.pack() rcounter += 1 # Create textbox for bit-limit self.nl = Label(self.root, text="Number of bits to test: (0 to test all)") self.nl.grid(column=0, row=rcounter, columnspan=1) rcounter += 1 self.nt = Text(self.root, state="normal", width="15", height="1") self.nt.insert(END, "0") self.nt.grid(column=0, row=rcounter, columnspan=1, padx=10, pady=(0, 5)) rcounter += 1 # Create and pack the "Select/Deselect All" button and bind the checkAll method: self.b2 = Button(self.root, text="Select/Deselect All Tests", command=self.checkAll) self.b2.grid(column=0, row=rcounter, columnspan=1, pady=(0, 5)) rcounter += 1 # self.b2.pack() # Create and pack the "Select/Deselect Fast" button and bind the checkFast method: self.b3 = Button(self.root, text="Select/Deselect Fast Tests", command=self.checkFast) self.b3.grid(column=0, row=rcounter, columnspan=1, pady=(0, 5)) rcounter += 1 # self.b2.pack() # Create and pack the "Select/Deselect Slow" button and bind the checkSlow method: self.b4 = Button(self.root, text="Select/Deselect Slow Tests", command=self.checkSlow) self.b4.grid(column=0, row=rcounter, columnspan=1, pady=(0, 5)) rcounter += 1 # self.b2.pack() # Set IntVars for each test to check if it is selected to run: for test in self.tests + self.slowtests: setvar = "self.run_%s = IntVar(self.root)" % (test.__name__) exec(setvar) setvar = "" for i in range(func_data[test.__name__][1]): setvar = "self.%s_arg_%s = IntVar(self.root)" % ( test.__name__, func_data[test.__name__][2][i]) # Example: # self.run_Frequency = IntVar(self.root) # Create and pack the checkbutton for each test and bind its IntVar to it: for test in self.tests + self.slowtests: make = [ "self.cb_%s = " % (test.__name__), "Checkbutton(self.root, ", "text='%s ', " % (func_data[test.__name__][0]), "variable=self.run_%s)" % (test.__name__) ] make = "".join(make) grid = [ "self.cb_%s.grid(" % (test.__name__), "column=0, row=%d, sticky=W)" % rcounter ] grid = "".join(grid) # args stuff rcounter += 1 # pack = "self.cb_%s.pack()" % (test.__name__) exec(make) exec(grid) # exec(pack) # Example: # self.cb1 = Checkbutton(self.root, text="Frequency", # variable=self.run_Frequency) # self.cb1.pack() # Create and pack the "Run Tests" button and bind the runTests method: self.rb = Button(self.root, text="Run Tests", command=self.runTests) self.rb.grid(column=0, row=rcounter, columnspan=2) rcounter += 1 # self.rb.pack() self.root.resizable(0, 0) self.root.lift() self.root.attributes('-topmost', True) self.root.after_idle(self.root.attributes, '-topmost', False) def __delete_root_window(self): # print "delete_root_window" try: self.root.destroy() except: pass def __destroy_root_window(self, event): # print "destroy_root_window", event pass def __delete_results_window(self): # print "delete_results_window" try: self.results_window.destroy() except: pass def __destroy_results_window(self, event): # print "destroy_results_window", event self.results_window = False def __make_results_window(self): # wname = "results_window" self.results_window = Toplevel(self, name="results_window") self.results_window.protocol("WM_DELETE_WINDOW", self.__delete_results_window) self.results_window.bind("<Destroy>", self.__destroy_results_window) self.results_window.wm_title("Test Results") self.results_window.config(menu=self.menubar) self.results_save_button = Button(self.results_window, text="Save to File", command=self.save_to_file) self.results_save_button.pack() self.results_text = Text(self.results_window, state="normal", width="70", height="50") self.results_text.pack(fill="both", expand=True, padx=10) def loadFile(self): # print "loadFile called!" self.root.filename = tkFileDialog.askopenfilename( initialdir=".", title="Select file...") # print (self.root.filename) # self.l2.config(text=self.root.filename) def save_to_file(self): if self.results_window: self.root.outfile = tkFileDialog.asksaveasfile( mode='w', defaultextension=".txt", initialdir=".", initialfile="output", title="Save as...") data = str(self.results_text.get(0.0, END)) self.root.outfile.write(data) self.root.outfile.close() def checkAll(self): all_checked = 1 for test in self.tests + self.slowtests: if not eval('self.run_' + test.__name__ + '.get()'): all_checked = 0 val = 1 - all_checked for test in self.tests + self.slowtests: eval('self.run_' + test.__name__).set(val) def checkFast(self): all_checked = 1 for test in self.tests: if not eval('self.run_' + test.__name__ + '.get()'): all_checked = 0 val = 1 - all_checked for test in self.tests: eval('self.run_' + test.__name__).set(val) def checkSlow(self): all_checked = 1 for test in self.slowtests: if not eval('self.run_' + test.__name__ + '.get()'): all_checked = 0 val = 1 - all_checked for test in self.slowtests: eval('self.run_' + test.__name__).set(val) def text_insert(self, text, noret=False): if not self.results_window: self.__make_results_window() place = 'end' if not self.results_text: raise Exception("results_text does not exist") if type(text) != str: raise TypeError("Expected str, got %s: %s" % (type(text), text)) # self.results_text.configure(state="normal") # enables changing content self.results_text.insert(place, text + ["\n", ""][noret]) self.update_idletasks() # self.results_text.configure(state="disabled") # relocks the content def getn(self): return int(self.nt.get("1.0", END)) def setn(self, n): self.nt.delete(1.0, END) self.nt.insert(END, str(int(n))) def runTests(self): if self.results_window: self.__delete_results_window() cont = True try: n = self.getn() if n < 0: raise ValueError except Exception as e: print 'Error:', e self.setn("0") cont = False if cont: try: if self.root.filename == "": raise ValueError("No file selected") e = read_data(self.root.filename) if n == 0: n = len(e) e = e[:n] if len(e) == 0: raise LengthError("No data in file") out = "Data read:\n" out += "e = " out += "".join([str(i) for i in e][:min(32, len(e))]) out += ["", "..."][len(e) > 32] + "\n" out += "See test_results folder for detailed results\n" self.text_insert(out) except: self.text_insert("Failed to read data.") cont = False if cont: # for test in self.tests: # self.text_insert("self.run_" + test.__name__ + " = " + str(eval( # "self.run_" + test.__name__ + ".get()"))) test_dir = "./test_results" if not os.path.exists(test_dir): os.makedirs(test_dir) for test in self.tests + self.slowtests: try: if eval("self.run_" + test.__name__ + ".get()"): self.text_insert("Running " + test.__name__ + ":") output = test(e) self.text_insert(["Non-Random", "Random"][output]) self.text_insert("\n") except Exception as e: self.text_insert("\nError in %s: %s\n" % (test.__name__, e.__str__())) self.text_insert("Tests completed.")
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 ContinuousTMPViewer(object): def __init__(self, regions, tl_x=0, tl_y=0, width=500, height=250, title='Grid', background='tan'): self.tk = Tk() # tk.geometry('%dx%d+%d+%d'%(width, height, 100, 0)) self.tk.withdraw() self.top = Toplevel(self.tk) self.top.wm_title(title) self.top.protocol('WM_DELETE_WINDOW', self.top.destroy) self.regions = regions self.tl_x = tl_x self.tl_y = tl_y self.width = width self.height = height self.canvas = Canvas(self.top, width=self.width, height=self.height, background=background) self.canvas.pack() # self.center() self.move_frame(self.tl_x, self.tl_y) self.dist_to_pixel = (self.width - 2 * PIXEL_BUFFER) / get_width( regions[GROUND]) # Maintains aspect ratio self.dist_width = self.width / self.dist_to_pixel self.dist_height = self.height / self.dist_to_pixel self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT self.robot_dist = self.dist_height / 2. self.robot = [] self.blocks = [] self.holding = None self.environment = [] self.draw_environment() def center(self): 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 self.top.geometry("%dx%d+%d+%d" % (size + (x, y))) def move_frame(self, x, y): self.top.update_idletasks() size = tuple( int(_) for _ in self.top.geometry().split('+')[0].split('x')) self.top.geometry("%dx%d+%d+%d" % (size + (x, y))) def scale_x(self, x): # x \in [-self.dist_width/2, self.dist_width/2] return self.dist_to_pixel * (x + self.dist_width / 2.) def scale_y(self, y): # y \in [0, self.dist_height] return self.ground_height - self.dist_to_pixel * y def draw_block(self, x, width, height, color='blue'): self.blocks.append( self.canvas.create_rectangle(self.scale_x(x - width / 2.), self.scale_y(0), self.scale_x(x + width / 2.), self.scale_y(height), fill=color, outline='black', width=2)) # def draw_holding(self, x, width, height, color='blue'): # self.holding = self.canvas.create_rectangle(self.scale_x(x - width / 2.), # self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2 - height), # self.scale_x(x + width / 2.), # self.scale_y(self.robot_dist - SUCTION_HEIGHT / 2), # fill=color, outline='black', width=2) def draw_region(self, region, color='red'): x1, x2 = map(self.scale_x, region) self.environment.append( self.canvas.create_rectangle(x1, self.ground_height, x2, self.height, fill=color, outline='black', width=2)) def draw_environment(self, table_color='lightgrey'): self.environment = [] self.draw_region(self.regions[GROUND], color=table_color) for name, region in self.regions.items(): if name != GROUND: self.draw_region(region) def draw_robot( self, x, y, color='yellow' ): # TODO - could also visualize as top grasps instead of side grasps #y = self.robot_dist self.robot = [ self.canvas.create_rectangle(self.scale_x(x - SUCTION_WIDTH / 2.), self.scale_y(y - SUCTION_HEIGHT / 2.), self.scale_x(x + SUCTION_WIDTH / 2.), self.scale_y(y + SUCTION_HEIGHT / 2.), fill=color, outline='black', width=2), self.canvas.create_rectangle(self.scale_x(x - STEM_WIDTH / 2.), self.scale_y(y + SUCTION_HEIGHT / 2.), self.scale_x(x + STEM_WIDTH / 2.), self.scale_y(y + SUCTION_HEIGHT / 2. + STEM_HEIGHT), fill=color, outline='black', width=2), ] def clear_state(self): for block in self.blocks: self.canvas.delete(block) for part in self.robot: self.canvas.delete(part) if self.holding is not None: self.canvas.delete(self.holding) def clear_all(self): self.canvas.delete('all') def save(self, filename): # self.canvas.postscript(file='%s.ps'%filename, colormode='color') from PIL import ImageGrab ImageGrab.grab((0, 0, self.width, self.height)).save(filename + '.jpg')
class ContinuousTMPViewer(object): def __init__(self, env_region, regions=[], tl_x=0, tl_y=0, width=500, height=250, title='Grid', background='tan'): self.tk = Tk() self.tk.withdraw() self.top = Toplevel(self.tk) self.top.wm_title(title) self.top.protocol('WM_DELETE_WINDOW', self.top.destroy) self.env_region = env_region self.regions = regions self.tl_x = tl_x self.tl_y = tl_y self.width = width self.height = height self.canvas = Canvas(self.top, width=self.width, height=self.height, background=background) self.canvas.pack() self.move_frame(self.tl_x, self.tl_y) self.dist_to_pixel = (self.width - 2 * PIXEL_BUFFER) / (self.env_region.w) self.dist_width = self.width / self.dist_to_pixel self.dist_height = self.height / self.dist_to_pixel self.ground_height = self.height - self.dist_to_pixel * ENV_HEIGHT self.robot_dist = self.dist_height / 2. self.robot = [] self.blocks = [] self.holding = None self.draw_environment() def center(self): 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 self.top.geometry("%dx%d+%d+%d" % (size + (x, y))) def move_frame(self, x, y): self.top.update_idletasks() size = tuple( int(_) for _ in self.top.geometry().split('+')[0].split('x')) self.top.geometry("%dx%d+%d+%d" % (size + (x, y))) def t_x(self, x): return self.dist_to_pixel * (x + self.dist_width / 2.) def t_y(self, y): return self.ground_height - self.dist_to_pixel * y def draw_block(self, block, x): self.blocks.append( self.canvas.create_rectangle(self.t_x(x - block.w / 2.), self.t_y(0), self.t_x(x + block.w / 2.), self.t_y(block.h), fill=block.color, outline='black', width=2)) def draw_holding(self, block, x): self.holding = self.canvas.create_rectangle( self.t_x(x - block.w / 2.), self.t_y(self.robot_dist - SUCTION_HEIGHT / 2 - block.h), self.t_x(x + block.w / 2.), self.t_y(self.robot_dist - SUCTION_HEIGHT / 2), fill=block.color, outline='black', width=2) def draw_region(self, region): self.environment.append( self.canvas.create_rectangle(self.t_x(region.x - region.w / 2.), self.ground_height, self.t_x(region.x + region.w / 2.), self.height, fill='red', outline='black', width=2)) def draw_environment(self, table_color='lightgrey', bin_color='grey'): self.environment = [ self.canvas.create_rectangle(self.t_x(-self.env_region.w / 2), self.ground_height, self.t_x(self.env_region.w / 2), self.height, fill=table_color, outline='black', width=2) ] for region in self.regions: self.draw_region(region) def draw_robot(self, x, color='yellow'): self.robot = [ self.canvas.create_rectangle( self.t_x(x - SUCTION_WIDTH / 2.), self.t_y(self.robot_dist - SUCTION_HEIGHT / 2.), self.t_x(x + SUCTION_WIDTH / 2.), self.t_y(self.robot_dist + SUCTION_HEIGHT / 2.), fill=color, outline='black', width=2), self.canvas.create_rectangle( self.t_x(x - STEM_WIDTH / 2.), self.t_y(self.robot_dist + SUCTION_HEIGHT / 2.), self.t_x(x + STEM_WIDTH / 2.), self.t_y(self.robot_dist + SUCTION_HEIGHT / 2. + STEM_HEIGHT), fill=color, outline='black', width=2), ] def clear_state(self): for block in self.blocks: self.canvas.delete(block) for part in self.robot: self.canvas.delete(part) if self.holding is not None: self.canvas.delete(self.holding) def clear_all(self): self.canvas.delete('all') def save(self, filename): from PIL import ImageGrab ImageGrab.grab((0, 0, self.width, self.height)).save(filename + '.jpg')
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()
class FirmwareParms: def __init__(self, app, prtr, settings, log): self.app = app self.printer = prtr self.settings = settings self.log = log self.readingFirmware = False self.reportOnly = False self.top = None self.parameters = {} self.groups = {} groups = [] for s in FirmwareSettings: grp = s.split('_')[0] if grp not in groups: if grp not in grporder: print "Unknown group: %s" % grp else: groups.append(grp) g = self.groups[grp] = paramGroup(grp, grpinfo[grp][GRPLABEL]) else: g = self.groups[grp] p = self.parameters[s] = param(s, pinfo[s][PLABEL], eepVal = self.settings.firmware[s], width=pinfo[s][PWIDTH]) g.addParam(p) def isActive(self): return self.top != None def start(self, reportOnly=False): self.got92 = False self.got201 = False self.got203 = False self.got204 = False self.got205 = False self.got206 = False self.got301 = False self.reportOnly = reportOnly self.app.readingFirmware = True self.printer.send_now("M503") def checkComplete(self): if self.got92 and self.got201 and self.got203 and self.got204 and self.got204 and self.got206 and self.got301: self.app.readingFirmware = False; self.app.event_generate(MWM_FIRMWARECOMPLETE) return True else: return False def m92(self, x, y, z, e): self.parameters['m92_x'].setFlash(x) self.parameters['m92_y'].setFlash(y) self.parameters['m92_z'].setFlash(z) self.parameters['m92_e'].setFlash(e) self.got92 = True return self.checkComplete() def m201(self, x, y, z, e): self.parameters['m201_x'].setFlash(x) self.parameters['m201_y'].setFlash(y) self.parameters['m201_z'].setFlash(z) self.parameters['m201_e'].setFlash(e) self.got201 = True return self.checkComplete() def m203(self, x, y, z, e): self.parameters['m203_x'].setFlash(x) self.parameters['m203_y'].setFlash(y) self.parameters['m203_z'].setFlash(z) self.parameters['m203_e'].setFlash(e) self.got203 = True return self.checkComplete() def m204(self, s, t): self.parameters['m204_s'].setFlash(s) self.parameters['m204_t'].setFlash(t) self.got204 = True return self.checkComplete() def m205(self, s, t, b, x, z, e): self.parameters['m205_s'].setFlash(s) self.parameters['m205_t'].setFlash(t) self.parameters['m205_b'].setFlash(b) self.parameters['m205_x'].setFlash(x) self.parameters['m205_z'].setFlash(z) self.parameters['m205_e'].setFlash(e) self.got205 = True return self.checkComplete() def m206(self, x, y, z): self.parameters['m206_x'].setFlash(x) self.parameters['m206_y'].setFlash(y) self.parameters['m206_z'].setFlash(z) self.got206 = True return self.checkComplete() def m301(self, p, i, d): self.parameters['m301_p'].setFlash(p) self.parameters['m301_i'].setFlash(i) self.parameters['m301_d'].setFlash(d) self.got301 = True return self.checkComplete() def reportComplete(self): if self.reportOnly: return self.parameters if self.top != None: self.updateFlashDisplay() if self.readingFirmware: self.readingFirmware = False for s in FirmwareSettings: p = self.parameters[s] v = p.getFlash() p.setEEProm(v) self.settings.firmware[s] = v self.settings.setModified() self.updateEEPromDisplay() return None self.top = Toplevel(self.app) self.top.protocol('WM_DELETE_WINDOW', self.delTop) self.top.title("Firmware Parameters") gf = LabelFrame(self.top, text="") gf.grid(row=1, column=1, rowspan=len(grporder), padx=10, pady=10, sticky=N+S+E+W) l = Label(gf, text="Profiles:") l.grid(row=1, column=1, columnspan=2, pady=10) self.profList = Listbox(gf) self.profList.grid(row=2, column=1, columnspan=2, sticky=N+S+E+W) self.yScroll = Scrollbar (gf, orient=VERTICAL) self.yScroll.grid (row=2, column=3, sticky=N+S) self.profList.config(yscrollcommand=self.yScroll.set) self.yScroll.config(command=self.profList.yview) self.profList.bind('<ButtonRelease-1>', self.profSel) l = Label(gf, text=" ") l.grid(row=3, column=1, columnspan=2, pady=10) l = Label(gf, text="New Profile Name") l.grid(row=4, column=1, columnspan=2) self.newProf = Entry(gf, width=12) self.newProf.grid(row=5, column=1, columnspan=2) self.cbOWrite = IntVar() self.cbOverWrite = Checkbutton(gf, text="Over-Write", variable=self.cbOWrite) self.cbOverWrite.grid(row=6, column=1, sticky=W) self.bSave = Button(gf, width=12, text="Save", command = self.doSave) self.bSave.grid(row=6, column=2) l = Label(gf, text=" ") l.grid(row=7, column=1, columnspan=2, pady=10) self.cbCDel = IntVar() self.cbConfirmDelete = Checkbutton(gf, text="Delete", variable=self.cbCDel, command=self.cbDoConfirmDelete, state=DISABLED) self.cbConfirmDelete.grid(row=8, column=1, sticky=W) self.bDel = Button(gf, width=12, text="Delete", command = self.doDelete, state=DISABLED) self.bDel.grid(row=8, column=2) gf = LabelFrame(self.top, text="") gf.grid(row=len(grporder)+1, column=1, sticky=N+S+E+W, padx=10) self.bToEEProm = Button(gf, text='Copy Flash -> EEPROM', command=self.doFlashToEEProm, width = 20) self.bToEEProm.place(relx=0.5, rely=0.5, y=-20, anchor=CENTER) self.bFromEEProm = Button(gf, text='Copy EEPROM -> Flash', command=self.doEEPromToFlash, width = 20) self.bFromEEProm.place(relx=0.5, rely=0.5, y=20, anchor=CENTER) self.entryWidgets = {} self.buttons = {} self.allButtons = {} self.flashWidgets = {} self.eepromWidgets = {} f = Frame(self.top) f.grid(row=1, column=2, columnspan=4, sticky=N+W+E+W) t = Label(f, text="Flash EEProm", width=68, anchor=E) t.grid(row=1, column=1, sticky=E) Row = 2 for g in grporder: glf = LabelFrame(self.top, text=self.groups[g].getLabel(), width=10, height=10) glf.grid(row=Row, column = 2, columnspan=4, sticky=N+W+E+S) gRow = 1 for p in self.groups[g]: t = Label(glf, text=p.getLabel(), width=18, anchor=E) t.grid(row=gRow, column=1) w = self.entryWidgets[p.getTag()] = Entry(glf, width=10, justify=RIGHT) w.grid(row=gRow, column=2) w = self.buttons[p.getTag()] = Button(glf, text="->", width=2, height=1, command=lambda prm=p: self.profButton(prm)) w.grid(row=gRow, column=3) l = Label(glf, text=p.displayFlash(), width=14, anchor=E) l.grid(row=gRow, column=5) self.flashWidgets[p.getTag()] = l l = Label(glf, text=p.displayEEProm(), width=14, anchor=E) l.grid(row=gRow, column=6) self.eepromWidgets[p.getTag()] = l gRow += 1 w = self.allButtons[g] = Button(glf, text="All\n->", command=lambda prm=g: self.allButton(self.groups[prm])) w.grid(row=1, column=4, rowspan=gRow-1, sticky=N+E+W+S) Row += 1 self.loadProfiles() self.top.geometry("850x920+50+50") return None def loadProfiles(self, name=None): self.profList.delete(0, END) self.profList.insert(END, EMPTY) self.profiles = self.settings.getProfiles() match = 0 px = 1 for pn in self.profiles: self.profList.insert(END, pn) if pn == name: match = px px += 1 self.profList.selection_set(match) self.profSel() def cbDoConfirmDelete(self): if self.cbCDel.get() == 1: self.bDel.config(state=NORMAL) else: self.bDel.config(state=DISABLED) def doDelete(self): try: item = int(self.profList.curselection()[0]) except: item = 0 if item == 0: return prof = self.profiles[item-1] self.settings.delProfile(prof) self.loadProfiles() def profSel(self, *arg): try: item = int(self.profList.curselection()[0]) except: item = 0 if item == 0: self.cbConfirmDelete.config(state=DISABLED) self.bDel.config(state=DISABLED) for s in FirmwareSettings: p = self.parameters[s] p.setProf(None) else: self.cbConfirmDelete.config(state=NORMAL) self.cbCDel.set(0) prof = self.profiles[item-1] po = self.settings.getProfile(prof) for s in FirmwareSettings: p = self.parameters[s] p.setProf(po.getAttrib(s)) self.updateProfDisplay() def doSave(self): np = self.newProf.get().strip() if np == "": showerror("Write Error", "New Profile name required", parent=self.top) return if np in self.profiles and self.cbOWrite.get() == 0: showerror("Write Error", "Must check over-write for an existing profile", parent=self.top) return p = self.settings.getProfile(np) newProf = False if p == None: p = self.settings.addProfile(np) newProf = True for s in FirmwareSettings: val = self.entryWidgets[s].get() if self.valueValid(val): p.setAttrib(s, float(val)) else: p.delAttrib(s) if newProf: self.loadProfiles(p.getName()) def doFlashToEEProm(self): for s in FirmwareSettings: p = self.parameters[s] v = p.getFlash() p.setEEProm(v) self.settings.firmware[s] = v self.eepromWidgets[s].config(text=self.parameters[s].displayEEProm()) self.settings.setModified() self.log.logMsg("Committing to EEProm") self.printer.send_now("M500") def updateFlashDisplay(self): for s in FirmwareSettings: self.flashWidgets[s].config(text=self.parameters[s].displayFlash()) def updateEEPromDisplay(self): for s in FirmwareSettings: self.eepromWidgets[s].config(text=self.parameters[s].displayEEProm()) def updateProfDisplay(self): for s in FirmwareSettings: self.entryWidgets[s].delete(0, END) self.entryWidgets[s].insert(0, self.parameters[s].displayProf()) def doEEPromToFlash(self): self.readingFirmware = True self.got92 = False self.got201 = False self.got203 = False self.got204 = False self.got205 = False self.got206 = False self.got301 = False self.app.readingFirmware = True self.printer.send_now("M501") def valueValid(self, v): if v == None: return False if v == "": return False try: vf = float(v) return True except: return False def profButton(self, p): ptag = p.getTag() cmd, pn = ptag.split('_') val = self.entryWidgets[ptag].get() if self.valueValid(val): vf = float(val) self.parameters[ptag].setFlash(vf) dspv = self.parameters[ptag].displayFlash().strip() self.flashWidgets[ptag].config(text=dspv) self.printer.send_now("%s %s%s" % (cmd.upper(), pn.upper(), dspv)) self.log.logMsg("setting %s - %s to %s" % (self.groups[cmd].getLabel(), self.parameters[ptag].getLabel(), dspv)) else: self.log.logMsg("Bad parameter value") def allButton(self, g): gtag = g.getTag() cmd = gtag.upper() hasParams = False for p in self.groups[gtag]: ptag = p.getTag() pn = p.tag.split('_')[1] val = self.entryWidgets[ptag].get() if self.valueValid(val): hasParams = True vf = float(val) self.parameters[ptag].setFlash(vf) dspv = self.parameters[ptag].displayFlash().strip() self.flashWidgets[ptag].config(text=dspv) self.log.logMsg("setting %s - %s to %s" % (self.groups[gtag].getLabel(), self.parameters[ptag].getLabel(), dspv)) cmd += " %s%s" % (pn.upper(), dspv) else: self.log.logMsg("Bad parameter value: %s" % self.parameters[ptag].getLabel()) if hasParams: self.printer.send_now(cmd) else: self.log.logMsg("No parameters entered") def delTop(self): self.top.destroy() self.top = None
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()
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)
class GUIHandler: screenwidth = 0 screenheight = 0 windowwidth = 0 windowheight = 0 ## Initializes the GUI setup of the program. # def __init__(self,game): assert type(game) is Game self.root = Tk() self.root.title('SET') self.root.resizable(0,0) self.root.withdraw() GUIHandler.screenwidth = self.root.winfo_screenwidth() GUIHandler.screenheight = self.root.winfo_screenheight() if GUIHandler.screenwidth < 1024 or GUIHandler.screenheight < 768: showerror("Resolution Error","Your screen's resolution is likely not the best choice to run this game. Minimum resolution for this game is at least 1024x768.") raise ResolutionError(GUIHandler.screenwidth,GUIHandler.screenheight) GUIHandler.windowwidth = GUIHandler.screenwidth // 3 GUIHandler.windowheight = GUIHandler.screenheight // 1.5 self.buttonField = None self.checkButtonField = None self.Game = game self.Field = game.field assert self.Game assert self.Field self.root.geometry('%dx%d+%d+%d' % (GUIHandler.windowwidth, GUIHandler.windowheight, self.root.winfo_screenwidth()/8, self.root.winfo_screenheight()/8)) menu = Menu(self.root) gamemenu = Menu(menu,tearoff=0) gamemenu.add_command(label='New Game',command=lambda:self.startNewGame(),accelerator="F2") gamemenu.add_command(label='Leaderboards',command=lambda:showinfo("Not implemented","Feature not implemented...yet.")) gamemenu.add_command(label='Exit',command=lambda:self.root.destroy(),accelerator="Alt-F4") menu.add_cascade(label='Game',menu=gamemenu) settingmenu = Menu(menu,tearoff=0) gamedifficulty = Menu(settingmenu,tearoff=0) gamedifficulty.add_radiobutton(label='Beginner',command=lambda :self.changeGameDifficulty(Difficulty.BEGINNER),accelerator="B") gamedifficulty.add_radiobutton(label='Novice',command=lambda :self.changeGameDifficulty(Difficulty.NOVICE),accelerator="N") gamedifficulty.add_radiobutton(label='Advanced',command=lambda :self.changeGameDifficulty(Difficulty.ADVANCED),accelerator="A") settingmenu.add_cascade(label='Game Difficulty',menu=gamedifficulty) timedmode = Menu(settingmenu,tearoff=0) timedmode.add_radiobutton(label='On',command=lambda:showinfo("Not implemented","Feature not implemented...yet.")) timedmode.add_radiobutton(label='Off',command=lambda:showinfo("Not implemented","Feature not implemented...yet.")) settingmenu.add_cascade(label='Timed Mode',menu=timedmode) timeddifficulty = Menu(settingmenu,tearoff=0) timeddifficulty.add_radiobutton(label='Easy',accelerator="E") timeddifficulty.add_radiobutton(label='Medium',accelerator="M") timeddifficulty.add_radiobutton(label='Hard',accelerator="H") settingmenu.add_cascade(label='Timed Difficulty',menu=timeddifficulty) menu.add_cascade(label='Settings',menu=settingmenu) helpmenu = Menu(menu,tearoff=0) helpmenu.add_command(label='About SET',command=lambda:showinfo("Not implemented","Feature not implemented...yet.")) menu.add_cascade(label='Help',menu=helpmenu) self.root.config(menu=menu) self.root.bind('<F2>',lambda e:gamemenu.invoke(0)) self.root.bind('L',lambda e:gamemenu.invoke(1)) self.root.bind('<Alt-F4>',lambda e:gamemenu.invoke(2)) self.root.bind('b',lambda e:gamedifficulty.invoke(Difficulty.BEGINNER)) self.root.bind('n',lambda e:gamedifficulty.invoke(Difficulty.NOVICE)) self.root.bind('a',lambda e:gamedifficulty.invoke(Difficulty.ADVANCED)) self.remainderLabel = Label(self.root,text="There are %d set(s) remaining on the board." % self.Game.numSetsRemaining(),bg="white",relief=Tkinter.RAISED,font=('Helvetica',12)) self.remainderLabel.place(x=(GUIHandler.windowwidth-self.remainderLabel.winfo_reqwidth())//2,y=3*GUIHandler.windowheight//4) timer = Label(self.root,text="Untimed Mode",bg="green",relief=Tkinter.RAISED,font=('Helvetica',12)) timer.place(x=(GUIHandler.windowwidth-timer.winfo_reqwidth())//2,y=3*GUIHandler.windowheight//4.5) hintbutton = Button(text="Hint, please!",font=("Helvetica",12),command=lambda :self.getHint()) hintbutton.place(x=(GUIHandler.windowwidth-hintbutton.winfo_reqwidth())//2,y=3*GUIHandler.windowheight//3.5) self.userSetsCreated = Toplevel(self.root) self.userSetsHeight = 0 self.userSetsCreated.title("Sets Created") self.userSetsCreated.geometry("%dx%d+%d+%d" % (Card.pixelWidth*3, self.userSetsCreated.winfo_screenheight(), self.root.winfo_pointerx()+self.userSetsCreated.winfo_reqwidth(),0)) self.userSetsCreated.protocol("WM_DELETE_WINDOW",0) self.userSetsCreated.resizable(0,0) self.root.focus_set() self.updateCardsOnField(self.Field) ## Process the card location that the user picked. The function calls the game instance's addCardChoice method # to get a callback on the result of adding the card choice. def processCardChoice(self,i): cbutton = self.checkButtonField[i//self.Field.cols()][i%self.Field.cols()] cbutton.select() result = self.Game.addCardChoice(i) if result == 3: cbutton.deselect() return elif not result: return if result == 2: #Case 1: 3 choices were made and the Game object verified them as a set. showinfo("Good Job!","You made a set!") self.remainderLabel.config(text="There are %d set(s) remaining on the board." % self.Game.numSetsRemaining()) x = 0 for h in map(Card.getCardImgNumber,[self.Field[i//self.Field.cols()][i%self.Field.cols()] for i in self.Game.setsMadeSoFar[-1]]): pic = PhotoImage(file='../media/%d.gif'%h) label = Label(self.userSetsCreated,image=pic) label.image = pic label.place(x=x,y=self.userSetsHeight) x+=Card.pixelWidth self.userSetsHeight+=Card.pixelHeight if not self.Game.numSetsRemaining(): showinfo("WINNER!","Congratulations! You found all sets!") self.disableButtons() elif result == 1: #Case 2: 3 choices were made but the user has made this set before in the game. showinfo("Repeat","You've already made this set") elif type(result) == tuple: #Case #3: 3 choices were made but they didn't form a set. assert len(result) == 2 showinfo("Not a set","Not a set because 2 are %s and 1 is %s" % (result[0],result[1])) for i in self.checkButtonField: for j in i: j.deselect() def disableButtons(self): for i in self.buttonField: for j in i: j.config(state=Tkinter.DISABLED) for i in self.checkButtonField: for j in i: j.config(state=Tkinter.DISABLED) #Hard Coded lists of button widgets because python won't let me generate each of the Button's command #feature correctly via list comprehension. def setupNoviceField(self): self._destroyAllButtons() if self.buttonField else None self.buttonField = [[Button(self.root,command=lambda :self.processCardChoice(0)), Button(self.root,command=lambda :self.processCardChoice(1)), Button(self.root,command=lambda :self.processCardChoice(2))], [Button(self.root,command=lambda :self.processCardChoice(3)), Button(self.root,command=lambda :self.processCardChoice(4)), Button(self.root,command=lambda :self.processCardChoice(5))], [Button(self.root,command=lambda :self.processCardChoice(6)), Button(self.root,command=lambda :self.processCardChoice(7)), Button(self.root,command=lambda :self.processCardChoice(8))]] self.checkButtonField = [[Checkbutton(self.root,text='1',command=lambda :self.processCardChoice(0)), Checkbutton(self.root,text='2',command=lambda :self.processCardChoice(1)), Checkbutton(self.root,text='3',command=lambda :self.processCardChoice(2))], [Checkbutton(self.root,text='4',command=lambda :self.processCardChoice(3)), Checkbutton(self.root,text='5',command=lambda :self.processCardChoice(4)), Checkbutton(self.root,text='6',command=lambda :self.processCardChoice(5))], [Checkbutton(self.root,text='7',command=lambda :self.processCardChoice(6)), Checkbutton(self.root,text='8',command=lambda :self.processCardChoice(7)), Checkbutton(self.root,text='9',command=lambda :self.processCardChoice(8))]] #See the comment above setup Novice _Field. def setupAdvancedField(self): self._destroyAllButtons() if self.buttonField else None self.buttonField = [[Button(self.root,command=lambda :self.processCardChoice(0)), Button(self.root,command=lambda :self.processCardChoice(1)), Button(self.root,command=lambda :self.processCardChoice(2)), Button(self.root,command=lambda :self.processCardChoice(3))], [Button(self.root,command=lambda :self.processCardChoice(4)), Button(self.root,command=lambda :self.processCardChoice(5)), Button(self.root,command=lambda :self.processCardChoice(6)), Button(self.root,command=lambda :self.processCardChoice(7))], [Button(self.root,command=lambda :self.processCardChoice(8)), Button(self.root,command=lambda :self.processCardChoice(9)), Button(self.root,command=lambda :self.processCardChoice(10)), Button(self.root,command=lambda :self.processCardChoice(11))]] self.checkButtonField = [[Checkbutton(self.root,text='1',command=lambda :self.processCardChoice(0)), Checkbutton(self.root,text='2',command=lambda :self.processCardChoice(1)), Checkbutton(self.root,text='3',command=lambda :self.processCardChoice(2)), Checkbutton(self.root,text='4',command=lambda :self.processCardChoice(3))], [Checkbutton(self.root,text='5',command=lambda :self.processCardChoice(4)), Checkbutton(self.root,text='6',command=lambda :self.processCardChoice(5)), Checkbutton(self.root,text='7',command=lambda :self.processCardChoice(6)), Checkbutton(self.root,text='8',command=lambda :self.processCardChoice(7))], [Checkbutton(self.root,text='9',command=lambda :self.processCardChoice(8)), Checkbutton(self.root,text='10',command=lambda :self.processCardChoice(9)), Checkbutton(self.root,text='11',command=lambda :self.processCardChoice(10)), Checkbutton(self.root,text='12',command=lambda :self.processCardChoice(11))]] def updateCardsOnField(self,cardField): rows = cardField.rows() cols = cardField.cols() if cols == 3: self.setupNoviceField() elif cols == 4: self.setupAdvancedField() else: raise IndexError("CardField argument has illegal number of columns") assert len(self.buttonField) == rows assert len(self.buttonField[0]) == cols spacing = (GUIHandler.windowwidth-(cols * Card.pixelWidth) - 5) / (cols-1) x,y = 0,0 cbwidth = self.checkButtonField[0][0].winfo_reqwidth() for i in xrange(rows): for j in xrange(cols): pic = PhotoImage(file='../media/%s.gif' % str(cardField[i][j].getCardImgNumber())) self.buttonField[i][j].config(image=pic) self.buttonField[i][j].image = pic self.buttonField[i][j].place(x=x,y=y) self.checkButtonField[i][j].place(x=x + Card.pixelWidth//2 - cbwidth//4,y=(y+Card.pixelHeight+10)) x += Card.pixelWidth + spacing y += Card.pixelHeight + 40 x = 0 def startNewGame(self): self.userSetsHeight = 0 [i.destroy() for i in self.userSetsCreated.children.values()] self.Game.resetGame() self.updateCardsOnField(self.Game.field) self.remainderLabel.config(text="There are %d set(s) remaining on the board." % self.Game.numSetsTotal) #print map(lambda ls:map(lambda x:x+1,ls),self.Game.setsListTotal) def _destroyAllButtons(self): for i in self.buttonField: for j in i: j.destroy() for i in self.checkButtonField: for j in i: j.destroy() def changeGameDifficulty(self,difficulty): if self.Game.changeGameDifficulty(difficulty): self.startNewGame() def getHint(self): result = self.Game.callHint() if result == -3: showinfo("One set remains","You cannot use hints in finding the last set.") elif result == -2: showinfo("Game's over","Game has ended. Start a new game if you wish.") elif result == -1: showinfo("No more hints","Sorry. You are out of hints to spare.") else: showinfo("Your Hint","Pick Card #%d"%(result+1)) def run(self): self.root.deiconify() self.root.mainloop()
def set_buffer(self): window = Toplevel(self, bg='#C1CDCD') window.title('set_buffer_size') window.geometry('400x300') window.resizable(0, 0) # 禁止调整窗口大小 window.protocol("WM_DELETE_WINDOW", self.close) buffer_num = 10 var = [] for i in range(buffer_num): var.append(StringVar()) Label(window, text=u"请填写输入/输出块大小,单位k(无需填满),代表每次读/写多少kb", bg='#C1CDCD').grid(row=0, column=0, columnspan=4, pady=5, padx=15) for j in range(buffer_num / 2): Label(window, text=u"buffer_size " + str(j * 2) + ":", bg='#C1CDCD').grid(row=j + 1, column=0, pady=8, padx=10) Entry(window, width=10, textvariable=var[j * 2]).grid(row=j + 1, column=1, pady=8, padx=10) Label(window, text=u"buffer_size " + str(j * 2 + 1) + ":", bg='#C1CDCD').grid(row=j + 1, column=2, pady=8, padx=10) Entry(window, width=10, textvariable=var[j * 2 + 1]).grid(row=j + 1, column=3, pady=8, padx=10) def get_buffer_list(): v4 = '' self.buffer_list[:] = [] for k in range(buffer_num): v = var[k].get() if v == '' or v.isspace() or not v.isdigit(): continue else: self.buffer_list.append(int(v)) self.buffer_list = list(set(self.buffer_list)) if 0 in self.buffer_list: self.buffer_list.remove(0) self.buffer_list.sort() for size in self.buffer_list: v4 = v4 + str(size) + 'k' + ',' print v4 self.v4.set(v4) window.destroy() Button(window, text=u"确定", width=20, command=get_buffer_list, bg='#C1CDCD').grid(row=buffer_num / 2 + 2, column=0, columnspan=4, pady=8, padx=10) window.protocol("WM_DELETE_WINDOW", window.destroy)