def goto_date_gui(self): date_top = Toplevel() date_top.title("Enter date") date_top.resizable(0, 0) # Inputs for month/year goto_month = Label(date_top, text="Month:") goto_month.grid(row=0, column=0) m_entry = Entry(date_top) m_entry.grid(row=0, column=1) goto_year = Label(date_top, text="Year:") goto_year.grid(row=1, column=0) y_entry = Entry(date_top) y_entry.grid(row=1, column=1) def month_jump(): try: month = int(m_entry.get()) year = int(y_entry.get()) if 0 < month <= 12 and 1970 <= year < 5000: self.calendar.month = month - 1 self.calendar.year = year self.update_calendar() except: pass submit = Button(date_top, text="Submit", command=month_jump) submit.grid(column=0, columnspan=3)
def instructions(self): """Open instructions window.""" # Instantiates separate Toplevel instruction window. instr_window = Toplevel(self.root) instr_window.geometry('550x575+25+25') instr_window.title('Instructions') instr_window.wm_iconbitmap(constants.ICO) instr_window.resizable(False, False) # Creatse Scrollbar and Frame for containing other widgets. instr_scroll = Scrollbar(instr_window) instr_scroll.pack(fill=Y, side="right") instr_frame = Frame(instr_window, bg='white') instr_frame.pack(fill=BOTH, side="left") # Adds instruction text from constants and adds image of Cinzano's diagram. instr = Text(instr_frame, width=65, height=40, padx=10, pady=5, bd=0, wrap="word") instr.insert("end", constants.INSTR) cdiagram_file = Image.open("./static/cinzano_diagram.PNG") cdiagram_file = cdiagram_file.resize((500, 450), Image.ANTIALIAS) self.cdiag = ImageTk.PhotoImage(cdiagram_file) instr.image_create("end", image=self.cdiag) instr.tag_add("top", "1.0", "4.10") instr.tag_config("top", font='Times 12 bold') instr.tag_add("body", "5.0", "19.20") instr.tag_config("body", font='Times 12') instr.insert("end", constants.CDIAG) instr.pack() instr_scroll.config(command=instr.yview)
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 new_pop_up(title_string, message_string): ''' Defines a new top level window for a quick message to the user ''' popup = Toplevel() popup.title(title_string) popup.minsize(250, 20) popup.resizable(False, False) Message(popup, text=message_string, width=250).pack() Button(popup, text="Dismiss", command=popup.destroy).pack()
def callHelpdWindow(): textvar='K-TAIL State Transition Software\nVersion:1.0\nAuthor:Lenz L Nerit\University:Victoria University of Wellington\n' helpWind=Toplevel() helpWind.resizable(width=FALSE, height=FALSE) frame=ttk.Frame(helpWind) frm=LabelFrame(frame,text='test') frm.pack() lbl=Label(frm,text="sampleStatus",width=10,bg='blue') lbl.pack(fill=BOTH) helpWind.mainloop()
def show_about(): t = Toplevel(master) t.title("About") t.transient(master) t.resizable(False, False) Label(t, image=self.img_logo).grid(column=0, row=0, sticky=(E, W)) Label(t, text="Context %s" % VERSION, anchor=CENTER).grid(column=0, row=1, sticky=(E, W)) Label(t, text="(c) 2011-2014 Shish", anchor=CENTER).grid(column=0, row=2, sticky=(E, W)) Button(t, text="Close", command=t.destroy).grid(column=0, row=3, sticky=(E,)) win_center(t)
def no_acc(): global win2, habusrenr win2 = Toplevel(root) win2.geometry('250x50') win2.iconbitmap('Logo.ico') win2.resizable(width=FALSE, height=FALSE) win2.title("Support") habusrlab = Label(win2, text="Full Name") habusrenr = Entry(win2) habusrbtt = Button(win2, text="Send", command=send_acc_req) habusrlab.grid(column=0, row=0) habusrenr.grid(column=1, row=0) habusrbtt.place(relx=0.6, x=1, y=22.5, anchor=NE)
def 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
def getDlg(root, title): """Create a dialog Arguments root -- dialog parent title -- dialog title """ dlg = Toplevel(root) dlg.title(title) dlg.root = root dlg.grab_set() dlg.transient(root) dlg.resizable(False, False) return dlg
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 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 about(self): """Open an about window. Window gives authors, SET version number, and icon credit. """ # Instantiates a new Toplevel about window. about_window = Toplevel(self.root) about_window.geometry('350x335+25+25') about_window.title('About') about_window.wm_iconbitmap(constants.ICO) about_window.resizable(False, False) # Adds text to about window. about = Text(about_window, width=50, height=30, padx=10, pady=3) about.insert("end", constants.ABOUT) about.tag_add("abt", "1.0", "21.30") about.tag_config("abt", font='Times 10 bold', justify=CENTER) about.pack()
def edit_admin_username(): admin = manentry.get() sqlq = "SELECT COUNT(1) FROM db_ADMINS WHERE username = '******'" % (admin) cursor.execute(sqlq) if cursor.fetchone()[0]: global uschentry, win2 win2 = Toplevel(root) win2.resizable(width=FALSE, height=FALSE) win2.title("Username change") uschlabel = Label(win2, text="New username") uschentry = Entry(win2) uschbutto = Button(win2, text="Change", command=change_username) uschlabel.pack() uschentry.pack() uschbutto.pack() else: tkMessageBox.showerror("Error", "Invalid username.") cnx.commit()
def about_info_gui(self): """ Opens window for information about application """ info_top = Toplevel() info_top.title("About") info_top.resizable(0, 0) about = Label(info_top, text="About the application") about.grid() dev_text = Label(info_top, text="Developer: Paul Cowie") dev_text.grid() date_text = Label(info_top, text=u"\u00a9 Paul Cowie 2014") date_text.grid() submit = Button(info_top, text="Ok", command=info_top.destroy) submit.grid(column=0, columnspan=3)
def reset_holidays_gui(self): confirm_top = Toplevel() confirm_top.title("Are you sure you wish to continue?") confirm_top.resizable(0, 0) # Warning to user warning_label = Label(confirm_top, text="WARNING: This will remove all holidays from the application\nAre you sure you wish to continue?") warning_label.grid() buttons = Frame(confirm_top) ok_button = Button(buttons, text="OK", command=lambda: [self.reset(), confirm_top.destroy()]) ok_button.grid(row=0, column=1) cancel_button = Button(buttons, text="Cancel", command=confirm_top.destroy) cancel_button.grid(row=0, column=0) buttons.grid(row=1)
def transitionSelection(tracelog,*args): # start of child window GUI code root = Toplevel() root.title("Manual Transition selection") root.resizable(width=FALSE, height=FALSE) # frame mainFrame = ttk.Frame(root, width="364", padding="4 4 8 8") mainFrame.grid(column=0, row=0) labelSource=ttk.Label(mainFrame,text="Source", justify=LEFT) labelSource.grid(column=0, row=0, sticky="e") srcState = ttk.Combobox(mainFrame,width=10) srcState.delete(0, END) srcState['values'] = ([k for k in tracelog]) srcState.grid(column=1, row=0, sticky="e") srcState.state(['readonly']) # Destination label labelDestination=ttk.Label(mainFrame,text="Destination",justify=LEFT) labelDestination.grid(column=0, row=1, sticky="e") # destination combobox destState = ttk.Combobox(mainFrame,width=10) destState.delete(0, END) destState['values'] = ([get_num(k) for k in tracelog]) destState.grid(column=1, row=1, sticky="e") destState.state(['readonly']) listFrame=ttk.LabelFrame(root) listFrame.grid(column=0,row=2,sticky="we") scrollBar = Scrollbar(listFrame) scrollBar.pack(side=RIGHT, fill=Y) listBoxTop = Listbox(listFrame, selectmode=SINGLE,width=20,height=10) listBoxTop.pack(fill=BOTH) scrollBar.config(command=listBoxTop.yview) listBoxTop.config(yscrollcommand=scrollBar.set) def addItemsToList(): if len(srcState.get())==0: tkMessageBox.showerror("No Source Entry","Please select a source state first") root.focus() return else: st=get_apha(srcState.get()) set_listTop(listBoxTop,str(get_num(srcState.get())) +'-->'+ str(destState.get()) + '[label='+st+']') manualMappingList.append(str(get_num(srcState.get())) +'-->'+ str(destState.get())) transitionDict[get_num(srcState.get())]=st generateFSMGraph() def removeMapFromList(): try: if len(listBoxTop.get(0, END))==0 or listBoxTop.curselection() is None: tkMessageBox.showerror("Empty List", "The mapping list is empty") return else: selection=listBoxTop.curselection() value = listBoxTop.get(selection[0]) ch='' for c in value: if c=='[': #Strip out characters after the symbol [ break else: ch +=c #when we remove an entry from the listbox, we also update the manual mapping list manualMappingList.remove(ch) listBoxTop.delete(selection) #remove the selected entry from listbox generateFSMGraph() transitionDict={} #reset the transition dictionary to capture updated entries from the listBox except (IndexError,AttributeError,ValueError): tkMessageBox.showerror("Error", "Please select an entry if exists or try again") def generateFSMGraph(): if len(listBoxTop.get(0, END))==0: tkMessageBox.showerror("No entry","There is no mapping entry.Please add mapping entry first") return try: for e in transitionDict: print transitionDict[e] stateMap1[int(e)]={} for m in manualMappingList: st=[int(s) for s in m.split('-->') if s.isdigit()] #extract digits in a mapping entry if str(e)==str(st[0]) and str(e)==str(st[1]): stateMap1[int(e)][int(st[0])]=transitionDict[e] elif str(e)!=str(st[1]) and str(e)==str(st[0]): stateMap1[int(e)][int(st[1])]=transitionDict[e] #callback functions drawStateTransitionGraph() loadFSMImage() except (ValueError,IndexError,GraphvizError,AttributeError): pass def closeWindowTop(): root.destroy() #Add a button inside the tab btnAdd=ttk.Button(mainFrame,text="Add",width=10,command=addItemsToList) btnAdd.grid(column=2,row=0) btnRemove=ttk.Button(mainFrame,text="Remove",width=10,command=removeMapFromList) btnRemove.grid(column=2,row=1) #Add frame to hold buttons btnFrame=ttk.LabelFrame(root) btnFrame.grid(column=0,row=3,sticky="we") btnCancel=ttk.Button(btnFrame,text="Close",width=13,command=closeWindowTop) btnCancel.pack(side=RIGHT,fill=X) btnOk=ttk.Button(btnFrame,text="Generate FSM",width=13,command=generateFSMGraph) btnOk.pack(side=RIGHT, fill=X) def set_listTop(Listbox,sMap): try: index=Listbox.curselection()[0] #Check if there is an existing entry in the listbox except IndexError: index=END for i,listbox_entry in enumerate(Listbox.get(0, END)): if listbox_entry == sMap: tkMessageBox.showinfo("Entry", "There is already an entry for this transition.") return Listbox.insert(index, sMap) def drawStateTransitionGraph(): #Here we appy the state transitions to create a finite state machine ktail = FiniteStateMachine('K-TAIL') for nx,kvx in stateMap1.items(): for c in kvx: State(nx).update({kvx[c]:State(c)}) print 'State Transition: ' +str(nx) + '-->'+str(c) + '[label='+kvx[c] +']' #Define initial state if nx==0: nx=State(0, initial=True) #Create a state machine print '------------------------------------------------------------------------------------' #Check if there is existing graph data try: graph=get_graph(ktail) if graph!=None: graph.draw('../graph/ktail.png', prog='dot') print graph else: pass except GraphvizError: tkMessageBox.ERROR # padding for widgets for child in mainFrame.winfo_children(): child.grid_configure(padx=4, pady=4) root.mainloop()
def Delete_click(root, Listbox): if (Listbox.curselection() != ()): root.grab_release() print("Delete click") popup = Toplevel() popup.resizable(False, False) popup.geometry("200x100+700+300") popup.grab_set() def Cancle(): popup.grab_release() root.grab_set() popup.destroy() def OK(Listbox): print('feature_support.OK_click') newrow = [] selected = Listbox.get(ACTIVE) os.remove("./data/%s.mp3" % selected.split(' ----- ')[1]) for line in fileinput.input("./data/database.csv", inplace=True): if line == '\n': continue if int(line[0]) < int(selected[0]): print line, if int(line[0]) > int(selected[0]): newline = line.split() newline[0] = str(int(newline[0]) - 1) print " ".join(newline) print '\n', fileinput.close() with open('./data/list_person.txt', 'rb') as lpfile: row_count = sum(1 for row in lpfile) os.remove('./model/net%d.xml' % int(selected[0])) if (row_count > 1) or (int(selected[0]) != row_count): for i in range(int(selected[0]) + 1, row_count + 1): os.rename('./model/net%d.xml' % i, './model/net%d.xml' % (i - 1)) with open('./data/list_person.txt', 'rb') as lpfile: for row in lpfile: if (row != []): row = row.split() if (int(row[0]) < int(selected[0])): newrow.append(row) if (int(row[0]) > int(selected[0])): row[0] = int(row[0]) - 1 newrow.append(row) Listbox.delete(0, END) with open('./data/list_person.txt', 'wb') as lpfile: i = 0 for row in newrow: Listbox.insert(i, "%d ----- %s" % (int(row[0]), row[1])) lpfile.write("%s %s\n" % (row[0], row[1])) i += 1 NeuralNetwork.remove_model(int(selected[0])) popup.destroy() root.grab_set() popup.wm_title("Delete") l1 = Label(popup, text="Bạn có muốn xóa !") b1 = Button(popup, text="OK", width=7, command=lambda: OK(Listbox)) b2 = Button(popup, text="Cancle", width=7, command=Cancle) l1.place(relx=0.25, rely=0.2) b1.place(relx=0.18, rely=0.6) b2.place(relx=0.52, rely=0.6) popup.mainloop() else: tkMessageBox.showinfo("Error", "Vui lòng chọn đối tượng")
def showAll(self): Ventana2 = Toplevel(self.master) try: Poss = [0, 50] maxi = self.buscMax() if int(maxi) < Poss[1]: Poss[1] = int(maxi) Ventana2.configure(height=45, width=25, bg="#4a4a4a") Ventana2.resizable(0, 0) frameAux = Frame(Ventana2, bg="#4a4a4a", borderwidth=0) frameAux.pack(fill=BOTH) scrolly = Scrollbar(frameAux, orient=VERTICAL) self.listbox1 = Listbox(frameAux, width=90, background="#4a4a4a", borderwidth=0, fg="#FFFFFF", highlightcolor="#4d86a1", highlightbackground="#4d86a1", yscrollcommand=scrolly.set) self.listbox1.config(font=("", 11)) self.listbox1.pack(side=LEFT) scrolly.pack(side=RIGHT, fill=Y) scrolly.configure(command=self.yview) self.load50(Poss) if sys.platform.startswith('win32'): ruta = "image\\GoBack.png" ruta2 = "image\\GoOn.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): ruta = "image/GoBack.png" ruta2 = "image/GoOn.png" load = Image.open(ruta) render = ImageTk.PhotoImage(load) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) backbutton1 = Button(Ventana2, image=render, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "-")) backbutton1.image = render backbutton1.pack(side=LEFT) backbutton2 = Button(Ventana2, image=render2, bg="#4a4a4a", borderwidth=0, activebackground="#4d86a1", highlightcolor="#4d86a1", highlightbackground="#4a4a4a", command=lambda: self.load50(Poss, "+")) backbutton2.image = render2 backbutton2.pack(side=LEFT) backbutton3 = Button( Ventana2, height=2, width=10, text="Back", command=lambda: self.Switch(self.master, Ventana2)) backbutton3.pack(side=RIGHT) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar")
class SkyglowEstimationToolbox: """Main class that establishes GUI.""" def __init__(self, root): self.root = root # Radio action buttons self.action = None self.sgmap_single_btn, self.krn_lib_btn, self.multi_map_btn = None, None, None self.file_log_var = StringVar() self.csv_file_var = StringVar() self.krn_folder_var = StringVar() self.output_folder_var = StringVar() self.sgmap_folder_var = StringVar() self.krn_ent_var = StringVar() self.krn_var, self.hem_var = IntVar(), IntVar() self.img, self.cdiag = None, None self.lat_lbl, self.lat_entry = None, None self.k_lbl, self.k_entry = None, None self.zen_lbl, self.zen_entry = None, None self.azi_lbl, self.azi_entry = None, None self.krn_lvl, self.krn_entry, self.krn_btn = None, None, None self.txt_redir, self.prg_log = None, None self.map_btn, self.gen_krn_btn = None, None # Sets window title, size, and icon on screen. self.root.title("Skyglow Estimation Toolbox (SET)") self.root.geometry('%dx%d+%d+%d' % (constants.SW * 0.75, constants.SH * 0.75, 25, 25)) self.root.iconbitmap(os.path.join(os.getcwd(), constants.ICO)) self.root.resizable(False, False) self.root.update_idletasks() # Creates three paned windows for the main screen. base = PanedWindow() base.pack(fill=BOTH, expand=1) sub1 = PanedWindow(base, orient=VERTICAL, height=self.root.winfo_height() * 3 / 4) base.add(sub1) sub2 = PanedWindow(sub1, orient=HORIZONTAL, height=self.root.winfo_height() / 5) sub1.add(sub2) # Creates frame for holding inputs. self.input_frame = Frame(sub2) sub2.add(self.input_frame) # Creates frame for bottom half of main screen. self.img_frame = Frame(sub1, bd=2, bg='white', relief="sunken") sub1.add(self.img_frame) # Creates canvas for displaying images. self.img_canvas = Canvas(self.img_frame, bd=2, relief="groove", width=constants.SW * 0.6, height=self.root.winfo_height() * 3 / 4 * 0.9) self.img_canvas.place(relx=.5, rely=.5, anchor=CENTER) # Creates help button for link to documentation, instructions, and about. self.help_btn = Menubutton(self.input_frame, text="Help", relief="raised", bd=2, width=8, pady=1) #self.help_btn.place(relx=1, rely=0, anchor=NE) self.help_btn.grid(column=4, columnspan=1, row=0) self.help_btn_menu = Menu(self.help_btn, tearoff=0) doc = 'https://github.com/NASA-DEVELOP' self.help_btn_menu.add_command(label="Documentation", command=lambda: self.open_url(doc)) self.help_btn_menu.add_command(label="Instructions", command=self.instructions) self.help_btn_menu.add_separator() self.help_btn_menu.add_command(label="About", command=self.about) self.help_btn["menu"] = self.help_btn_menu def main_screen(self): """Set up input GUI and image display screen.""" self.action = IntVar() btn_width = int(constants.SW / 60) file_width = int(constants.SW / 18) lbl_width = int(constants.SW / 60) gen_width = int(constants.SW / 42) radio_font = Font(family='TkDefaultFont', size=12) self.sgmap_single_btn = Radiobutton( self.input_frame, text="Generate Artificial Skyglow Map", font=radio_font, width=btn_width, variable=self.action, value='sng', command=self.sng_popup) self.krn_lib_btn = Radiobutton(self.input_frame, text="Generate Kernel Library", font=radio_font, width=btn_width, variable=self.action, value='krn', command=self.krn_popup) self.multi_map_btn = Radiobutton( self.input_frame, text="Generate Maps from Multiple Kernels", font=radio_font, width=btn_width, variable=self.action, value='mul', command=self.mul_popup) self.hem_map_btn = Radiobutton( self.input_frame, text="Generate Hemispherical Visualization", font=radio_font, width=btn_width, variable=self.action, value='hem', command=self.hem_popup) #Place widget self.sgmap_single_btn.grid(column=0, columnspan=1, row=0) self.krn_lib_btn.grid(column=1, columnspan=1, row=0) self.multi_map_btn.grid(column=2, columnspan=1, row=0) self.hem_map_btn.grid(column=3, columnspan=1, row=0) # VIIRS Image Reference File self.file_lbl = Label(self.input_frame, text="Image File:", width=lbl_width, anchor=E) self.file_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.file_log_var) self.browse_btn = Button(self.input_frame, text="Browse", command=self.import_viirs) # Angles CSV File self.csv_file_lbl = Label(self.input_frame, text="Angles CSV File:", width=lbl_width, anchor=E) self.csv_file_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.csv_file_var) self.csv_browse_btn = Button(self.input_frame, text="Browse", command=self.import_csv) # Multiple Maps form Kernel library self.mul_file_lbl = Label(self.input_frame, text="Kernel Folder:", width=lbl_width, anchor=E) self.mul_file_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.krn_folder_var) self.mul_browse_btn = Button(self.input_frame, text="Browse", command=self.import_krn_folder) # MultiKrn Map Output Location self.output_lbl = Label(self.input_frame, text="Output Location:", width=lbl_width, anchor=E) self.output_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.output_folder_var) self.output_btn = Button(self.input_frame, text="Browse", command=self.import_out_folder) # Hemisphere Output Location self.sgmap_folder_lbl = Label(self.input_frame, text="Skyglow Map Location:", width=lbl_width, anchor=E) self.sgmap_folder_log = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.sgmap_folder_var) self.sgmap_folder_btn = Button(self.input_frame, text="Browse", command=self.import_sgmap_folder) # Import Kernel Checkbutton self.check_lbl = Label(self.input_frame, text="Import Kernel:", width=lbl_width, anchor=E) self.krn_chk = Checkbutton(self.input_frame, anchor=W, variable=self.krn_var, command=self.checkbtn_val) self.hem_chk_lbl = Label(self.input_frame, text="Generate kernels for hemisphere:", width=lbl_width, anchor=E) self.hem_chk = Checkbutton(self.input_frame, anchor=W, variable=self.hem_var) # Region Latitude (deg), Grand Teton National park = 43.7904 degrees N self.lat_lbl = Label(self.input_frame, text="Latitude (deg):", width=lbl_width, anchor=E) self.lat_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") self.lon_lbl = Label(self.input_frame, text="Longitude (deg):", width=lbl_width, anchor=E) self.lon_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") # Atmospheric Clarity Parameter, REF 2, Eq. 12, p. 645 self.k_lbl = Label(self.input_frame, text="Atmospheric Clarity Parameter:", width=btn_width, anchor=E) self.k_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") # Zenith angle (deg), z, REF 2, Fig. 6, p.648 self.zen_lbl = Label(self.input_frame, text="Zenith Angle (deg):", width=lbl_width, anchor=E) self.zen_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") # Azimuth angle (deg) self.azi_lbl = Label(self.input_frame, text="Azimuth Angle (deg):", width=lbl_width, anchor=E) self.azi_entry = Entry(self.input_frame, width=btn_width, bd=2, relief="sunken") self.krn_lbl = Label(self.input_frame, text="Kernel File:", width=lbl_width, anchor=E) self.krn_ent = Entry(self.input_frame, width=file_width, bd=2, relief="sunken", textvariable=self.krn_ent_var) self.krn_btn = Button(self.input_frame, text="Browse", command=self.import_krn) # Generate Artificial Skyglow Map Button self.map_btn = Button(self.input_frame, text="Generate Artificial Skyglow Map", width=gen_width, command=self.generate_map) # Generate Kernal library button for SET self.gen_krn_btn = Button(self.input_frame, text="Generate Kernel Library", width=gen_width, command=self.generate_krn) # Generate Map of Multiple Kernals(word better later on) self.mul_map_btn = Button(self.input_frame, text="Generate Maps from Multiple Kernels", width=gen_width, command=self.generate_mmap) # Generate Hemispherical Visualization Display of Skyglow self.hem_gen_btn = Button(self.input_frame, text="Generate Hemisphere", width=gen_width, command=self.generate_hem) def import_viirs(self): """Import a VIIRS DNB file.""" # Allows user to search through his directory for VIIRS Image file. file_types = [('TIFF Files', '*.tif'), ('All files', '*')] file_name = filedialog.askopenfilename(initialdir='/', title="Select file", filetypes=file_types) self.file_log_var.set(file_name) # Checks to see if file is empty. If not, displays image on canvas. if file_name != '': pilimg = Image.open(file_name) pilimg_width, pilimg_height = pilimg.size pilimg.tile = [ t for t in pilimg.tile if t[1][2] < pilimg_width and t[1][3] < pilimg_height ] canvas_size = (self.img_canvas.winfo_width(), self.img_canvas.winfo_height()) pilimg_r = pilimg.resize(canvas_size, Image.ANTIALIAS) pilimg_col = ImageOps.colorize(ImageOps.grayscale(pilimg_r), (0, 0, 0), (255, 255, 255)) pilimg_cont = ImageOps.autocontrast(pilimg_col, cutoff=.4, ignore=None) self.img = ImageTk.PhotoImage(pilimg_cont) self.img_canvas.create_image(canvas_size[0] / 2, canvas_size[1] / 2, image=self.img) else: print('File is empty.') def import_csv(self): """Import CSV file.""" file_types = [('CSV Files', '*.csv'), ('All files', '*')] file_name = filedialog.askopenfilename(initialdir='/', title="Select file", filetypes=file_types) self.csv_file_var.set(file_name) if file_name is '': print('File is empty.') def import_krn_folder(self): """Import kernel folder.""" krn_dir = filedialog.askdirectory(initialdir='/', title="Select kernel folder") self.krn_folder_var.set(krn_dir) if krn_dir is '': print('Directory is empty.') def import_out_folder(self): """Import skyglow output folder.""" output_dir = filedialog.askdirectory(initialdir='/', title="Select output folder") self.output_folder_var.set(output_dir) if output_dir is '': print('Directory is empty.') def import_krn(self): """Import existing kernel tif.""" file_types = [('TIFF Files', '*.tif'), ('All files', '*')] file_name = filedialog.askopenfilename(initialdir='/', title="Select file", filetypes=file_types) self.krn_ent_var.set(file_name) def import_sgmap_folder(self): """Import skyglow map folder for hemisphere building.""" sgmap_dir = filedialog.askdirectory(initialdir='/', title="Select skyglow map folder") self.sgmap_folder_var.set(sgmap_dir) if sgmap_dir is '': print('Directory is empty.') def sng_popup(self): """Single map tab.""" self.remove_all() self.check_lbl.grid(column=0, row=2) self.krn_chk.place(relx=.22, rely=.41, anchor=CENTER) self.file_lbl.grid(column=0, row=1) self.file_log.grid(column=1, columnspan=3, row=1) self.browse_btn.grid(column=4, row=1, sticky=W, padx=3) self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) self.k_lbl.grid(column=2, row=3) self.k_entry.grid(column=3, row=3) self.zen_lbl.grid(column=0, row=4) self.zen_entry.grid(column=1, row=4) self.azi_lbl.grid(column=2, row=4) self.azi_entry.grid(column=3, row=4) self.map_btn.grid(column=1, columnspan=3, row=5, sticky=N + S + E + W) def krn_popup(self): """Kernel lib tab.""" self.remove_all() # latitude self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) # atmospheric clarity self.k_lbl.grid(column=2, row=3) self.k_entry.grid(column=3, row=3) # angles file self.csv_file_lbl.grid(column=0, row=1) self.csv_file_log.grid(column=1, columnspan=3, row=1) self.csv_browse_btn.grid(column=4, row=1, sticky=W, padx=3) # input VIIRS image self.file_lbl.grid(column=0, row=2) self.file_log.grid(column=1, columnspan=3, row=2) self.browse_btn.grid(column=4, row=2, sticky=W, padx=3) self.hem_chk_lbl.grid(column=0, row=4) self.hem_chk.place(relx=.21, rely=.69) self.gen_krn_btn.grid(column=1, columnspan=3, row=5, sticky=N + S + E + W) def mul_popup(self): """Multiple maps tab.""" self.remove_all() # Kernel folder location self.mul_file_lbl.grid(column=0, row=1) self.mul_file_log.grid(column=1, columnspan=3, row=1) self.mul_browse_btn.grid(column=4, row=1, sticky=W, padx=3) # input VIIRS image self.file_lbl.grid(column=0, row=2) self.file_log.grid(column=1, columnspan=3, row=2) self.browse_btn.grid(column=4, row=2, sticky=W, padx=3) # Choose output location self.output_lbl.grid(column=0, row=3) self.output_log.grid(column=1, columnspan=3, row=3) self.output_btn.grid(column=4, row=3, sticky=W, padx=3) # Generate map from kernel folder self.mul_map_btn.grid(column=1, columnspan=3, row=4, sticky=N + S + E + W) def hem_popup(self): """Hemisphere tab.""" self.remove_all() # Skyglow Map Folder self.sgmap_folder_lbl.grid(column=0, row=1) self.sgmap_folder_log.grid(column=1, columnspan=3, row=1) self.sgmap_folder_btn.grid(column=4, row=1, sticky=W, padx=3) # Latitude entry self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) # Longitude entry self.lon_lbl.grid(column=2, row=3) self.lon_entry.grid(column=3, row=3) # Generate Hemispherical Visualization button self.hem_gen_btn.grid(column=1, columnspan=3, row=4, sticky=N + S + E + W) def remove_all(self): """Remove all existing GUI elements before opening new tab.""" self.check_lbl.grid_remove() self.krn_chk.place_forget() self.hem_chk.place_forget() self.hem_chk_lbl.grid_remove() self.file_lbl.grid_remove() self.file_log.grid_remove() self.browse_btn.grid_remove() self.krn_lbl.grid_remove() self.krn_ent.grid_remove() self.krn_btn.grid_remove() self.lat_lbl.grid_remove() self.lat_entry.grid_remove() self.k_lbl.grid_remove() self.k_entry.grid_remove() self.zen_lbl.grid_remove() self.zen_entry.grid_remove() self.azi_lbl.grid_remove() self.azi_entry.grid_remove() self.map_btn.grid_remove() self.gen_krn_btn.grid_remove() self.mul_map_btn.grid_remove() self.csv_file_lbl.grid_remove() self.csv_file_log.grid_remove() self.csv_browse_btn.grid_remove() self.mul_file_lbl.grid_remove() self.mul_file_log.grid_remove() self.mul_browse_btn.grid_remove() self.output_lbl.grid_remove() self.output_log.grid_remove() self.output_btn.grid_remove() self.hem_gen_btn.grid_remove() self.lat_lbl.grid_remove() self.lat_entry.grid_remove() self.lon_lbl.grid_remove() self.lon_entry.grid_remove() self.sgmap_folder_lbl.grid_remove() self.sgmap_folder_log.grid_remove() self.sgmap_folder_btn.grid_remove() def checkbtn_val(self): """Change interface based on if Import Kernel button is checked.""" # Import Kernel File widgets when Kernel Checkbutton is marked. if self.krn_var.get(): self.lat_lbl.grid_remove() self.lat_entry.grid_remove() self.k_lbl.grid_remove() self.k_entry.grid_remove() self.zen_lbl.grid_remove() self.zen_entry.grid_remove() self.azi_lbl.grid_remove() self.azi_entry.grid_remove() self.krn_lbl.grid(column=0, row=2) self.krn_ent.grid(column=1, columnspan=3, row=2) self.krn_btn.grid(column=4, row=2, sticky=W, padx=3) self.krn_chk.place_forget() self.krn_chk.place(relx=0.19, rely=.5) # Input parameter widgets when Kernel Checkbuttton is unmarked else: self.krn_lbl.grid_remove() self.krn_ent.grid_remove() self.krn_btn.grid_remove() self.lat_lbl.grid(column=0, row=3) self.lat_entry.grid(column=1, row=3) self.k_lbl.grid(column=2, row=3) self.k_entry.grid(column=3, row=3) self.zen_lbl.grid(column=0, row=4) self.zen_entry.grid(column=1, row=4) self.azi_lbl.grid(column=2, row=4) self.azi_entry.grid(column=3, row=4) self.krn_chk.place_forget() self.krn_chk.place(relx=0.22, rely=.41, anchor=CENTER) @staticmethod def open_url(url): """"Open a url""" webbrowser.open_new(url) def instructions(self): """Open instructions window.""" # Instantiates separate Toplevel instruction window. instr_window = Toplevel(self.root) instr_window.geometry('550x575+25+25') instr_window.title('Instructions') instr_window.wm_iconbitmap(constants.ICO) instr_window.resizable(False, False) # Creatse Scrollbar and Frame for containing other widgets. instr_scroll = Scrollbar(instr_window) instr_scroll.pack(fill=Y, side="right") instr_frame = Frame(instr_window, bg='white') instr_frame.pack(fill=BOTH, side="left") # Adds instruction text from constants and adds image of Cinzano's diagram. instr = Text(instr_frame, width=65, height=40, padx=10, pady=5, bd=0, wrap="word") instr.insert("end", constants.INSTR) cdiagram_file = Image.open("./static/cinzano_diagram.PNG") cdiagram_file = cdiagram_file.resize((500, 450), Image.ANTIALIAS) self.cdiag = ImageTk.PhotoImage(cdiagram_file) instr.image_create("end", image=self.cdiag) instr.tag_add("top", "1.0", "4.10") instr.tag_config("top", font='Times 12 bold') instr.tag_add("body", "5.0", "19.20") instr.tag_config("body", font='Times 12') instr.insert("end", constants.CDIAG) instr.pack() instr_scroll.config(command=instr.yview) def about(self): """Open an about window. Window gives authors, SET version number, and icon credit. """ # Instantiates a new Toplevel about window. about_window = Toplevel(self.root) about_window.geometry('350x335+25+25') about_window.title('About') about_window.wm_iconbitmap(constants.ICO) about_window.resizable(False, False) # Adds text to about window. about = Text(about_window, width=50, height=30, padx=10, pady=3) about.insert("end", constants.ABOUT) about.tag_add("abt", "1.0", "21.30") about.tag_config("abt", font='Times 10 bold', justify=CENTER) about.pack() def progress(self): """Construct a progress window to monitor darksky.""" # Instantiates a new Toplevel window and frame for progress bar and loading log. self.prg_window = Toplevel(self.root) self.prg_window.geometry('650x325+250+250') self.prg_window.title('Generating Artificial Skyglow Map...') self.prg_window.iconbitmap(constants.ICO) self.prg_window.resizable(False, False) prg_frame = Frame(self.prg_window) prg_frame.pack(fill=BOTH) # Creates Scrollbar, Progressbar, and Label for checking progress.. prg_scroll = Scrollbar(prg_frame) prg_scroll.pack(fill=Y, side="right") self.prg_bar = ttk.Progressbar(prg_frame, orient=HORIZONTAL, length=750, mode='indeterminate') self.prg_bar.pack() self.prg_bar.start() prg_lbl_txt = StringVar() prg_lbl = Label(prg_frame, textvariable=prg_lbl_txt) prg_lbl.pack() # Displays message log that prints from log file and starts darkskypy. self.prg_log = Text(prg_frame, width=90, padx=5, pady=5, relief="sunken") self.prg_log.pack() self.prg_log.insert( "end", "*****Progress Log*****\n=======================\n") self.prg_log.tag_add("abt", "1.0", "3.0") self.prg_log.tag_config("abt", font='Courier 12 bold', justify=CENTER) self.txt_redir = LogRedirector(self.prg_log) logger.addHandler(self.txt_redir) sys.stderr = StderrRedirector(self.prg_log) prg_lbl_txt.set("Start time: " + str(time.asctime())) self.no_progress = 0 def update_progress(self): """Update progress window to prevent it from freezing.""" self.prg_log.update() # if only one thread exists, stop progress bar and close window if len(threading.enumerate()) == 1: self.prg_bar.stop() self.no_progress += 1 if self.no_progress == 3: self.prg_window.withdraw() else: self.prg_bar.start() self.root.after(1000, self.update_progress) def generate_map(self): """Call darksky.sgmapper in background thread.""" # Acquires input arguments. lat_in, k_in, zen_in, azi_in, file_in, krn_file_in = 0, 0, 0, 0, '', '' if self.krn_var.get(): krn_file_in = self.krn_ent_var.get() else: lat_in = float(self.lat_entry.get()) k_in = float(self.k_entry.get()) zen_in = float(self.zen_entry.get()) azi_in = float(self.azi_entry.get()) file_in = self.file_log_var.get() self.progress() # Create new threads to run light propagation model simultaneously. p_thread = threading.Thread(target=self.update_progress()) t_thread = threading.Thread(target=darksky.sgmapper, args=(lat_in, k_in, zen_in, azi_in, file_in, krn_file_in)) t_thread.setDaemon(True) p_thread.start() t_thread.start() def generate_krn(self): """Start kernel generation in background threads.""" # Acquires input arguments csv_in, file_in, lat_in, k_in, hem = '', '', 0, 0, False csv_in = self.csv_file_var.get() file_in = self.file_log_var.get() lat_in = float(self.lat_entry.get()) k_in = float(self.k_entry.get()) hem = self.hem_var.get() self.progress() # Create new threads to run light propagation model simultaneously. p_thread = threading.Thread(target=self.update_progress()) with open(csv_in, "rb") as f: angle_list = loadtxt(f, delimiter=",", skiprows=1) p_thread.start() for angle_set in angle_list: t_thread = threading.Thread(target=darksky.generate_krn, args=(lat_in, k_in, angle_set[0], angle_set[1], file_in, hem)) t_thread.setDaemon(True) t_thread.start() def generate_mmap(self): """Start brightness map creation from kernels.""" # Acquires input arguments krn_folder_in, file_in, output_in, = '', '', '' krn_folder_in = self.krn_folder_var.get() file_in = self.file_log_var.get() output_in = self.output_folder_var.get() self.progress() # Create new threads to run light propagation model simultaneously. p_thread = threading.Thread(target=self.update_progress()) t_thread = threading.Thread(target=darksky.multisgmapper, args=(file_in, krn_folder_in, output_in)) t_thread.setDaemon(True) p_thread.start() t_thread.start() def generate_hem(self): """Generate hemisphere.""" sgmap_folder_in, lat_in, lon_in, = '', 0, 0 sgmap_folder_in = self.sgmap_folder_var.get() lat_in = float(self.lat_entry.get()) lon_in = float(self.lon_entry.get()) darksky.generate_hem(lat_in, lon_in, sgmap_folder_in)
class controllerSettings(): def createControllerWindow(self): #Creation of the main window self.controllerWindow = Toplevel() self.controllerWindow.title("Controller Settings") self.controllerWindow.geometry("400x310+450+200") self.controllerWindow.resizable(width=False, height=False) #Frame for the manual controller options self.k_controllerFrame = tk.Frame(self.controllerWindow) self.c_controllerFrame = tk.Frame(self.controllerWindow) self.instructionFrame = tk.Frame(self.controllerWindow) self.knownJsFrame=tk.Frame(self.k_controllerFrame,width=150,height=120) self.knownJsFrame.pack_propagate(0) self.chosenJsFrame=tk.Frame(self.c_controllerFrame,width=150,height=120) self.chosenJsFrame.pack_propagate(0) self.instrLabel = tk.Label(self.instructionFrame, text="Please select up " \ "to two remote controllers from the recognized controller list. Alter" \ "natively, scan for existing controllers and automatically add the " \ "controller to the software.", anchor=tk.W, justify=tk.LEFT, wraplength = 400) self.instrLabel.pack() self.l1 = tk.Label(self.knownJsFrame, text="Recognized Controllers") self.l1.pack() self.l2 = tk.Label(self.chosenJsFrame, text="Selected Controller/s") self.l2.pack() self.knownListbox = tk.Listbox(self.knownJsFrame, height = 15, width = 29) self.knownListbox.insert(tk.END) for item in ["PS3 PowerA", "Xbox 360 Afterglow"]: self.knownListbox.insert(tk.END, item) self.chosenListbox = tk.Listbox(self.chosenJsFrame, height = 15, width = 29) self.chosenListbox.insert(tk.END) self.controllers = [] self.controllers = self.retrieveControllers() if len(self.controllers) == 1: self.chosenListbox.insert(tk.END, self.controllers[0]) elif len(self.controllers) == 2: self.chosenListbox.insert(tk.END, self.controllers[0]) self.chosenListbox.insert(tk.END, self.controllers[1]) self.closeBtn = tk.Button(self.controllerWindow, text ="Close", \ command = self.controllerWindow.destroy, width = 12) self.okBtn = tk.Button(self.controllerWindow, text ="Okay", \ width = 12) self.applyBtn = tk.Button(self.controllerWindow, text ="Apply Changes", \ width = 16, command = self.selectedListBoxWriteout) self.addBtn = tk.Button(self.controllerWindow, text ="Add", \ width = 10, command = self.addListBoxIndex) self.rmvBtn = tk.Button(self.controllerWindow, text ="Remove", \ width = 10, command = self.rmvListBoxIndex) self.scanBtn = tk.Button(self.controllerWindow, text ="Scan for controllers...", \ width = 16) self.knownListbox.pack() self.chosenListbox.pack() self.knownJsFrame.pack() self.chosenJsFrame.pack() self.instructionFrame.pack() self.k_controllerFrame.pack() self.c_controllerFrame.pack() self.closeBtn.pack() self.okBtn.pack() self.applyBtn.pack() self.addBtn.pack() self.rmvBtn.pack() self.scanBtn.pack() self.k_controllerFrame.place(x = 20, y = 85) self.c_controllerFrame.place(x = 210, y = 85) self.closeBtn.place(x = 300, y = 275) self.okBtn.place(x = 200, y = 275) self.applyBtn.place(x = 20, y = 275) self.addBtn.place(x = 40, y = 210) self.rmvBtn.place(x = 240, y = 210) self.scanBtn.place(x = 230, y = 50) def addListBoxIndex(self): self.chosenInt = 0 self.chosenInt = self.chosenListbox.size() if self.chosenInt >= 2: tkm.showerror("Error", "You can only add up to two controllers.") else: self.listBoxStr = "" self.listBoxStr = self.knownListbox.get(tk.ACTIVE) self.chosenListbox.insert(tk.END, self.listBoxStr) def rmvListBoxIndex(self): self.chosenInt = 0 self.chosenInt = self.chosenListbox.index(tk.ACTIVE) self.chosenListbox.delete(self.chosenInt) def selectedListBoxWriteout(self): self.tempStr = "" self.contrlStr1 = "" self.contrlStr2 = "" self.success = 0 if self.chosenListbox.size() == 0: tkm.showerror("Error", "No controllers selected.") elif self.chosenListbox.size() == 1: self.contrlStr1 = self.chosenListbox.get(0) self.tempStr = "controllerdata{" + self.contrlStr1 + "}\n" self.tempStr = self.tempStr.replace (" ", "_") self.success = 1 elif self.chosenListbox.size() == 2: self.contrlStr1 = self.chosenListbox.get(0) self.contrlStr2 = self.chosenListbox.get(1) self.tempStr = "controllerdata{" + self.contrlStr1 + ","\ + self.contrlStr2 + "}\n" self.tempStr = self.tempStr.replace (" ", "_") self.success = 1 if self.success == 1: self.data = [] with open('config.txt', 'r') as file: # read a list of lines into data self.data = file.readlines() for x in range (0, len(self.data)): if self.data[x].find("controllerdata") != -1: self.data[x] = self.tempStr print self.data[x] with open('config.txt', 'w') as file: file.writelines(self.data) self.main.destroy() self.createMainWindow()
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)
class tkFileSelector() : def __init__(self,master,start_dir=expanduser("~"),filetypes=[],title="Select a music file.",color_1="#000000",color_2="#00c0c0",highlight_color_items="#c9c9c9") : ''' master == root_window == Tk() use color_1 and color_2 and bg_items and fg_items and highlight_color_items for colors personalisation. filetypes must "Strictly" be a list of extension beginning with an asterix followed by a point and the extension (in lowercase) or an empty list for no filtering. filetypes=["*.mp3","*.wav"] per example. Or insert an, item '*' for all filetype in combination with defined filetypes. for borderwidth and relief settings look at the code ''' # Constrcut GUI for the file selection toplevel. self.toplevel=Toplevel(master,bg=color_1,borderwidth=1,relief="sunken") self.toplevel.resizable(width=False, height=False) self.toplevel.title(title) self.dir_selection_frame=Frame(self.toplevel,bg=color_1,borderwidth=8/2,relief="groove") # Frame container for directory fields. self.dir_name_entry=Entry(self.toplevel,justify="center",width=50,bg=color_2,fg=color_1) # This will contains the current directory relative dirname self.dir_name_separator=Button(self.toplevel,width=1,relief="sunken",bg=color_1,fg=color_2) # An separator self.dir_back_button=Button(self.toplevel,width=6,relief="raised",bg=color_2,fg=color_1,text="Back",command=self.folder_go_back) # Change directory back button. self.canvas_frame=Frame(self.toplevel,borderwidth=8,relief="groove") # Frame for the file selection window canvas and his scrollbar. self.canvas=Canvas(self.canvas_frame,height=20*9,width=18*28,bg=color_2) # File selection window. self.canvas_scrollbar=Scrollbar(self.canvas_frame,orient=HORIZONTAL, bg=color_2,troughcolor=color_1,command=self.canvas.xview) # File selection window scrollbar. self.canvas.configure(xscrollcommand=self.canvas_scrollbar.set) self.file_selection_frame=Frame(self.toplevel,bg=color_1,borderwidth=8/2,relief="groove") # Frame container for filename fields. self.file_name_entry=Entry(self.toplevel,justify="center",width=50,bg=color_2,fg=color_1) # This will contains the basename (relative) of the selected file. self.file_name_separator=Button(self.toplevel,width=1,relief="sunken",bg=color_1,fg=color_2) # An separator. self.file_filter_menubutton = Menubutton(self.file_selection_frame, text='',relief="groove",width=8,bg=color_2,fg=color_1) # Menubutton for filetype filter. self.file_filter_extension="" if filetypes : self.file_filter_menu= Menu(self.file_filter_menubutton,borderwidth=3,relief="groove") # We use a menu for the filetypes filtering. i=0 self.file_filter_var=StringVar(master=None, value=filetypes[i], name=None) # Control varaible for current filetype and initialize with the first filetype item. self.file_filter_menubutton.config(text=filetypes[i]) self.file_filter_extension=filetypes[i][1::] while i < len(filetypes) : # Creating radiobutton to change the filetype filter. self.file_filter_menu.add_radiobutton(label=filetypes[i], variable=self.file_filter_var,value=filetypes[i],background=color_2,command=self.set_filetype_filter ) i += 1 self.file_filter_menubutton.configure(menu= self.file_filter_menu) self.buttons_frame=Frame(self.toplevel,bg=color_2,borderwidth=8,relief="groove",height=50,width=18*3) # Frame container for the buttons. self.button_cancel=Button(self.buttons_frame,bg=color_2,fg=color_1,text="Quit",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_quit) self.button_home=Button(self.buttons_frame,bg=color_2,fg=color_1,text="Home",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_home) self.button_ok=Button(self.buttons_frame,bg=color_2,fg=color_1,text=" OK ",borderwidth=8/2,relief="groove",width=8,command=self.item_selection_ok) self.start_dir=start_dir # Start folder. self.curdir=start_dir # Current folder. self.last_dir=[] # Container for the precedent folders we visit. self.last_dir.append(start_dir) # Append start folder. self.select_filepath="" # Value to return by file selection. self.dir_name_entry.insert(0,"../"+basename(self.curdir)) if not color_2 : self.items_bg="#D9D9D9" else : self.items_bg=color_2 self.items_fg=color_1 self.highlight_color_items=highlight_color_items self.init_icons() self.ls_dir() self.update_canvas() self.dir_selection_frame.grid(row=0,column=0,sticky="WE") self.dir_name_entry.grid(row=0,column=0,in_=self.dir_selection_frame,sticky="NSEW") self.dir_name_separator.grid(row=0,column=1,in_=self.dir_selection_frame,sticky="EW") self.dir_back_button.grid(row=0,column=2,in_=self.dir_selection_frame,sticky="EW") self.canvas_frame.grid(row=1,column=0,sticky="WE") self.canvas.grid(row=0,column=0,in_=self.canvas_frame) self.canvas_scrollbar.grid(row=1,column=0,in_=self.canvas_frame,sticky="WE") self.file_selection_frame.grid(row=2,column=0,sticky="WE") self.file_name_entry.grid(row=0,column=0,in_=self.file_selection_frame,sticky="NSEW") self.file_name_separator.grid(row=0,column=1,in_=self.file_selection_frame,sticky="EW") self.file_filter_menubutton.grid(row=0,column=2,in_=self.file_selection_frame,sticky="NS") self.buttons_frame.grid(row=3,column=0,sticky="NSEW") self.button_cancel.grid(row=0,column=2,padx=32+3,pady=4,in_=self.buttons_frame) self.button_home.grid(row=0,column=4,padx=32+3,pady=4,in_=self.buttons_frame) self.button_ok.grid(row=0,column=6,padx=34+3,pady=4,in_=self.buttons_frame) self.toplevel.wait_window() def init_icons(self) : # Folder and file icons, design by me. self.image_folder=Image.open("/usr/share/ScreenLocker/Images/file_selector/folder_icon.png") self.imagetk_folder=ImageTk.PhotoImage(image=self.image_folder) self.image_file=Image.open("/usr/share/ScreenLocker/Images/file_selector/file_icon.png") self.imagetk_file=ImageTk.PhotoImage(image=self.image_file) def ls_dir(self) : ''' List an directory and split the result in folders and files containers. Finally sort the 2 containers.''' folder_content=listdir(self.curdir) self.cur_folder_entries=len(folder_content) self.cur_folder_list=[] self.cur_files_list=[] folder_content.sort() for v in folder_content : if isdir(self.curdir+"/"+v) : self.cur_folder_list.append(unicode(v,encoding='utf-8')) elif isfile(self.curdir+"/"+v) : self.cur_files_list.append(unicode(v,encoding='utf-8')) self.cur_folder_list.sort() self.cur_files_list.sort() def update_canvas(self) : ''' Generating the content from the File selection window (an canvas)''' self.clear_canvas() i=0 # global folder and file iterator. pos_x=0 # Coordinates for the rows. pos_y=0 # Coordinates in the columns. max_len=0 # Column max folder|filename length. max_len_save=0 # Saved value for filling empty canvas scrollregion. while i < len(self.cur_folder_list) : # Generating the folder items of the current folder exec(u"folder_icon_{0}=Label(self.canvas,text='{1}',image=self.imagetk_folder,relief='flat',width=17,height=17,bg=self.items_bg)".format(str(i),self.cur_folder_list[i].replace("'","\\'"))) exec(u"folder_name_{0}=Label(self.canvas,text='{1}',relief='flat',width={2},font='Monospace 9 bold',justify='left',bg=self.items_bg,fg=self.items_fg)".format(str(i),self.cur_folder_list[i].replace("'","\\'"),int(len(" "+self.cur_folder_list[i])))) if int(len(" "+self.cur_folder_list[i])) > max_len : # Update longest folder name in this column. max_len=int(len(" "+self.cur_folder_list[i])) # Storing the value for max length of the longest folder name in this column. max_len_save=max_len # Value to save for filling if the generating content take minus place as the canvas scrollregion. exec("folder_icon_{0}.bind('<Double-1>',self.select_folder)".format(str(i))) exec("folder_name_{0}.bind('<Double-1>',self.select_folder)".format(str(i))) exec("folder_name_{0}.bind('<Enter>',self.highlight_item_enter)".format(str(i))) exec("folder_name_{0}.bind('<Leave>',self.highlight_item_leave)".format(str(i))) exec("folder_icon_{0}.pack(side='left',fill=BOTH)".format(str(i))) exec("folder_name_{0}.pack(side='right',fill=BOTH)".format(str(i))) exec("self.canvas.create_window(({1},{2}),anchor='nw',window=folder_icon_{0})".format(str(i),pos_x,pos_y)) exec("self.canvas.create_window(({1}+17+1,{2}),anchor='nw',window=folder_name_{0})".format(str(i),pos_x,pos_y)) pos_y += 20 # column increment 17 height of an items + 3 pixels padding. if ( i % 9 == 0) and not i == 0 : # An column can contains 9 items and we change column. pos_y=0 # Column position updating. pos_x += 17 + (max_len*9) # Update the x coordinates according the maximal length of foldername in this column ( (9 pixels == font size) (17 pixels for the folder item icon) ) . max_len=0 i += 1 # Go to the next item. ii=0 # Files iterator. while ii < len(self.cur_files_list) : # Generating the files items of the current folder. if (self.file_filter_extension and self.cur_files_list[ii].lower().endswith(self.file_filter_extension)) or not self.file_filter_extension : # applying filter of no filetype filering. exec(u"file_icon_{0}=Label(self.canvas,text='{1}',image=self.imagetk_file,relief='flat',width=17,height=17,bg=self.items_bg)".format(str(i),self.cur_files_list[ii].replace("'","\\'"))) exec(u"file_name_{0}=Label(self.canvas,text='{1}',relief='flat',width={2},font='Monospace 9 normal',justify='left',bg=self.items_bg,fg=self.items_fg)".format(str(i),self.cur_files_list[ii].replace("'","\\'"),int(len(" "+self.cur_files_list[ii])))) if int(len(" "+self.cur_files_list[ii])) > max_len : # Update longest filename in this column. max_len=int(len(" "+self.cur_files_list[ii])) # Storing the value for max length of the longest filename in this column. max_len_save=max_len # Value to save for filling if the generating content take minus place as the canvas scrollregion. exec("file_icon_{0}.bind('<Double-1>',self.select_file)".format(str(i))) exec("file_name_{0}.bind('<Double-1>',self.select_file)".format(str(i))) exec("file_name_{0}.bind('<Enter>',self.highlight_item_enter)".format(str(i))) exec("file_name_{0}.bind('<Leave>',self.highlight_item_leave)".format(str(i))) exec("file_icon_{0}.pack(side='left',fill=BOTH)".format(str(i))) exec("file_name_{0}.pack(side='right',fill=BOTH)".format(str(i))) exec("self.canvas.create_window(({1},{2}),anchor='nw',window=file_icon_{0})".format(str(i),pos_x,pos_y)) exec("self.canvas.create_window(({1}+17+1,{2}),anchor='nw',window=file_name_{0})".format(str(i),pos_x,pos_y)) pos_y += 20 # column increment 17 height of an items + 3 pixels padding. if ( i % 9 == 0) and not i == 0 : # An column can contains 9 items and we change column. # Note: we check the common file & folder iterator. pos_y=0 # Column position updating. pos_x += 17 + (max_len*9) # Update the x coordinates according the maximal length of filename in this column ( (9 pixels == font size) (17 pixels for the file item icon) ). max_len=0 i += 1 ii += 1 if not pos_x+(max_len_save*9)+17 < 18*28 : # items collection greater than the canvas scrollregion. self.canvas.config(scrollregion=(0,0,pos_x+(max_len_save*9)+17,0)) else : # items collection littler than the canvas scrollregion. self.canvas.config(scrollregion=(0,0,18*28,0)) def clear_canvas(self) : for child in self.canvas.children.values() : child.destroy() def highlight_item_enter(self,event) : event.widget.config(bg=self.highlight_color_items) def highlight_item_leave(self,event) : event.widget.config(bg=self.items_bg) def select_folder(self,event) : if isdir(self.curdir+"/"+event.widget.cget("text").lstrip()) : # event.widget.cget("text") return the selected folder. sea the update_canvas() method. self.select_filepath="" self.file_name_entry.delete(0,END) if self.curdir.startswith('//') : # Bugfix. self.curdir=self.curdir[1::] self.last_dir.append(self.curdir) else : self.last_dir.append(self.curdir) for v in self.last_dir : # Bigfix if self.last_dir.count(v) > 1 : self.last_dir.remove(v) try : # in case of access right this will fail immediatelly listdir(self.curdir+"/"+event.widget.cget("text")) self.curdir=self.curdir+"/"+event.widget.cget("text") self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+event.widget.cget("text")) self.ls_dir() self.update_canvas() except : pass def select_file(self,event) : if isfile(self.curdir+"/"+event.widget.cget("text")) : # Set the value to return and fill the file selection field. self.select_filepath=self.curdir+"/"+event.widget.cget("text") self.file_name_entry.delete(0,END) self.file_name_entry.insert(0,event.widget.cget("text")) def folder_go_back(self) : if len(self.last_dir) > 1 : self.curdir=self.last_dir.pop(-1) # pop the last value from the visited folder folders else : # In case we have yet only 1 folder in the visited folder container. if self.last_dir[0].rfind("/") : # The value of the container is not the root folder ( / ) but not the /home/username folder who can be only visited folder. self.last_dir[0]=self.last_dir[0][0:self.last_dir[0].rfind("/")] self.curdir=self.last_dir[0] elif self.last_dir[0].rfind("/") == 0 : # The value of the container is the root folder. self.last_dir[0]="/" self.curdir=self.last_dir[0] else : # The value is the /home/username directory self.curdir=self.last_dir[0] self.file_name_entry.delete(0,END) self.select_filepath="" self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+basename(self.curdir)) self.ls_dir() self.update_canvas() def set_filetype_filter(self) : '''Change filetype filter.''' self.file_filter_menubutton.config(text=self.file_filter_var.get()) self.file_filter_extension=self.file_filter_var.get()[1::] # Contains the selected filetype ( in form '.'+filetype ). self.file_name_entry.delete(0,END) self.select_filepath="" self.ls_dir() self.update_canvas() def item_selection_ok(self) : '''Return the selected filepath or empty string and destroy File_selector instance''' if self.select_filepath : self.toplevel.destroy() return True def item_selection_quit(self) : '''destroy File_selector instance''' self.toplevel.destroy() return False def item_selection_home(self) : '''Change current directory to the /home/username folder''' self.curdir=expanduser("~") self.select_filepath="" self.file_name_entry.delete(0,END) self.last_dir=[] self.last_dir.append(expanduser("~")) self.dir_name_entry.delete(0,END) self.dir_name_entry.insert(0,"../"+basename(self.curdir)) self.ls_dir() self.update_canvas()
def hiya(self): if not self.nand_mode: showinfo( 'Info', 'Now you will be asked to choose the SD card path that will be used ' 'for installing the custom firmware (or an output folder).\n\nIn order to avoid ' 'boot errors please assure it is empty before continuing.') self.sd_path = askdirectory() # Exit if no path was selected if self.sd_path == '': return # If adding a No$GBA footer, check if CID and ConsoleID values are OK elif self.nand_operation.get() == 2: cid = self.cid.get() console_id = self.console_id.get() # Check lengths if len(cid) != 32: showerror('Error', 'Bad eMMC CID') return elif len(console_id) != 16: showerror('Error', 'Bad Console ID') return # Parse strings to hex try: cid = cid.decode('hex') except TypeError: showerror('Error', 'Bad eMMC CID') return try: console_id = bytearray(reversed(console_id.decode('hex'))) except TypeError: showerror('Error', 'Bad Console ID') return dialog = Toplevel(self) # Open as dialog (parent disabled) dialog.grab_set() dialog.title('Status') # Disable maximizing dialog.resizable(0, 0) frame = Frame(dialog, bd=2, relief=SUNKEN) scrollbar = Scrollbar(frame) scrollbar.pack(side=RIGHT, fill=Y) self.log = ThreadSafeText(frame, bd=0, width=52, height=20, yscrollcommand=scrollbar.set) self.log.pack() scrollbar.config(command=self.log.yview) frame.pack() Button(dialog, text='Close', command=dialog.destroy, width=16).pack(pady=10) # Center in window dialog.update_idletasks() width = dialog.winfo_width() height = dialog.winfo_height() dialog.geometry( '%dx%d+%d+%d' % (width, height, root.winfo_x() + (root.winfo_width() / 2) - (width / 2), root.winfo_y() + (root.winfo_height() / 2) - (height / 2))) # Check if we'll be adding a No$GBA footer if self.nand_mode and self.nand_operation.get() == 2: Thread(target=self.add_footer, args=(cid, console_id)).start() else: Thread(target=self.check_nand).start()
width_text, height_text = draw.textsize(text) draw.text((text_x, text_y), text, fill="white") photoimage = ImageTk.PhotoImage(image) Label(root, image=photoimage).place(x=0, y=0) entry_pady = 7 Entry(root, background="white").place(x=text_x, y=text_y + height_text + entry_pady) ################################################### # Another example toplevel = Toplevel(root) toplevel.resizable(width=False, height=False) image_file = io.BytesIO(base64.b64decode(BASE64_BACKGROUND)) image = Image.open(image_file) photoimage2 = ImageTk.PhotoImage(image) canvas = Canvas(toplevel, width=width, height=height) canvas.create_image((0, 0), image=photoimage2, anchor="nw") canvas.create_text((text_x, text_y), text=text, fill="white", anchor="nw") canvas.pack() entry = Entry(canvas, background="white") canvas.create_window((text_x, text_y + height_text + entry_pady), window=entry, anchor="nw")
def add_holiday_gui(self, date=None): """ Opens window for adding new holidays to the holiday file :param date: If provided, the start/end date fields are prepopulated with this date, else with dd/mm/yyyy placeholders """ # Create a new window new_hol_top = Toplevel() new_hol_top.title("Add new holiday") new_hol_top.resizable(0, 0) # Title label title = Label(new_hol_top, text="Title:") title.grid(row=0, sticky="W") # Title entry box t_string = StringVar() t_entry = Entry(new_hol_top, textvariable=t_string) t_entry.grid(row=0, column=2) # Start date label start = Label(new_hol_top, text="Start Date:") start.grid(row=1, sticky="W") # Start date entry box s_string = StringVar() s_entry = Entry(new_hol_top, textvariable=s_string) if date is not None: s_entry.insert(0, str(date.day) + "/" + str(date.month) + "/" + str(date.year)) else: s_entry.insert(0, "dd/mm/yyyy") s_entry.grid(row=1, column=2) # End date label end = Label(new_hol_top, text="End Date:") end.grid(row=2, sticky="W") # End date entry box e_string = StringVar() e_entry = Entry(new_hol_top, textvariable=e_string) if date is not None: e_entry.insert(0, str(date.day) + "/" + str(date.month) + "/" + str(date.year)) else: e_entry.insert(0, "dd/mm/yyyy") e_entry.grid(row=2, column=2) # Colour label colours_label = Label(new_hol_top, text="Colour:") colours_label.grid(row=3, sticky="W") # Colour ttk combobox allowed_colours = ["red", "green", "blue", "orange", "yellow", "purple"] allowed_colours.sort() colour_select = ttk.Combobox(new_hol_top, values=allowed_colours, width=19) colour_select.set("Choose a colour...") colour_select.grid(row=3, column=2, sticky="E") def get_start_end(): # When holiday submitted, gets date, colour, title values and adds to # holidays variable s = s_string.get() e = e_string.get() t = t_string.get() c = colour_select.get() if c in allowed_colours: try: s = [int(i) for i in s.split("/")] e = [int(i) for i in e.split("/")] self.add_holiday(datetime.date(s[2], s[1], s[0]), datetime.date(e[2], e[1], e[0]), t, c) # Refresh canvas self.app.update_calendar() # Destroy popup window new_hol_top.destroy() except: pass submit = Button(new_hol_top, text="Submit", command=get_start_end) submit.grid(column=0, columnspan=3)
def no_click(): popup = Toplevel() popup.resizable(False,False) ttk.Label(popup, text='请选择文件!').pack(pady=25) center_window(popup, 300, 100) popup.after(2500,lambda:popup.destroy())
class robotGUI(): def __init__(self): #Initialize the master window self.main = tk.Tk() self.main.title("Robot Interface v0.24") self.main.geometry("850x650+300+300") self.main.resizable(width=False, height=False) menubar = Menu(self.main) self.main.config(menu=menubar) preferenceMenu = Menu(menubar) preferenceMenu.add_command(label="Controller Settings", \ command = self.createControllerWindow) helpMenu = Menu(menubar) helpMenu.add_command(label="Help...") comMenu = Menu(menubar) comMenu.add_command(label="Empty") fileMenu = Menu(menubar) fileMenu.add_command(label="Data Files...") menubar.add_cascade(label="File", menu=fileMenu) menubar.add_cascade(label="Preferences", menu=preferenceMenu) menubar.add_cascade(label="COM Port", menu=comMenu) menubar.add_cascade(label="Help", menu=helpMenu) #Initialize frame sections of the window self.titleFrame = tk.Frame() self.enableDisableFrame = tk.Frame() self.labelFrame = tk.Frame() #Frame partitions (subframes) go here self.enableDisable=tk.Frame(self.enableDisableFrame,width=129,height=87) self.enableDisable.pack_propagate(0) self.axisLabels=tk.Frame(self.labelFrame,width=130,height=200) self.axisLabels.pack_propagate(0) self.buttonLabels=tk.Frame(self.labelFrame,width=130,height=323) self.buttonLabels.pack_propagate(0) #Initialize the variables self.xAxisVar = tk.StringVar(value = "xAxis is: N/A") self.yAxisVar = tk.StringVar(value = "yAxis is: N/A") self.aAxisVar = tk.StringVar(value = "aAxis is: N/A") self.bAxisVar = tk.StringVar(value = "bAxis is: N/A") #Initialize buttons self.remote_Label = tk.Label(self.enableDisable, text='PS3 Controller',\ font=("Helvetica", 13), fg='black', anchor = tk.CENTER, width = 12) self.remote_Label.pack(side = "top") self.initBut = tk.Button(self.enableDisable, text ="Enable", \ command = self.runController, width = 15) self.initBut.pack() self.stopBut = tk.Button(self.enableDisable, text ="Disable", \ command = self.stopController, width = 15) self.stopBut.pack() #Initalize Axis Labels self.title_label = tk.Label(self.titleFrame, text='Mech Warfare GUI',\ font=("Helvetica", 20),bg='blue',fg='white', width = 53) self.axisTitle = tk.Label(self.axisLabels, text='Axes',\ font=("Helvetica", 13), fg='black', width = 40, \ anchor=tk.CENTER) self.xAxisLabel = tk.Label(self.axisLabels, fg="black", \ textvariable=self.xAxisVar, width=40, font=("Helvetica", 12), \ anchor=tk.W) self.yAxisLabel = tk.Label(self.axisLabels, fg="black", \ textvariable=self.yAxisVar, width=40, font=("Helvetica", 12), \ anchor=tk.W) self.aAxisLabel = tk.Label(self.axisLabels, fg="black", \ textvariable=self.aAxisVar, width=40, font=("Helvetica", 12), \ anchor=tk.W) self.bAxisLabel = tk.Label(self.axisLabels, fg="black", \ textvariable=self.bAxisVar, width=40, font=("Helvetica", 12), \ anchor=tk.W) #Initalize Button Labels self.buttonTitle = tk.Label(self.buttonLabels, text='Buttons',\ font=("Helvetica", 13), fg='black', width = 40, \ anchor=tk.CENTER) self.xLabel = tk.Label(self.buttonLabels, text=' X ',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.cirLabel = tk.Label(self.buttonLabels, text=' Circle ',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.triLabel = tk.Label(self.buttonLabels, text=' Triangle ',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.squLabel = tk.Label(self.buttonLabels, text=' Square ',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.leftTrigLabel = tk.Label(self.buttonLabels, text='Left Trigger',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.rightTrigLabel = tk.Label(self.buttonLabels, text='Right Trigger',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.leftBumpLabel = tk.Label(self.buttonLabels, text='Left Bumper',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.rightBumpLabel = tk.Label(self.buttonLabels, text='Right Bumper',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.selectLabel = tk.Label(self.buttonLabels, text='Select',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.startLabel = tk.Label(self.buttonLabels, text='Start',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.rightTogLabel = tk.Label(self.buttonLabels, text='Right Toggle',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.leftTogLabel = tk.Label(self.buttonLabels, text='Left Toggle',\ font=("Helvetica", 12), fg='black', bg='red', width = 30, \ anchor=tk.CENTER) self.title_label.pack() self.axisTitle.pack() self.xAxisLabel.pack() self.yAxisLabel.pack() self.aAxisLabel.pack() self.bAxisLabel.pack() self.buttonTitle.pack() self.xLabel.pack() self.cirLabel.pack() self.triLabel.pack() self.squLabel.pack() self.leftTrigLabel.pack() self.rightTrigLabel.pack() self.leftBumpLabel.pack() self.rightBumpLabel.pack() self.rightTogLabel.pack() self.leftTogLabel.pack() self.selectLabel.pack() self.startLabel.pack() #Package subframes go here self.axisLabels.pack() self.buttonLabels.pack() self.enableDisable.pack() #Package frames and create the window self.titleFrame.pack() self.enableDisableFrame.pack() self.labelFrame.pack() self.enableDisableFrame.place(x=6, y=42) self.labelFrame.place(x=5, y=129) self.axisLabels.config(highlightbackground="black", borderwidth= 5, \ relief = "ridge") self.buttonLabels.config(highlightbackground="black", borderwidth= 5, \ relief = "ridge") self.enableDisable.config(highlightbackground="black", borderwidth= 5, \ relief = "ridge") tk.mainloop() def createControllerWindow(self): #Creation of the main window self.controllerWindow = Toplevel() self.controllerWindow.title("Controller Settings") self.controllerWindow.geometry("400x310+300+300") self.controllerWindow.resizable(width=False, height=False) #Frame for the manual controller options self.k_controllerFrame = tk.Frame(self.controllerWindow) self.c_controllerFrame = tk.Frame(self.controllerWindow) self.instructionFrame = tk.Frame(self.controllerWindow) self.knownJsFrame=tk.Frame(self.k_controllerFrame,width=150,height=120) self.knownJsFrame.pack_propagate(0) self.chosenJsFrame=tk.Frame(self.c_controllerFrame,width=150,height=120) self.chosenJsFrame.pack_propagate(0) self.instrLabel = tk.Label(self.instructionFrame, text="Please select up " \ "to two remote controllers from the recognized controller list. Alter" \ "natively, scan for existing controllers and automatically add the " \ "controller to the software.", anchor=tk.W, justify=tk.LEFT, wraplength = 400) self.instrLabel.pack() self.l1 = tk.Label(self.knownJsFrame, text="Recognized Controllers") self.l1.pack() self.l2 = tk.Label(self.chosenJsFrame, text="Selected Controller/s") self.l2.pack() self.knownListbox = tk.Listbox(self.knownJsFrame, height = 15, width = 29) self.knownListbox.insert(tk.END) for item in ["PS3 PowerA", "Xbox 360 Afterglow"]: self.knownListbox.insert(tk.END, item) self.chosenListbox = tk.Listbox(self.chosenJsFrame, height = 15, width = 29) self.chosenListbox.insert(tk.END) self.closeBtn = tk.Button(self.controllerWindow, text ="Close", \ command = self.controllerWindow.destroy, width = 12) self.okBtn = tk.Button(self.controllerWindow, text ="Okay", \ width = 12) self.applyBtn = tk.Button(self.controllerWindow, text ="Apply Changes", \ width = 16) self.addBtn = tk.Button(self.controllerWindow, text ="Add", \ width = 10, command = self.addListBoxIndex) self.rmvBtn = tk.Button(self.controllerWindow, text ="Remove", \ width = 10, command = self.rmvListBoxIndex) self.scanBtn = tk.Button(self.controllerWindow, text ="Scan for controllers...", \ width = 16) self.knownListbox.pack() self.chosenListbox.pack() self.knownJsFrame.pack() self.chosenJsFrame.pack() self.instructionFrame.pack() self.k_controllerFrame.pack() self.c_controllerFrame.pack() self.closeBtn.pack() self.okBtn.pack() self.applyBtn.pack() self.addBtn.pack() self.rmvBtn.pack() self.scanBtn.pack() self.k_controllerFrame.place(x = 20, y = 85) self.c_controllerFrame.place(x = 210, y = 85) self.closeBtn.place(x = 300, y = 275) self.okBtn.place(x = 200, y = 275) self.applyBtn.place(x = 20, y = 275) self.addBtn.place(x = 40, y = 210) self.rmvBtn.place(x = 240, y = 210) self.scanBtn.place(x = 230, y = 50) def addListBoxIndex(self): self.chosenInt = 0 self.chosenInt = self.chosenListbox.size() if self.chosenInt >= 2: tkm.showerror("Error", "You can only add up to two controllers.") else: self.listBoxStr = "" self.listBoxStr = self.knownListbox.get(tk.ACTIVE) self.chosenListbox.insert(tk.END, self.listBoxStr) def rmvListBoxIndex(self): self.chosenInt = 0 self.chosenInt = self.chosenListbox.index(tk.ACTIVE) self.chosenListbox.delete(self.chosenInt) def initController(self): pygame.init() ### Tells the number of joysticks/error detection joystick_count = pygame.joystick.get_count() print ("There is ", joystick_count, "joystick/s") if joystick_count == 0: print ("Error, I did not find any joysticks") tkm.showerror("Error", "Please connect a remote controller.") else: my_joystick = pygame.joystick.Joystick(0) jsName = my_joystick.get_name print(jsName) my_joystick.init() self.js = my_joystick def stopController(self): self.js.quit() def runController(self): self.initController() while True: pygame.event.pump() axes = self.updateAxes() buttons = self.updateButtons() self.xAxisVar.set(value="xAxis is: %(xaxis)s" %{'xaxis':str(axes['X-Axis1'])}) self.yAxisVar.set(value="yAxis is: %(xaxis)s" %{'xaxis':str(axes['Y-Axis1'])}) self.aAxisVar.set(value="aAxis is: %(xaxis)s" %{'xaxis':str(axes['X-Axis2'])}) self.bAxisVar.set(value="bAxis is: %(xaxis)s" %{'xaxis':str(axes['Y-Axis2'])}) if buttons['xButton'] == 1: self.xLabel.configure(bg = 'green') elif buttons['xButton'] == 0: self.xLabel.configure(bg = 'red') if buttons['circleButton'] == 1: self.cirLabel.configure(bg = 'green') elif buttons['circleButton'] == 0: self.cirLabel.configure(bg = 'red') if buttons['triangleButton'] == 1: self.triLabel.configure(bg = 'green') elif buttons['triangleButton'] == 0: self.triLabel.configure(bg = 'red') if buttons['squareButton'] == 1: self.squLabel.configure(bg = 'green') elif buttons['squareButton'] == 0: self.squLabel.configure(bg = 'red') if buttons['leftTrigger'] == 1: self.leftTrigLabel.configure(bg = 'green') elif buttons['leftTrigger'] == 0: self.leftTrigLabel.configure(bg = 'red') if buttons['rightTrigger'] == 1: self.rightTrigLabel.configure(bg = 'green') elif buttons['rightTrigger'] == 0: self.rightTrigLabel.configure(bg = 'red') if buttons['leftBumper'] == 1: self.leftBumpLabel.configure(bg = 'green') elif buttons['leftBumper'] == 0: self.leftBumpLabel.configure(bg = 'red') if buttons['rightBumper'] == 1: self.rightBumpLabel.configure(bg = 'green') elif buttons['rightBumper'] == 0: self.rightBumpLabel.configure(bg = 'red') if buttons['selectButton'] == 1: self.selectLabel.configure(bg = 'green') elif buttons['selectButton'] == 0: self.selectLabel.configure(bg = 'red') if buttons['startButton'] == 1: self.startLabel.configure(bg = 'green') elif buttons['startButton'] == 0: self.startLabel.configure(bg = 'red') if buttons['rightToggle'] == 1: self.rightTogLabel.configure(bg = 'green') elif buttons['rightToggle'] == 0: self.rightTogLabel.configure(bg = 'red') if buttons['leftToggle'] == 1: self.leftTogLabel.configure(bg = 'green') elif buttons['leftToggle'] == 0: self.leftTogLabel.configure(bg = 'red') self.labelFrame.update() pygame.time.wait(100) def updateAxes(self): controllerDict = {'X-Axis1': 0, 'Y-Axis2': 0, 'X-Axis2': 0, 'Y-Axis2': 0}; xAxis = self.js.get_axis(0) yAxis = self.js.get_axis(1) * -1 aAxis = self.js.get_axis(2) bAxis = self.js.get_axis(3) * -1 if xAxis < 0.1 and xAxis > -0.1: xAxis = 0 if yAxis < 0.1 and yAxis > -0.1: yAxis = 0 if aAxis < 0.1 and aAxis > -0.1: aAxis = 0 if bAxis < 0.1 and bAxis > -0.1: bAxis = 0 xAxis = math.ceil(xAxis*10000)/10000 yAxis = math.ceil(yAxis*10000)/10000 aAxis = math.ceil(aAxis*10000)/10000 bAxis = math.ceil(bAxis*10000)/10000 print 'X-Axis 1: ' + str(xAxis) + ' Y-Axis 1: ' + str(yAxis) print 'X-Axis 2: ' + str(aAxis) + ' Y-Axis 2: ' + str(bAxis) controllerDict['X-Axis1'] = xAxis; controllerDict['Y-Axis1'] = yAxis; controllerDict['X-Axis2'] = aAxis; controllerDict['Y-Axis2'] = bAxis; print "dict['X-Axis1']: ", controllerDict['X-Axis1']; return controllerDict def updateButtons(self): buttonDict = {'xButton': 0, 'circleButton': 0, 'triangleButton': 0, 'squareButton': 0, 'leftBumper': 0, 'rightBumper': 0, 'leftTrigger': 0, 'rightTrigger': 0, 'selectButton': 0, 'startButton': 0, 'leftToggle': 0, 'rightToggle': 0,}; xButton = self.js.get_button(1) circleButton = self.js.get_button(2) triangleButton = self.js.get_button(3) squareButton = self.js.get_button(0) leftBumper = self.js.get_button(4) rightBumper = self.js.get_button(5) leftTrigger = self.js.get_button(6) rightTrigger = self.js.get_button(7) selectButton = self.js.get_button(8) startButton = self.js.get_button(9) leftToggle = self.js.get_button(10) rightToggle = self.js.get_button(11) print 'X Button is: ' + str(xButton) + ' Circle Button is: ' + str(circleButton) print 'Triangle Button is: ' + str(triangleButton) + ' Square Button is: ' + str(squareButton) print 'Left Bumper is: ' + str(leftBumper) + ' Right Bumper is: ' + str(rightBumper) print 'Left Trigger is: ' + str(leftTrigger) + ' Right Trigger is: ' + str(rightTrigger) print 'Select Button is: ' + str(selectButton) + ' Start Button is: ' + str(startButton) print 'Left Toggle is: ' + str(leftToggle) + ' Right Toggle is: ' + str(rightToggle) buttonDict['xButton'] = xButton; buttonDict['circleButton'] = circleButton; buttonDict['triangleButton'] = triangleButton; buttonDict['squareButton'] = squareButton; buttonDict['leftBumper'] = leftBumper; buttonDict['rightBumper'] = rightBumper; buttonDict['leftTrigger'] = leftTrigger; buttonDict['rightTrigger'] = rightTrigger; buttonDict['selectButton'] = selectButton; buttonDict['startButton'] = startButton; buttonDict['leftToggle'] = leftToggle; buttonDict['rightToggle'] = rightToggle; print "dict['xButton']: ", buttonDict['xButton']; return buttonDict
class sideWindow(AppShell): ################################################################# # sideWindow(AppShell) # This class will open a side window wich contains a scene graph and # a world setting page. ################################################################# appversion = '1.0' appname = 'Navigation Window' frameWidth = 325 frameHeight = 580 frameIniPosX = 0 frameIniPosY = 110 padx = 0 pady = 0 lightEnable = 0 ParticleEnable = 0 basedriveEnable = 0 collision = 0 backface = 0 texture = 1 wireframe = 0 enableBaseUseDrive = 0 def __init__(self, worldColor, lightEnable, ParticleEnable, basedriveEnable, collision, backface, texture, wireframe, grid, widgetVis, enableAutoCamera, parent=None, nodePath=render, **kw): self.worldColor = worldColor self.lightEnable = lightEnable self.ParticleEnable = ParticleEnable self.basedriveEnable = basedriveEnable self.collision = collision self.backface = backface self.texture = texture self.wireframe = wireframe self.grid = grid self.enableAutoCamera = enableAutoCamera self.widgetVis = widgetVis # Define the megawidget options. optiondefs = (('title', self.appname, None), ) self.defineoptions(kw, optiondefs) if parent == None: self.parent = Toplevel() else: self.parent = parent AppShell.__init__(self, self.parent) self.parent.geometry('%dx%d+%d+%d' % (self.frameWidth, self.frameHeight, self.frameIniPosX, self.frameIniPosY)) self.parent.resizable( False, False) ## Disable the ability to resize for this Window. def appInit(self): print '----SideWindow is Initialized!!' def createInterface(self): # The interior of the toplevel panel interior = self.interior() mainFrame = Frame(interior) ## Creat NoteBook self.notebookFrame = Pmw.NoteBook(mainFrame) self.notebookFrame.pack(fill=Tkinter.BOTH, expand=1) sgePage = self.notebookFrame.add('Tree Graph') envPage = self.notebookFrame.add('World Setting') self.notebookFrame['raisecommand'] = self.updateInfo ## Tree Grapgh Page self.SGE = seSceneGraphExplorer.seSceneGraphExplorer( sgePage, nodePath=render, scrolledCanvas_hull_width=270, scrolledCanvas_hull_height=570) self.SGE.pack(fill=Tkinter.BOTH, expand=0) ## World Setting Page envPage = Frame(envPage) pageFrame = Frame(envPage) self.LightingVar = IntVar() self.LightingVar.set(self.lightEnable) self.LightingButton = Checkbutton(pageFrame, text='Enable Lighting', variable=self.LightingVar, command=self.toggleLights) self.LightingButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.CollisionVar = IntVar() self.CollisionVar.set(self.collision) self.CollisionButton = Checkbutton(pageFrame, text='Show Collision Object', variable=self.CollisionVar, command=self.showCollision) self.CollisionButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.ParticleVar = IntVar() self.ParticleVar.set(self.ParticleEnable) self.ParticleButton = Checkbutton(pageFrame, text='Show Particle Dummy', variable=self.ParticleVar, command=self.enableParticle) self.ParticleButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.baseUseDriveVar = IntVar() self.baseUseDriveVar.set(self.basedriveEnable) self.baseUseDriveButton = Checkbutton(pageFrame, text='Enable base.usedrive', variable=self.baseUseDriveVar, command=self.enablebaseUseDrive) self.baseUseDriveButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.backfaceVar = IntVar() self.backfaceVar.set(self.backface) self.backfaceButton = Checkbutton(pageFrame, text='Enable BackFace', variable=self.backfaceVar, command=self.toggleBackface) self.backfaceButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.textureVar = IntVar() self.textureVar.set(self.texture) self.textureButton = Checkbutton(pageFrame, text='Enable Texture', variable=self.textureVar, command=self.toggleTexture) self.textureButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.wireframeVar = IntVar() self.wireframeVar.set(self.wireframe) self.wireframeButton = Checkbutton(pageFrame, text='Enable Wireframe', variable=self.wireframeVar, command=self.toggleWireframe) self.wireframeButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.gridVar = IntVar() self.gridVar.set(self.grid) self.gridButton = Checkbutton(pageFrame, text='Enable Grid', variable=self.gridVar, command=self.toggleGrid) self.gridButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.widgetVisVar = IntVar() self.widgetVisVar.set(self.widgetVis) self.widgetVisButton = Checkbutton(pageFrame, text='Enable WidgetVisible', variable=self.widgetVisVar, command=self.togglewidgetVis) self.widgetVisButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.enableAutoCameraVar = IntVar() self.enableAutoCameraVar.set(self.enableAutoCamera) self.enableAutoCameraButton = Checkbutton( pageFrame, text='Enable Auto Camera Movement for Loading Objects', variable=self.enableAutoCameraVar, command=self.toggleAutoCamera) self.enableAutoCameraButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.backgroundColor = ColorEntry(pageFrame, text='BG Color', value=self.worldColor) self.backgroundColor['command'] = self.setBackgroundColorVec self.backgroundColor['resetValue'] = [0, 0, 0, 0] self.backgroundColor.pack(side=Tkinter.LEFT, expand=False) self.bind(self.backgroundColor, 'Set background color') pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) envPage.pack(expand=False) ## Set all stuff done self.notebookFrame.setnaturalsize() mainFrame.pack(fill='both', expand=1) def createMenuBar(self): # We don't need menu bar here. self.menuBar.destroy() def onDestroy(self, event): ################################################################# # onDestroy(self, event) # This function will be called when user closed the side window. # Here we will send out a message with whole data set we will need # for the next time user open the side window. ################################################################# messenger.send('SW_close', [ self.worldColor, self.lightEnable, self.ParticleEnable, self.basedriveEnable, self.collision, self.backface, self.texture, self.wireframe, self.grid, self.widgetVis, self.enableAutoCamera ]) ''' If you have open any thing, please rewrite here! ''' pass ############################### def updateInfo(self, page='Tree Graph'): ################################################################# # updateInfo(self, page = 'Tree Graph') # This function will be called when each time user change the main # page of the window. # What it dose is to call right function to restore the data for current selected page. ################################################################# if page == 'Tree Graph': self.updateTreeGraph() elif page == 'World Setting': self.updateWorldSetting() def updateTreeGraph(self): ################################################################# # updateTreeGraph(self) # When scene graoh page has been opend, call sceneGraphExplorer to # updata the tree. ################################################################# self.SGE.update() pass def updateWorldSetting(self): ################################################################# # updateWorldSetting(self) # When world setting page has been selected, this function will # reset those check box in the page to reflect the current world setting. ################################################################# self.LightingVar.set(self.lightEnable) self.CollisionVar.set(self.collision) self.ParticleVar.set(self.ParticleEnable) self.baseUseDriveVar.set(self.basedriveEnable) self.backgroundColor.set(value=self.worldColor) pass def toggleLights(self): ################################################################# # toggleLights(self) # send out a message to let sceneEditor know we need to toggle the light. # Then, sceneEditor will pass the message to dataHolder to disable/enable # the lights. (lightManager is inside the dataHolder) ################################################################# self.lightEnable = (self.lightEnable + 1) % 2 messenger.send('SW_lightToggle') pass def showCollision(self): ################################################################# # showCollision(self) # This function will send out a message to sceneEditor to toggle # the visibility of collision objects. ################################################################# self.collision = (self.collision + 1) % 2 messenger.send('SW_collisionToggle', [self.collision]) pass def enableParticle(self): ################################################################# # enableParticle(self) # This function will send out a message to sceneEditor to toggle # the visibility of particle objects. ################################################################# self.ParticleEnable = (self.ParticleEnable + 1) % 2 messenger.send('SW_particleToggle', [self.ParticleEnable]) pass def enablebaseUseDrive(self): ################################################################# # enablebaseUseDrive(self) # This function will toggle the usage of base.useDrive. # Well, it may not usefull at all. # # We won't send out any message in this time to notice # the sceneEditor this event happend. # In the other hand, we will restore it back when # the side window has been closed. # ################################################################# if self.enableBaseUseDrive == 0: print 'Enabled' base.useDrive() self.enableBaseUseDrive = 1 else: print 'disabled' #base.useTrackball() base.disableMouse() self.enableBaseUseDrive = 0 self.basedriveEnable = (self.basedriveEnable + 1) % 2 pass def toggleBackface(self): ################################################################# # toggleBackface(self) # This function will toggle the back face setting. so it will # render the polygon with two sides. ################################################################# base.toggleBackface() self.backface = (self.backface + 1) % 2 return def toggleBackfaceFromMainW(self): ################################################################# # toggleBackfaceFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the back face setting in the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.backface = (self.backface + 1) % 2 self.backfaceButton.toggle() return def toggleTexture(self): ################################################################# # toggleTexture(self) # This function will toggle the txture using option for the whole scene. ################################################################# base.toggleTexture() self.texture = (self.texture + 1) % 2 return def toggleTextureFromMainW(self): ################################################################# # toggleTextureFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the texture usage from the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.texture = (self.texture + 1) % 2 self.textureButton.toggle() return def toggleWireframe(self): ################################################################# # toggleWireframe(self) # This function will toggle the wire frame mode. ################################################################# base.toggleWireframe() self.wireframe = (self.wireframe + 1) % 2 return def toggleWireframeFromMainW(self): ################################################################# # toggleWireframeFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the wire frame mode in the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.wireframe = (self.wireframe + 1) % 2 self.wireframeButton.toggle() return def toggleGrid(self): ################################################################# # toggleGrid(self) # This function will toggle the usage of the grid. ################################################################# self.grid = (self.grid + 1) % 2 if self.grid == 1: SEditor.grid.enable() else: SEditor.grid.disable() def togglewidgetVis(self): ################################################################# # togglewidgetVis(self) # This function will toggle the visibility of the widget of the grid. ################################################################# self.widgetVis = (self.widgetVis + 1) % 2 SEditor.toggleWidgetVis() if SEditor.widget.fActive: messenger.send('shift-f') return def toggleWidgetVisFromMainW(self): ################################################################# # toggleWidgetVisFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the visibility of widgets ('v') from the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.widgetVis = (self.widgetVis + 1) % 2 self.widgetVisButton.toggle() return def setBackgroundColorVec(self, color): ################################################################# # setBackgroundColorVec(self,color) # Call back function # This will be called from the colorEntry on the world setting page. # The "color" here is a list containing three integer data, R, G and B. ################################################################# base.setBackgroundColor(color[0] / 255.0, color[1] / 255.0, color[2] / 255.0) self.worldColor = [color[0], color[1], color[2], 0] def toggleAutoCamera(self): ################################################################# # toggleAutoCamera(self) # This function will toggle the usage of the auto-camera movement # when user loaded model or actor into the scene. ################################################################# self.enableAutoCamera = (self.enableAutoCamera + 1) % 2 SEditor.toggleAutoCamera() return def selectPage(self, page='Tree Graph'): ################################################################# ################################################################# self.notebookFrame.selectpage(page)
width_text, height_text = draw.textsize(text) draw.text((text_x, text_y), text, fill="white") photoimage = ImageTk.PhotoImage(image) Label(root, image=photoimage).place(x=0,y=0) entry_pady = 7 Entry(root, background="white").place(x=text_x, y=text_y + height_text +entry_pady) ################################################### # Another example toplevel = Toplevel(root) toplevel.resizable(width=False, height=False) image_file = io.BytesIO(base64.b64decode(BASE64_BACKGROUND)) image = Image.open(image_file) photoimage2 = ImageTk.PhotoImage(image) canvas = Canvas(toplevel,width=width, height=height) canvas.create_image((0,0), image=photoimage2, anchor="nw") canvas.create_text((text_x, text_y), text=text, fill="white", anchor="nw") canvas.pack() entry = Entry(canvas, background="white") canvas.create_window((text_x, text_y + height_text +entry_pady), window=entry, anchor="nw") root.mainloop()
class sideWindow(AppShell): ################################################################# # sideWindow(AppShell) # This class will open a side window wich contains a scene graph and # a world setting page. ################################################################# appversion = '1.0' appname = 'Navigation Window' frameWidth = 325 frameHeight = 580 frameIniPosX = 0 frameIniPosY = 110 padx = 0 pady = 0 lightEnable = 0 ParticleEnable = 0 basedriveEnable = 0 collision = 0 backface = 0 texture = 1 wireframe = 0 enableBaseUseDrive = 0 def __init__(self, worldColor,lightEnable,ParticleEnable, basedriveEnable,collision, backface, texture, wireframe, grid, widgetVis, enableAutoCamera, parent = None, nodePath = render, **kw): self.worldColor = worldColor self.lightEnable = lightEnable self.ParticleEnable = ParticleEnable self.basedriveEnable = basedriveEnable self.collision = collision self.backface = backface self.texture = texture self.wireframe = wireframe self.grid = grid self.enableAutoCamera = enableAutoCamera self.widgetVis = widgetVis # Define the megawidget options. optiondefs = ( ('title', self.appname, None), ) self.defineoptions(kw, optiondefs) if parent == None: self.parent = Toplevel() else: self.parent = parent AppShell.__init__(self, self.parent) self.parent.geometry('%dx%d+%d+%d' % (self.frameWidth, self.frameHeight,self.frameIniPosX,self.frameIniPosY)) self.parent.resizable(False,False) ## Disable the ability to resize for this Window. def appInit(self): print '----SideWindow is Initialized!!' def createInterface(self): # The interior of the toplevel panel interior = self.interior() mainFrame = Frame(interior) ## Creat NoteBook self.notebookFrame = Pmw.NoteBook(mainFrame) self.notebookFrame.pack(fill=Tkinter.BOTH,expand=1) sgePage = self.notebookFrame.add('Tree Graph') envPage = self.notebookFrame.add('World Setting') self.notebookFrame['raisecommand'] = self.updateInfo ## Tree Grapgh Page self.SGE = seSceneGraphExplorer.seSceneGraphExplorer( sgePage, nodePath = render, scrolledCanvas_hull_width = 270, scrolledCanvas_hull_height = 570) self.SGE.pack(fill = Tkinter.BOTH, expand = 0) ## World Setting Page envPage = Frame(envPage) pageFrame = Frame(envPage) self.LightingVar = IntVar() self.LightingVar.set(self.lightEnable) self.LightingButton = Checkbutton( pageFrame, text = 'Enable Lighting', variable = self.LightingVar, command = self.toggleLights) self.LightingButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.CollisionVar = IntVar() self.CollisionVar.set(self.collision) self.CollisionButton = Checkbutton( pageFrame, text = 'Show Collision Object', variable = self.CollisionVar, command = self.showCollision) self.CollisionButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.ParticleVar = IntVar() self.ParticleVar.set(self.ParticleEnable) self.ParticleButton = Checkbutton( pageFrame, text = 'Show Particle Dummy', variable = self.ParticleVar, command = self.enableParticle) self.ParticleButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.baseUseDriveVar = IntVar() self.baseUseDriveVar.set(self.basedriveEnable) self.baseUseDriveButton = Checkbutton( pageFrame, text = 'Enable base.usedrive', variable = self.baseUseDriveVar, command = self.enablebaseUseDrive) self.baseUseDriveButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.backfaceVar = IntVar() self.backfaceVar.set(self.backface) self.backfaceButton = Checkbutton( pageFrame, text = 'Enable BackFace', variable = self.backfaceVar, command = self.toggleBackface) self.backfaceButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.textureVar = IntVar() self.textureVar.set(self.texture) self.textureButton = Checkbutton( pageFrame, text = 'Enable Texture', variable = self.textureVar, command = self.toggleTexture) self.textureButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.wireframeVar = IntVar() self.wireframeVar.set(self.wireframe) self.wireframeButton = Checkbutton( pageFrame, text = 'Enable Wireframe', variable = self.wireframeVar, command = self.toggleWireframe) self.wireframeButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.gridVar = IntVar() self.gridVar.set(self.grid) self.gridButton = Checkbutton( pageFrame, text = 'Enable Grid', variable = self.gridVar, command = self.toggleGrid) self.gridButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.widgetVisVar = IntVar() self.widgetVisVar.set(self.widgetVis) self.widgetVisButton = Checkbutton( pageFrame, text = 'Enable WidgetVisible', variable = self.widgetVisVar, command = self.togglewidgetVis) self.widgetVisButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.enableAutoCameraVar = IntVar() self.enableAutoCameraVar.set(self.enableAutoCamera) self.enableAutoCameraButton = Checkbutton( pageFrame, text = 'Enable Auto Camera Movement for Loading Objects', variable = self.enableAutoCameraVar, command = self.toggleAutoCamera) self.enableAutoCameraButton.pack(side=Tkinter.LEFT, expand=False) pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) pageFrame = Frame(envPage) self.backgroundColor = ColorEntry( pageFrame, text = 'BG Color', value=self.worldColor) self.backgroundColor['command'] = self.setBackgroundColorVec self.backgroundColor['resetValue'] = [0,0,0,0] self.backgroundColor.pack(side=Tkinter.LEFT, expand=False) self.bind(self.backgroundColor, 'Set background color') pageFrame.pack(side=Tkinter.TOP, fill=Tkinter.X, expand=True) envPage.pack(expand=False) ## Set all stuff done self.notebookFrame.setnaturalsize() mainFrame.pack(fill = 'both', expand = 1) def createMenuBar(self): # We don't need menu bar here. self.menuBar.destroy() def onDestroy(self, event): ################################################################# # onDestroy(self, event) # This function will be called when user closed the side window. # Here we will send out a message with whole data set we will need # for the next time user open the side window. ################################################################# messenger.send('SW_close',[self.worldColor, self.lightEnable, self.ParticleEnable, self.basedriveEnable, self.collision, self.backface, self.texture, self.wireframe, self.grid, self.widgetVis, self.enableAutoCamera]) ''' If you have open any thing, please rewrite here! ''' pass ############################### def updateInfo(self, page = 'Tree Graph'): ################################################################# # updateInfo(self, page = 'Tree Graph') # This function will be called when each time user change the main # page of the window. # What it dose is to call right function to restore the data for current selected page. ################################################################# if page=='Tree Graph': self.updateTreeGraph() elif page == 'World Setting': self.updateWorldSetting() def updateTreeGraph(self): ################################################################# # updateTreeGraph(self) # When scene graoh page has been opend, call sceneGraphExplorer to # updata the tree. ################################################################# self.SGE.update() pass def updateWorldSetting(self): ################################################################# # updateWorldSetting(self) # When world setting page has been selected, this function will # reset those check box in the page to reflect the current world setting. ################################################################# self.LightingVar.set(self.lightEnable) self.CollisionVar.set(self.collision) self.ParticleVar.set(self.ParticleEnable) self.baseUseDriveVar.set(self.basedriveEnable) self.backgroundColor.set(value = self.worldColor) pass def toggleLights(self): ################################################################# # toggleLights(self) # send out a message to let sceneEditor know we need to toggle the light. # Then, sceneEditor will pass the message to dataHolder to disable/enable # the lights. (lightManager is inside the dataHolder) ################################################################# self.lightEnable = (self.lightEnable+1)%2 messenger.send('SW_lightToggle') pass def showCollision(self): ################################################################# # showCollision(self) # This function will send out a message to sceneEditor to toggle # the visibility of collision objects. ################################################################# self.collision = (self.collision+1)%2 messenger.send('SW_collisionToggle', [self.collision]) pass def enableParticle(self): ################################################################# # enableParticle(self) # This function will send out a message to sceneEditor to toggle # the visibility of particle objects. ################################################################# self.ParticleEnable = (self.ParticleEnable+1)%2 messenger.send('SW_particleToggle', [self.ParticleEnable]) pass def enablebaseUseDrive(self): ################################################################# # enablebaseUseDrive(self) # This function will toggle the usage of base.useDrive. # Well, it may not usefull at all. # # We won't send out any message in this time to notice # the sceneEditor this event happend. # In the other hand, we will restore it back when # the side window has been closed. # ################################################################# if self.enableBaseUseDrive==0: print 'Enabled' base.useDrive() self.enableBaseUseDrive = 1 else: print 'disabled' #base.useTrackball() base.disableMouse() self.enableBaseUseDrive = 0 self.basedriveEnable = (self.basedriveEnable+1)%2 pass def toggleBackface(self): ################################################################# # toggleBackface(self) # This function will toggle the back face setting. so it will # render the polygon with two sides. ################################################################# base.toggleBackface() self.backface = (self.backface+1)%2 return def toggleBackfaceFromMainW(self): ################################################################# # toggleBackfaceFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the back face setting in the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.backface = (self.backface+1)%2 self.backfaceButton.toggle() return def toggleTexture(self): ################################################################# # toggleTexture(self) # This function will toggle the txture using option for the whole scene. ################################################################# base.toggleTexture() self.texture = (self.texture+1)%2 return def toggleTextureFromMainW(self): ################################################################# # toggleTextureFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the texture usage from the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.texture = (self.texture+1)%2 self.textureButton.toggle() return def toggleWireframe(self): ################################################################# # toggleWireframe(self) # This function will toggle the wire frame mode. ################################################################# base.toggleWireframe() self.wireframe = (self.wireframe+1)%2 return def toggleWireframeFromMainW(self): ################################################################# # toggleWireframeFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the wire frame mode in the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.wireframe = (self.wireframe+1)%2 self.wireframeButton.toggle() return def toggleGrid(self): ################################################################# # toggleGrid(self) # This function will toggle the usage of the grid. ################################################################# self.grid = (self.grid+1)%2 if self.grid==1: SEditor.grid.enable() else: SEditor.grid.disable() def togglewidgetVis(self): ################################################################# # togglewidgetVis(self) # This function will toggle the visibility of the widget of the grid. ################################################################# self.widgetVis = (self.widgetVis+1)%2 SEditor.toggleWidgetVis() if SEditor.widget.fActive: messenger.send('shift-f') return def toggleWidgetVisFromMainW(self): ################################################################# # toggleWidgetVisFromMainW(self) # This function is called by sceneEditor when user used hot key # to toggle the visibility of widgets ('v') from the main panda window. # In here we will only reset the flag and reset the state of # check box ################################################################# self.widgetVis = (self.widgetVis+1)%2 self.widgetVisButton.toggle() return def setBackgroundColorVec(self,color): ################################################################# # setBackgroundColorVec(self,color) # Call back function # This will be called from the colorEntry on the world setting page. # The "color" here is a list containing three integer data, R, G and B. ################################################################# base.setBackgroundColor(color[0]/255.0, color[1]/255.0, color[2]/255.0) self.worldColor = [color[0],color[1],color[2],0] def toggleAutoCamera(self): ################################################################# # toggleAutoCamera(self) # This function will toggle the usage of the auto-camera movement # when user loaded model or actor into the scene. ################################################################# self.enableAutoCamera = (self.enableAutoCamera+1)%2 SEditor.toggleAutoCamera() return def selectPage(self,page='Tree Graph'): ################################################################# ################################################################# self.notebookFrame.selectpage(page)
def showOne(self): Ventana2 = Toplevel(self.master) try: Ventana2.configure(height=210, width=428, bg="#FFFFFF") Ventana2.resizable(1, 1) Ventana2.title("Buscar") frameAux = Frame(Ventana2, height=210, width=428, bg="#4a4a4a") frameAux.place(x=0, y=0) if sys.platform.startswith('win32'): r = "image\\BuscarBosch.png" ruta = "image\\Back.png" ruta2 = "image\\SearchOne.png" elif sys.platform.startswith('linux') or sys.platform.startswith( 'darwin'): r = "image/BuscarBosch.png" ruta = "image/Back.png" ruta2 = "image/SearchOne.png" l = Image.open(r) re = ImageTk.PhotoImage(l) labelFont = Label(frameAux, image=re, borderwidth=0) labelFont.image = re labelFont.place(x=0, y=0) labelText1 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Serie", fg="#FFFFFF", anchor=W) labelText1.config(font=("Tahoma", 11)) labelText1.place(x=15, y=25) labelText11 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText11.config(font=("Tahoma", 11)) labelText11.place(x=210, y=25) labelText2 = Label(frameAux, height=1, width=24, bg="#696969", text="Gravedad", fg="#FFFFFF", anchor=W) labelText2.config(font=("Tahoma", 11)) labelText2.place(x=15, y=50) labelText22 = Label(frameAux, height=1, width=24, bg="#696969", fg="#FFFFFF", anchor=W) labelText22.config(font=("Tahoma", 11)) labelText22.place(x=210, y=50) labelText3 = Label(frameAux, height=1, width=24, bg="#4a4a4a", text="Fecha", fg="#FFFFFF", anchor=W) labelText3.config(font=("Tahoma", 11)) labelText3.place(x=15, y=75) labelText33 = Label(frameAux, height=1, width=24, bg="#4a4a4a", fg="#FFFFFF", anchor=W) labelText33.config(font=("Tahoma", 11)) labelText33.place(x=210, y=75) labell = Label(frameAux, height=1, width=25, bg="#4a4a4a", text="Ingresa el numero de serie", fg="#FFFFFF", anchor=W) #labell.place(x=15,y=135) labell.config(font=("Tahoma", 11)) listbox3 = Entry(frameAux, width=24, justify=RIGHT, bg="#696969", fg="#FFFFFF", borderwidth=0) listbox3.place(x=210, y=125) listbox3.config(font=("Tahoma", 11)) load = Image.open(ruta) render = ImageTk.PhotoImage(load) backbutton = Button( frameAux, image=render, bg="#8d8e8c", borderwidth=0, activebackground="#696969", command=lambda: self.Switch(self.master, Ventana2)) backbutton.image = render backbutton.place(x=245, y=155) load2 = Image.open(ruta2) render2 = ImageTk.PhotoImage(load2) searchButton = Button( frameAux, image=render2, bg="#8d8e8c", borderwidth=0, activebackground="#c4c4c4", command=lambda: self.load1(listbox3, labelText11, labelText22, labelText33)) searchButton.image = render2 searchButton.place(x=324, y=155) except Exception as e: print(e) Ventana2.destroy() self.Error("Se produjo un error al cargar")
class 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()