def create_footer(self, parent_frame): footer = Frame(parent_frame) disclaimer = Message( footer, text=self.config.disclaimer_text, anchor=CENTER ) disclaimer.grid(row=0, pady=2) parent_frame.bind( "<Configure>", lambda e: disclaimer.configure(width=e.width - 20) ) if self.config.requirement_link_text: requirement_link = Text( footer, height=1, bg=disclaimer.cget("bg"), relief=FLAT, font=disclaimer.cget("font"), ) requirement_link.tag_configure("center", justify="center") hyperlinks = HyperlinkManager(requirement_link) requirement_link.insert(INSERT, "Validating: ") requirement_link.insert( INSERT, self.config.requirement_link_text, hyperlinks.add(self.open_requirements), ) requirement_link.tag_add("center", "1.0", "end") requirement_link.config(state=DISABLED) requirement_link.grid(row=1, pady=2) ToolTip(requirement_link, self.config.requirement_link_url) footer.grid_columnconfigure(0, weight=1) footer.pack(fill=BOTH, expand=True) return footer
def print_classes(self): rowOffset = 0 label = tk.Label(self.frm, text="Grain Classes:") label.grid(row=rowOffset, column=1) for k in sorted(self.classesDict.keys()): rowOffset += 1 classDescr = "" for grain in self.classesDict[k]: classDescr = classDescr + "\n" + grain classMsg = Message(self.frm, text=classDescr, width=100) classMsg.grid(column=1, row=rowOffset) #print("GRAIN_COLS:") #print(GRAIN_COLS) b_accept = tk.Button(self.frm, text='Accept') b_accept['command'] = self.accept b_accept.grid(row=rowOffset + 1, column=1) if len(self.remaining_grains) == 0: b_accept.config(state=NORMAL) self.b_remaining.config(state=DISABLED) self.b_add.config(state=DISABLED) else: b_accept.config(state=DISABLED) if len(self.classesDict) == 0: self.b_reset.config(state=DISABLED) else: self.b_reset.config(state=NORMAL)
def printFiles(self): for pdf in self.PDFs: self.jobCounter = ghostscript("\"T:\RELEASED_FILES\CURRENT_PDF\\"+pdf.replace("\"","")+"\"", self.jobCounter, self.selectedPrinter.get(), self.selectedPaper.get(),self.POPENFile) #print (jobCounter) if self.print_wrong_revision_var.get(): for pdf in self.wrongRevsion: self.jobCounter = ghostscript("\"T:\RELEASED_FILES\CURRENT_PDF\\"+pdf.replace("\"","")+"\"", self.jobCounter, self.selectedPrinter.get(), self.selectedPaper.get(),self.POPENFile) #os.remove(self.POPENFile) posx = 500 posy = 400 sizex = 500 sizey = 100 top = Toplevel() top.title("Done") top.grid_rowconfigure(0,weigh=1) top.grid_columnconfigure(0, weight=1) top.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) msg = Message(top, text="Sent all files to printer.\nPlease wait for the printer to finish", width=200, pady=10) msg.grid(row=0, column=0, columnspan=4) top.focus_force() self.current_window = top if self.runningInFrozen: top.iconbitmap(sys._MEIPASS+r"/emblem_print.ico") else: top.iconbitmap("emblem_print.ico") top.bind("<FocusOut>", self.Alarm) button = Button(top,text="Ok", command=top.quit) button.grid(row=1, column=0)
def initUI(self, server): self.parent.title("TrackWise Service Manager") self.pack(fill=BOTH, expand = True, padx = 300) # self.centerWindow() menubar = Menu(self.parent) self.parent.config(menu = menubar) fileMenu = Menu(menubar) fileMenu.add_command(label = "Exit", command = self.onExit) menubar.add_cascade(label = "File", menu = fileMenu) svcsMenu = Menu(menubar) svcsMenu.add_command(label = "List Service Status", command = self.onStatus) svcsMenu.add_command(label = "Stop Services", command = self.onStop) svcsMenu.add_command(label = "Start Services", command = self.onStart) menubar.add_cascade(label = "Services", menu = svcsMenu) # svcs = ['TrackWise Tomcat', 'Web Services Tomcat', 'QMD Tomcat', 'Keystone Intake', 'ID Intake', 'TWC'] svcs = server.getservices() hostname = server.gethostname().strip() servertype = server.gettype().strip() frame0 = Labelframe(self, text = "Server Details", borderwidth = 1) frame0.grid(column = 0, row = 0, sticky = W) so = StringVar() svroverview = Message(frame0, textvariable = so, anchor = W, width = 300) svroverview.grid(column = 0, row = 0) sstr = "Server: {}\n".format(hostname) sstr += "Server Type: {}".format(servertype) so.set(sstr) frame1 = Labelframe(self, text = "Service Status", borderwidth = 1) frame1.grid(column = 0, row = 1, sticky = W) l = StringVar() label1 = Message(frame1, textvariable = l , anchor = W) svcscount = 0 lstr = "" for i in svcs: svcscount += 1 lstr += '{} - '.format(i) + ('UP\n' if svcscount % 2 else 'DOWN\n') l.set(lstr) label1.pack(side=TOP, padx = 5, pady = 5) frame4 = Frame(self, relief=RAISED, borderwidth = 1) frame4.grid(column = 0, row = 2, sticky = W) closeButton = Button(frame4, text="Close", command = self.quit) closeButton.grid(column = 0, row = 0) okButton = Button(frame4, text = "OK") okButton.grid(column = 1, row = 0)
def main(self): """ Method name: main. Method use: The program starts the main GUI of the Rating System. """ try: self.IS.destroy() except: pass try: self.EM.destroy() except: pass self.MF = Frame(self.master) self.MF.pack() WelcomeLabel = Label(self.MF, text="Choose who you are ?", font=("Arial", 20)) WelcomeLabel.grid(column=1, columnspan=2) label = Label(self.MF, text=" ") label.grid(row=2, columnspan=2) ISButton = Button(self.MF, text="Intern", command=self.internWindow) ISButton.grid(row=3, column=1) EMButton = Button(self.MF, text="Employee", command=self.employeeWindow) EMButton.grid(row=3, column=2) contentText = "\n\nWhat is this?\nThis app lets us to rate Interns through the FLO blockchain .\n\nThis is a zero knowledge application.\n\nHow to work ?\n\n Choose if you are an Intern or Employeer\n\n" + "An Intern's work would be to enter the Transaction id in the given field and get rating\n\nAn Empolyee must enter the transaction address and write all the intern data to it " Context = Message(self.MF, text=contentText) Context.grid(column=1, columnspan=2)
def print_classes(self): frm = Frame(self) frm.grid(column=2, row=1, rowspan=20, sticky=(N, E, W, S)) rowOffset = 0 label = Label(self, text="Grain Classes:") label.grid(row=rowOffset, column=2) for k in sorted(self.classesDict.keys()): rowOffset += 1 classDescr = "" + k + ":" for grain in self.classesDict[k]: classDescr = classDescr + "\n" + grain classMsg = Message(frm, text=classDescr) #, width=100) classMsg.grid(column=0, row=rowOffset, sticky=(N, W)) #print("GRAIN_COLS:") #print(GRAIN_COLS) self.window.calc.cclasses_changed(self.classesDict) if len(self.remaining_grains) == 0: #self.b_accept.config(state = NORMAL) self.b_remaining.config(state=DISABLED) self.b_add.config(state=DISABLED) else: self.b_add.config(state=NORMAL) self.b_remaining.config(state=NORMAL) #self.b_accept.config(state = DISABLED) if len(self.classesDict) == 0: self.b_reset.config(state=DISABLED) else: self.b_reset.config(state=NORMAL)
def __init__(self): # create the window window = Tk() window.title("Widget Demo") # create the first frame frame1 = Frame(window) frame1.pack() # create variables for buttons and create the buttons self.v1 = IntVar() cbtBold = Checkbutton(frame1, text="Bold", variable=self.v1, command=self.processCheckbutton) self.v2 = IntVar() rbRed = Radiobutton(frame1, text="Red", bg="red", variable=self.v2, value=1, command=self.processRadiobutton) rbYellow = Radiobutton(frame1, text="Yellow", bg="yellow", variable=self.v2, value=2, command=self.processRadiobutton) # set the buttons in the frame cbtBold.grid(row=1, column=1) rbRed.grid(row=1, column=2) rbYellow.grid(row=1, column=3) # create the second frame frame2 = Frame(window) frame2.pack() # create labels and entry and button and message label = Label(frame2, text="Enter Your Name: ") self.name = StringVar() entryName = Entry(frame2, textvariable=self.name) btGetName = Button(frame2, text="Get Name", command=self.processButton) message = Message(frame2, text="This is the Message Widget") # position what we just made label.grid(row=1, column=1) entryName.grid(row=1, column=2) btGetName.grid(row=1, column=3) message.grid(row=1, column=4) # create a text window and add text to it text = Text(window) text.pack() text.insert(END, "Tip\nThe Best way to learn tkinter is to read ") text.insert(END, "these carefully designed examples and use them ") text.insert(END, "to create your application") window.mainloop()
def initUI(self): self.master.title("Annotator") # self.grid(row=0, column=0, sticky='news') # self.rowconfigure(0, weight=1) # self.columnconfigure(0, weight=1) self.pack(fill=BOTH, expand=True) self.columnconfigure(0, weight=1) self.columnconfigure(11, pad=10) for i in range(10): self.rowconfigure(i, weight=1) # for i in range(20): # self.columnconfigure(i, weight=1) # Title: row = 0 titleMessage = Message(self, text="Annotator", **self.headMessagesOption) titleMessage.grid(row=row, column=11, sticky='ewn') row += 1 # Description: w1 = Message(self, text=self.toolDescription, width=200, font='Arial 8') w1.grid(sticky="n", row=row, column=11, pady=4) row += 1 # Task description: if self.taskDescription is not None: titleMessage = Message(self, text="Task description", **self.headMessagesOption) titleMessage.grid(row=row, column=11, sticky='ewn') row += 1 w1 = Message(self, text=self.taskDescription, width=200, font='Arial 8') w1.grid(sticky="n", row=row, column=11, pady=4) row += 1 # Labels: self.labelFrameRow = row row += 1 # Control head: browsingMessage = Message(self, text="Browsing", **self.headMessagesOption) browsingMessage.grid(row=row, column=11, sticky='ewn') row += 1 # We make buttons: subFrame = Frame(self) subFrame.columnconfigure(0, weight=1) subFrame.columnconfigure(1, weight=1) subFrame.rowconfigure(0, weight=1) subFrame.grid(row=row, column=11, sticky="new") previousButton = Button(subFrame, text="<<", command=self.left) previousButton.grid(row=0, column=0, sticky="new") nextButton = Button(subFrame, text=">>", command=self.right) nextButton.grid(row=0, column=1, sticky="new") row += 1
def aviso_aguarde_instalando(self, recente): """ Realizando a atualização """ if self.tp_atualizacao is not None: self.tp_atualizacao.destroy() self.tp_atualizacao = Toplevel(None) self.tp_atualizacao.withdraw() self.tp_atualizacao.focus_force() self.tp_atualizacao.resizable(False, False) self.tp_atualizacao.tk.call('wm', 'iconphoto', self.tp_atualizacao._w, self.icon) self.tp_atualizacao.configure( self.design.dic["aviso_versao_top_level"]) self.tp_atualizacao.grid_columnconfigure(1, weight=1) self.tp_atualizacao.title('Atualizando.... Não feche a Safira!') #try: # self.tp_atualizacao.wm_attributes('-type', 'splash') #except Exception as erro: # print("Erro ao remover barra de titulos => ", erro) fr_atualizaca = Frame(self.tp_atualizacao) lb_versao_dev = Label(fr_atualizaca, text='{:^30}'.format('Aguarde Atualizando!')) lb_versao_tex = Message(fr_atualizaca, text=' ' * 50, width=200) fr_botoes = Frame(fr_atualizaca) bt_atualiza = Button(fr_botoes) fr_atualizaca.configure(self.design.dic["aviso_versao_fr_atualizacao"]) lb_versao_dev.configure(self.design.dic["aviso_versao_lb_dev"]) lb_versao_tex.configure(self.design.dic["aviso_versao_ms"]) fr_botoes.configure(self.design.dic["aviso_versao_btn"]) bt_atualiza.configure(self.design.dic["aviso_versao_btn_atualiza"], relief=FLAT) fr_atualizaca.grid_columnconfigure(1, weight=1) fr_botoes.grid_columnconfigure(1, weight=1) fr_botoes.grid_columnconfigure(2, weight=1) fr_atualizaca.grid(row=1, column=1, sticky=NSEW) lb_versao_dev.grid(row=1, column=1) lb_versao_tex.grid(row=2, column=1, sticky=NSEW) fr_botoes.grid(row=3, column=1, sticky=NSEW) j_width = self.tp_atualizacao.winfo_reqwidth() j_height = self.tp_atualizacao.winfo_reqheight() t_width = self.tela.winfo_screenwidth() t_heigth = self.tela.winfo_screenheight() self.tp_atualizacao.geometry("+{}+{}".format( int(t_width / 2) - int(j_width / 2), int(t_heigth / 2) - int(j_height / 2))) self.tp_atualizacao.deiconify() self.tp_atualizacao.update() th = Thread( target=lambda ver=recente, lb=lb_versao_tex, bt_at=bt_atualiza, lb_2=lb_versao_dev: self.aplica_versao(ver, lb, bt_at, lb_2)) th.start()
def initTextFrame(self, texts): # We init the frame: if self.textFrame is not None: self.textFrame.destroy() self.textFrame = Frame(self) self.textFrame.grid(row=0, column=0, columnspan=10, rowspan=10, padx=5, pady=0, sticky="news") self.textFrame.rowconfigure(0, weight=0) self.textFrame.rowconfigure(1, weight=1) # For each text: if not isinstance(texts, list): texts = [texts] nbColumns = len(texts) for i in range(nbColumns): self.textFrame.columnconfigure(i, weight=1) current = texts[i] try: # We add the head message: if dictContains(current, "title"): headMessage = Message(self.textFrame, text=tkStripExtra(current["title"]), **self.headMessagesOption) headMessage.grid(row=0, column=i, sticky='nwe', padx=2, pady=0) # We create the area for the text: textAreaFrame = Frame(self.textFrame) textAreaFrame.columnconfigure(0, weight=1) textAreaFrame.rowconfigure(0, weight=1) textAreaRow = 1 textAreaRowspan = 1 if not dictContains(current, "title"): textAreaRow = 0 textAreaRowspan = 2 textAreaFrame.grid(row=textAreaRow, rowspan=textAreaRowspan, column=i, sticky="news", padx=0) # We create the Text widget in: textWidget = Text(textAreaFrame) textWidget.grid(row=0, column=0, sticky="news") textWidget.insert(INSERT, tkStripExtra(current["text"])) textWidget.config(state=DISABLED) # We make the scroll bar: scrollBar = Scrollbar(textAreaFrame, command=textWidget.yview) scrollBar.grid(row=0, column=1, sticky="nse") textWidget['yscrollcommand'] = scrollBar.set except Exception as e: logException(e, self)
class OptimusGui(): def __init__(self, master): self.master = master master.title("Optimus Manager Gui") self.warning_label = Label( master, text= "changing graphics configuration requires this to be run as root!") self.warning_label.grid(row=2, column=1, columnspan=3) self.status_output = Message(master, text="getting status...") self.status_output.grid(columnspan=2, row=1, column=1) self.intel_button = Button(master, text="use intel graphics", command=lambda: self.swapGraphics("intel")) self.intel_button.grid(row=3, column=1) self.hybrid_button = Button( master, text="use hybrid graphics", command=lambda: self.swapGraphics("hybrid")) self.hybrid_button.grid(row=3, column=2) self.nvidia_button = Button( master, text="use nvidia graphics", command=lambda: self.swapGraphics("nvidia")) self.nvidia_button.grid(row=3, column=3) self.quit_button = Button(master, text="quit", command=master.quit) self.quit_button.grid(row=4, column=3) self.updateStatus() def swapGraphics(self, swap_val): if swap_val == "intel": # print("swapping to intel!") subprocess.run(["nvidia-optimus-manager", "configure", "intel"]) elif swap_val == "hybrid": # print("swapping to hybrid!") subprocess.run(["nvidia-optimus-manager", "configure", "hybrid"]) elif swap_val == "nvidia": # print("swapping to nvidia!") subprocess.run(["nvidia-optimus-manager", "configure", "nvidia"]) else: print("invalid argument for swapGraphics!") self.updateStatus() def updateStatus(self): print("updating status!") output = subprocess.check_output(["nvidia-optimus-manager", "status"], encoding="ascii") self.status_output.configure(text=output)
class Scroller(object): """ Scrolls through a solution list. """ def __init__(self, wdw, sols): """ Stores the list of solutions in sols and defines the layout of the GUI. """ wdw.title('solutions scroller') self.sols = sols self.cursor = 0 self.lbl = Label(wdw, text="solution : ") self.lbl.grid(row=0, column=0, sticky=E) self.ent = Entry(wdw) self.ent.grid(row=0, column=1, stick=W) self.ent.insert(INSERT, "0 of %d" % len(sols)) self.myft = Font(family="Courier New", size=12, weight="normal") self.mlen = self.myft.measure("M") lines = sols[0].split('\n') self.width = max([len(line) for line in lines]) self.display = StringVar() self.display.set(self.sols[0]) self.mess = Message(wdw, textvariable=self.display, \ font=self.myft, width=self.width*self.mlen, background='white') self.mess.grid(row=1, column=0, columnspan=2) self.btnext = Button(wdw, command=self.next, text='next') self.btnext.grid(row=2, column=1, sticky=W+E) self.btprev = Button(wdw, command=self.previous, text='previous') self.btprev.grid(row=2, column=0, sticky=W+E) def show(self): """ Shows the solution at position self.cursor in the message widget and updates the entry widget. """ self.display.set(self.sols[self.cursor]) self.ent.delete(0, END) self.ent.insert(INSERT, '%d of %d' % (self.cursor, len(self.sols))) def next(self): """ Increases the cursor by one if possible. """ if self.cursor < len(self.sols) - 1: self.cursor = self.cursor + 1 self.show() def previous(self): """ Decreases the cursor by one if possible. """ if self.cursor > 0: self.cursor = self.cursor - 1 self.show()
class Scroller(object): """ Scrolls through a solution list. """ def __init__(self, wdw, sols): """ Stores the list of solutions in sols and defines the layout of the GUI. """ wdw.title('solutions scroller') self.sols = sols self.cursor = 0 self.lbl = Label(wdw, text="solution : ") self.lbl.grid(row=0, column=0, sticky=E) self.ent = Entry(wdw) self.ent.grid(row=0, column=1, stick=W) self.ent.insert(INSERT, "0 of %d" % len(sols)) self.myft = Font(family="Courier New", size=12, weight="normal") self.mlen = self.myft.measure("M") lines = sols[0].split('\n') self.width = max([len(line) for line in lines]) self.display = StringVar() self.display.set(self.sols[0]) self.mess = Message(wdw, textvariable=self.display, \ font=self.myft, width=self.width*self.mlen, background='white') self.mess.grid(row=1, column=0, columnspan=2) self.btnext = Button(wdw, command=self.next, text='next') self.btnext.grid(row=2, column=1, sticky=W + E) self.btprev = Button(wdw, command=self.previous, text='previous') self.btprev.grid(row=2, column=0, sticky=W + E) def show(self): """ Shows the solution at position self.cursor in the message widget and updates the entry widget. """ self.display.set(self.sols[self.cursor]) self.ent.delete(0, END) self.ent.insert(INSERT, '%d of %d' % (self.cursor, len(self.sols))) def next(self): """ Increases the cursor by one if possible. """ if self.cursor < len(self.sols) - 1: self.cursor = self.cursor + 1 self.show() def previous(self): """ Decreases the cursor by one if possible. """ if self.cursor > 0: self.cursor = self.cursor - 1 self.show()
def _create_header(self): """Create the header elements: - message showing who is logged in - 'Log out' button.""" username = self.food_service.get_user().get_username() logged_in_label = Message(master=self._frame, text=f"You are logged in, {username}!") logged_in_label.grid(row=0, column=1, padx=5, pady=5) logout_button = self._create_logout_button() logout_button.grid(row=0, column=2, padx=5, pady=5)
def checkSettingsBeforePrint(self): if self.selectedPrinter.get() != '' and self.PDFs != None : printingThread = threading.Thread(target=self.printFiles) printingThread.start() else: if self.selectedPrinter.get() == '': posx = 500 posy = 400 sizex = 500 sizey = 100 top = Toplevel() top.grid_rowconfigure(0,weigh=1) top.grid_columnconfigure(0, weight=1) top.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) top.title("Printer not set") msg = Message(top, text="Set the default printer in\nPrinter Settings.",width=200, pady=10) msg.grid(row=0, column=0,columnspan=5) button = Button(top,text="Ok", command=top.destroy) button.grid(row=1, column=0) self.current_window = top if self.runningInFrozen: top.iconbitmap(sys._MEIPASS+r"/emblem_print.ico") else: top.iconbitmap("emblem_print.ico") top.focus_force() top.bind("<FocusOut>", self.Alarm) return None elif self.PDFs == None: posx = 500 posy = 400 sizex = 500 sizey = 100 top = Toplevel() top.grid_rowconfigure(0,weigh=1) top.grid_columnconfigure(0, weight=1) top.wm_geometry("%dx%d+%d+%d" % (sizex, sizey, posx, posy)) top.title("No file loaded") msg = Message(top, text="Browse for a file before printing.",width=200, pady=10) msg.grid(row=0, column=0,columnspan=5) button = Button(top,text="Ok", command=top.destroy) button.grid(row=1, column=0) self.current_window = top if self.runningInFrozen: top.iconbitmap(sys._MEIPASS+r"/emblem_print.ico") else: top.iconbitmap("emblem_print.ico") top.focus_force() top.bind("<FocusOut>", self.Alarm) return None
def big_yes_no(title, message): messagebox = Toplevel() messagebox.title(title) m = Message(messagebox, text=message, padx=100, pady=100) m.config(font=('TkDefaultFont', 20)) m.grid(row=0, column=1) yes = Button(messagebox, text='Yes', command=lambda x=messagebox: destroy(1, x)) yes.config(font=('TkDefaultFont', 20)) yes.grid(row=1, column=0) no = Button(messagebox, text='No', command=lambda x=messagebox: destroy(0, x)) no.config(font=('TkDefaultFont', 20)) no.grid(row=1, column=2)
def display_about(self): """Display About Window.""" # General About Window Settings about_window = Tk() about_window.title("About") about_text = ("IEEEUMich Roster Updater is a tool aimed to automate " "or at least alleviate the pain of manually adding new " "members to our email roster on MCommunity.\n\n" "This tool was created by Shuta Suzuki ([email protected])" ".\n\n" "Last Updated: 4/7/2018\n\n" "You can click 'OK' to close this window." ) # About Text Content about_label = Message(about_window, text=about_text, font=("Arial", 16), width=500) about_label.grid(row=0, column=0, padx=50, pady=(50, 0)) # OK Button ok_button = Button(about_window, text="OK", command=about_window.destroy) ok_button.grid(row=1, column=0, pady=(50, 50))
def nouvelle_parti(self): """Fonction qui démarre la partie et ferme la fenêtre. """ if self.nom_joueur1 == "" or self.nom_joueur2.get() == "": w = Message(self, text="SVP veuillez ajouter le nom des joueurs 1 et 2", width=300) w.grid(row=6, column=1, columnspan=6) else: list_joueur = [] est_joker = self.joker_d_as.get() for i in range(0, len(self.master.de_buttom)): self.master.de_buttom[i].config(state="normal") self.master.list_obj_joueur = [] if (self.nom_joueur3.get() == ""): self.master.frame_player3.destroy() list_joueur.append(self.nom_joueur1.get()) list_joueur.append(self.nom_joueur2.get()) else: list_joueur.append(self.nom_joueur1.get()) list_joueur.append(self.nom_joueur2.get()) list_joueur.append(self.nom_joueur3.get()) for i in list_joueur: joueur = Joueur(i, self.master, est_joker) self.master.list_obj_joueur.append(joueur) self.master.partie = Partie(self.master.list_obj_joueur, self.master) self.grab_release() self.master.focus_set() self.destroy() self.master.blancer.config(state="normal") self.master.tour.config(state="disabled") self.master.partie.jouer_partie() self.master.tour.config(state="normal") self.master.blancer.config(state="disabled") for i in self.master.de_buttom: i.config(state="disabled")
def buscar_BD_Fecha(error=False): def buscarFecha(event): diaS = dia.get() mesS = mes.get() anhoS = anho.get() if (len(diaS.strip()) == 0 or len(mesS.strip()) == 0 or len(anhoS.strip()) == 0): v.destroy() buscar_BD_Fecha(True) else: v.destroy() encontrarFecha(diaS + "/" + mesS + "/" + anhoS) v = Toplevel() lb = Label(v, text="Introduzca el dia (dd)") lb.grid(row=0, column=0) dia = Entry(v, width=2) dia.bind("<Return>", buscarFecha) dia.grid(row=0, column=1) lb = Label(v, text="Introduzca el mes (MM)") lb.grid(row=1, column=0) mes = Entry(v, width=2) mes.bind("<Return>", buscarFecha) mes.grid(row=1, column=1) lb = Label(v, text="Introduzca el anyo (yyyy)") lb.grid(row=2, column=0) anho = Entry(v, width=4) anho.bind("<Return>", buscarFecha) anho.grid(row=2, column=1) if (error): var = StringVar() #Mirar si cambiar Message por Label label = Message(v, textvariable=var, relief=FLAT, fg='red') var.set("Rellena los campos perro") label.grid(row=3, column=0)
def run_btn_click(): # grab things from the text entry field user_entry = textEntry.get() # define something, just like normal window new_label = Label(root, text=f'Calling python script {user_entry}.py') # show the label new_label.grid() # assigns the imported module based on the user entry into the text field module_to_call = sys.modules[user_entry] # assigns the main method as the method to use, allowing the script to run in the terminal method_to_call = getattr(module_to_call, 'main') # display picture if calling apod raw_data = method_to_call() program_answer = Message(root, text=raw_data) if user_entry == 'apod': im = Image.open(io.BytesIO(raw_data)) image = ImageTk.PhotoImage(im) label1 = Label(root, image=image) label1.grid(column=3) # need to keep a local reference to the image or it breaks images.append(image) else: program_answer.grid(column=3)
def __init__(self): win = Tk() win.title("日志文件解析器") frame1 = Frame(win) frame1.pack() self.data_from = StringVar() self.data_To =StringVar() self.status = StringVar() # 文件来源选择框 entry_from = Entry(frame1,textvariable=self.data_from) mess_f = Message(frame1,text="文件读取路径") entry_to =Entry(frame1,textvariable=self.data_To) mess_t = Message(frame1,text="文件写入路径") self.setTatus_1() mess_s = Message(frame1,textvariable=self.status) button_f = Button(frame1,text="readPath",command=self.read_Path) button_to = Button(frame1,text="WritePath",command=self.write_Path) button_st = Button(frame1,text="Start_Operation",command=self.start_operation) # 设置位置 mess_f.grid(row=2,column=1,columnspan=2) entry_from.grid(row=2,column=3,columnspan=2) button_f.grid(row=2,column=5,columnspan=2) mess_t.grid(row=3,column=1,columnspan=2) entry_to.grid(row=3,column=3,columnspan=2) button_to.grid(row=3,column=5,columnspan=2) mess_s.grid(row=4,rowspan=2,column=3) button_st.grid(row=6,column=3) # 填充 newM = Message(frame1) newM.grid(row=7,rowspan=2) win.mainloop()
class DemoClient(Frame): def __init__(self, tk, args): Frame.__init__(self, tk) locale.setlocale(locale.LC_ALL, '') # empty string for platform's default settings self.master = tk self.config = json.load(open('config.json', 'r')) self.config['COMBOBOX_INDEX'] = sorted(self.config['COMBOBOX_INDEX'], key=lambda x: x[0]) self.game_type = int( args.gametype ) if args.gametype else self.config["DEFAULT_GAME_TYPE_ID"] tk.title(self.config["APP_TITLE"]) tk.resizable(False, False) self.get_icon() atexit.register(self.cancel_game) # Init class data fields that we use for storing info that we need for using the API self.bot_id = None self.bot_password = None self.logged_in = False self.game_style_ids = [] self.gameChips = 0 self.gameDeals = 0 self.gameStake = 0 self.gamePrize = 0 self.player_key = None self.play_again = BooleanVar() self.do_not_play_same_user = BooleanVar() self.close_after_game = False self.game_cancelled = False self.in_game = False self.topFrame = Frame(tk, padx=12, pady=12) self.middleFrame = Frame(tk, padx=12) self.middleFrameLeft = Frame(self.middleFrame) self.middleFrameRight = Frame(self.middleFrame) self.middleFrameRighter = Frame(self.middleFrame) self.topFrame.grid(row=0, sticky=W + E) self.middleFrame.grid(row=1, sticky=W) self.middleFrameLeft.grid(row=1, column=0) self.middleFrameRight.grid(row=1, column=1) self.middleFrameRighter.grid(row=1, column=2) # =================================== # Create form elements # Top Frame Elements self.botNameLabel = Label(self.topFrame, text="Bot Name:") self.bot_id_entry = Entry(self.topFrame) self.bot_id_entry.bind('<Return>', self.log_in_if_not) self.bot_id_entry.focus() self.passwordLabel = Label(self.topFrame, text="Password:"******"Login", command=self.log_in_out_clicked) self.balanceLabel = Label(self.topFrame, text="Bot Balance:") self.balance = Label(self.topFrame, text="0") self.close_button = Button(self.topFrame, text="Close", padx=2, command=tk.destroy) # Middle Frame Elements # Middle Frame LEFT Elements self.gameTypeCmb = ttk.Combobox( self.middleFrameLeft, state="disabled", values=tuple((game[0]) for game in self.config['COMBOBOX_INDEX'])) if self.game_type != self.config['NULL_GAME_TYPE_ID']: index = [ i for i in range(len(self.config['COMBOBOX_INDEX'])) if self.config['COMBOBOX_INDEX'][i][1] == self.game_type ][0] self.gameTypeCmb.current( index) # Default selection matches default game type id self.gameTypeCmb.bind("<<ComboboxSelected>>", self.game_type_selected) self.gameStyleLabel = Label(self.middleFrameLeft, font=(None, 18), pady=0, text="Game Style Selection") self.opponentLabel = Label(self.middleFrameLeft, text="Specify Opponent (optional):") self.specify_opponent_cmb = ttk.Combobox( self.middleFrameLeft, values=self.config['AVAILABLE_OPPONENTS']) self.do_not_play_same_user_check = Checkbutton( self.middleFrameLeft, text='Don\'t play another bot in same user account as me', var=self.do_not_play_same_user) self.game_styles_listbox = Listbox(self.middleFrameLeft, background='#FFFFFF', height=8) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind( '<Return>', self.find_game_double_clicked ) # Not a double click but we want it to do the same thing self.refresh_game_styles_button = Button( self.middleFrameLeft, text="Refresh Game Styles", command=self.refresh_game_styles_clicked) self.thinkingTimeLabel = Label(self.middleFrameLeft, text="Add \"Thinking Time\" (ms):") self.thinking_time_entry = Entry(self.middleFrameLeft) self.auto_play_next_game_check = Checkbutton( self.middleFrameLeft, text='Play another game when complete', var=self.play_again) self.cancel_stop_game_button = Button( self.middleFrameLeft, text=CANCEL_GAME_TEXT, command=self.cancel_stop_game_clicked) self.find_game_button = Button(self.middleFrameLeft, text="Find Game", command=self.find_game_clicked) self.resultText = Message( self.middleFrameLeft, width=300, text="This is where the informational messages will appear") self.spacerLabel = Label(self.middleFrameLeft, text=" ") # Middle Frame RIGHT Elements self.gameTitleLabel = Label(self.middleFrameRight, text="Game Title") self.gameTitleText = Text(self.middleFrameRight, height=3, background='white', spacing1=3, pady=0) self.player = None # Initialise as none before updating in create_visuals() self.opponent = None # Initialise as none before updating in create_visuals() self.create_visuals() self.gameActionLabel = Label(self.middleFrameRight, text="") # =================================== # Set initial element states self.set_gamestyle_controls_states(DISABLED) self.cancel_stop_game_button.config(state=DISABLED) self.game_styles_listbox.config(background='white') self.thinking_time_entry.insert(0, 100) self.gameTitleText.config(state=DISABLED) self.set_balance(0) self.gameTitleText.tag_configure("center", justify='center') self.gameTitleText.tag_configure("bold", font='-weight bold') # =================================== # Form Layout # Top Frame Form Layout self.topFrame.grid_rowconfigure(0, weight=1) self.botNameLabel.grid(row=0, column=0, sticky=E) self.bot_id_entry.grid(row=0, column=1, sticky=W) self.passwordLabel.grid(row=0, column=2, sticky=E) self.bot_password_entry.grid(row=0, column=3, sticky=W) self.log_in_out_button.grid(row=0, column=4, sticky=E) self.topFrame.grid_columnconfigure(5, weight=1) self.balanceLabel.grid(row=0, column=5, sticky=E) self.balance.grid(row=0, column=6, sticky=W) self.close_button.grid(row=0, column=7, sticky=E, padx=(50, 0)) # Middle Frame Form Layout self.middleFrame.grid_rowconfigure(0, weight=1) self.gameTypeCmb.grid(row=0, column=0, columnspan=1, sticky=W + E) self.gameStyleLabel.grid(row=1, column=0, columnspan=1, sticky=W + E) self.spacerLabel.grid(row=1, column=2, sticky=E) self.opponentLabel.grid(row=2, column=0, sticky=W, pady=4) self.specify_opponent_cmb.grid(row=2, column=0, sticky=E, pady=4) self.do_not_play_same_user_check.grid(row=3, column=0, columnspan=1, sticky='we', pady=4) self.game_styles_listbox.grid(row=4, column=0, columnspan=1, sticky='we', pady=4) self.find_game_button.grid(row=5, column=0, pady=4, sticky=W) self.refresh_game_styles_button.grid(row=5, column=0, columnspan=1, sticky='', pady=4) self.cancel_stop_game_button.grid(row=5, column=0, sticky=E) self.thinkingTimeLabel.grid(row=6, column=0, sticky=W, pady=4) self.thinking_time_entry.grid(row=6, column=0, sticky=E, pady=4) self.auto_play_next_game_check.grid(row=7, column=0, columnspan=1, sticky=W, pady=4) self.resultText.grid(row=9, column=0, columnspan=2, sticky=W, pady=4) self.middleFrame.grid_columnconfigure(9, weight=1) self.gameTitleLabel.grid(row=0, column=3) self.gameTitleText.grid(row=0, column=3, columnspan=2) self.gameActionLabel.grid(row=11, column=3, sticky='w') if args.botid is not None and args.password is not None: self.auto_play(args) def auto_play(self, args): self.bot_id_entry.insert(0, args.botid) self.bot_password_entry.insert(0, args.password) self.log_in_out_clicked() self.thinking_time_entry.insert(0, args.timeout) if args.playanothergame: self.auto_play_next_game_check.select() if args.dontplaysameuserbot: self.do_not_play_same_user_check.select() if args.closeaftergame: self.close_after_game = True if args.gamestyle is not None: i = 0 for i in range(self.game_styles_listbox.size()): if args.gamestyle in str(self.game_styles_listbox.get(i)): break self.game_styles_listbox.select_set(i, i) self.find_game_clicked() def log_in_out_clicked(self): """Click handler for the 'Login'/'Logout' button.""" # This means we're logging out if self.logged_in: self.resultText.config(text='Logged Out') self.master.title(self.config["APP_TITLE"] + " (Not Logged In)") self.cancel_game() self.bot_id = None self.bot_password = None self.clear_game_title_text() self.gameActionLabel.config(text="") self.reset_game_styles_listbox() self.clear_all_boards() self.opponent.delete("all") self.log_in_out_button.config(text='Login') self.set_login_controls_states(ENABLED) self.set_gamestyle_controls_states(DISABLED) self.gameTypeCmb.config(state="disabled") self.logged_in = False self.bot_password_entry.delete(0, 'end') self.set_balance(0) # This means we're logging in else: self.bot_id = self.bot_id_entry.get() self.bot_password = self.bot_password_entry.get() res = self.get_list_of_game_styles() if res['Result'] == 'SUCCESS': self.resultText.config(text='Logged In') game_styles = res['GameStyles'] self.master.title(self.bot_id + " - " + self.config["APP_TITLE"]) self.set_login_controls_states(DISABLED) self.set_gamestyle_controls_states(ENABLED) self.gameTypeCmb.config(state="readonly") self.set_game_styles_listbox(game_styles) self.set_balance(res['Balance']) self.log_in_out_button.config(text='Logout') self.logged_in = True else: messagebox.showerror( 'Error', 'Invalid login attempt. Please check the username and password entered.' ) def log_in_if_not(self, _): if not self.logged_in: self.log_in_out_clicked() def clear_all_boards(self): self.player.clear_board() self.opponent.clear_board() self.player.delete("all") self.opponent.delete("all") self.player.myBoard = None self.opponent.oppBoard = None def set_in_game(self, value): self.in_game = value def set_game_title_text(self, text, tag): self.gameTitleText.config(state=ENABLED) self.gameTitleText.insert("end", text, ("center", tag)) self.gameTitleText.config(state=DISABLED) def clear_game_title_text(self): self.gameTitleText.config(state=ENABLED) self.gameTitleText.delete("1.0", "end") self.gameTitleText.config(state=DISABLED) def set_login_controls_states(self, state): self.bot_id_entry.config(state=state) self.bot_password_entry.config(state=state) def set_gamestyle_controls_states(self, state): self.specify_opponent_cmb.config(state=state) self.do_not_play_same_user_check.config(state=state) self.game_styles_listbox.config(state=state) self.find_game_button.config(state=state) self.refresh_game_styles_button.config(state=state) self.auto_play_next_game_check.config(state=state) self.thinking_time_entry.config(state=state) self.opponentLabel.config(state=state) self.thinkingTimeLabel.config(state=state) self.balanceLabel.config(state=state) self.balance.config(state=state) self.gameStyleLabel.config(state=state) self.game_styles_listbox.config(state=state) self.player.config(state=state) self.opponent.config(state=state) def set_balance(self, balance): """Set the balance field""" self.balance['text'] = int_with_commas(balance) def get_list_of_game_styles(self): """Get list of game styles from the server.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'GameTypeId': self.game_type } url = self.config["BASE_URL"] + self.config[ "GET_LIST_OF_GAME_STYLES_EXTENSION"] return DemoClient.make_api_call(url, req) def set_game_styles_listbox(self, game_styles): """Set the content of the game styles listbox with a list of GameStyle dictionaries. Keyword Arguments: game_styles -- The list of GameStyle dictionaries, this should be obtained through get_list_of_game_styles(). """ self.reset_game_styles_listbox() for index, game_style in enumerate(game_styles): if self.game_type == self.config["BATTLESHIPS_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["BATTLESHIPS_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Ships'], game_style['GameTypeSpecificInfo']['Board Size'], game_style['GameTypeSpecificInfo']['Timeout ms'], game_style['GameTypeSpecificInfo']['DealsTotal'], game_style['GameTypeSpecificInfo']['PercentageLand'], game_style['GameTypeSpecificInfo']['RandomLand'])) elif self.game_type == self.config[ "NOUGHTS_AND_CROSSES_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["NOUGHTS_AND_CROSSES_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['DealsTotal'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config[ "TRAVELLING_SALESDRONE_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self. config["TRAVELLING_SALESDRONE_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['TotalCities'], game_style['GameTypeSpecificInfo']['DealLength'])) elif self.game_type == self.config["PREDICTIVE_TEXT_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self. config["PREDICTIVE_TEXT_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo'] ['Number of Sentences'], game_style['GameTypeSpecificInfo'] ['Switched Words Game'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["TWIST_CUBE_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["TWIST_CUBE_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['cubeSize'], game_style['GameTypeSpecificInfo']['GameLength'])) elif self.game_type == self.config["SLIDING_PUZZLE_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["SLIDING_PUZZLE_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['RowSize'], game_style['GameTypeSpecificInfo']['ColumnSize'], game_style['GameTypeSpecificInfo']['TimeLimit'])) elif self.game_type == self.config["BLURRY_WORD_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["BLURRY_WORD_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['NumImages'], game_style['GameTypeSpecificInfo']['GameLength'])) elif self.game_type == self.config["MASTERMIND_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["MASTERMIND_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['NumPegs'], game_style['GameTypeSpecificInfo']['NumColours'], game_style['GameTypeSpecificInfo'] ['DuplicatesAllowed'])) elif self.game_type == self.config[ "WAREHOUSE_LOGISTICS_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["WAREHOUSE_LOGISTICS_GAME_STYLE_LISTBOX_TEXT"]. format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo'] ['WarehouseDimensions'][0], game_style['GameTypeSpecificInfo'] ['WarehouseDimensions'][1])) elif self.game_type == self.config["FOUR_IN_A_ROW_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["FOUR_IN_A_ROW_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['Connections'])) elif self.game_type == self.config["WHO_IS_WHO_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["WHO_IS_WHO_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['NumCharacters'], game_style['GameTypeSpecificInfo']['ComparisonRound'])) elif self.game_type == self.config[ "REVERSING_STONES_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["REVERSING_STONES_GAME_STYLE_LISTBOX_TEXT"]. format(game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['Holes'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["CHECKERS_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["CHECKERS_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["GO_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["GO_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], "CAPTURE" if game_style['GameTypeSpecificInfo']['IsCaptureGo'] else game_style['GameTypeSpecificInfo']['ScoringMethod'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["LEXICO_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["LEXICO_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Dimensions'][0], game_style['GameTypeSpecificInfo']['Dimensions'][1], game_style['GameTypeSpecificInfo']['TileMultipliers'], game_style['GameTypeSpecificInfo']['Timeout ms'])) elif self.game_type == self.config["DOMINOES_GAME_TYPE_ID"]: self.game_styles_listbox.insert( index, self.config["DOMINOES_GAME_STYLE_LISTBOX_TEXT"].format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['SpotNo'], game_style['GameTypeSpecificInfo']['Timeout ms'])) else: raise ValueError('INVALID GAME TYPE PARAMETER') self.game_style_ids.append(game_style['GameStyleId']) # self.game_styles_listbox.select_set(GAME_STYLE_LISTBOX_DEFAULT_SELECTION) def reset_game_styles_listbox(self): """Clear the content of the game styles listbox.""" if self.game_styles_listbox.size() != 0: self.game_styles_listbox.delete(0, 'end') self.game_style_ids = [] def refresh_game_styles_clicked(self): """Click handler for the 'Refresh Game Styles' button.""" res = self.get_list_of_game_styles() game_styles = res['GameStyles'] self.set_game_styles_listbox(game_styles) def find_game_clicked(self): """Click handler for the 'Find Game' button""" self.find_game_button.config(state=DISABLED) self.cancel_stop_game_button.config(state=ENABLED) self.game_styles_listbox.unbind('<Double-1>') self.game_styles_listbox.unbind('<Return>') self.game_styles_listbox.config(state=DISABLED) self.clear_all_boards() # Here we dispatch the work to a separate thread, to keep the GUI responsive. if not MAC: threading.Thread(target=self.game_loop, daemon=True).start() else: self.game_loop() # Doesn't work on MACs def find_game_double_clicked(self, _): self.find_game_clicked() def game_type_selected(self, _): self.game_type = self.config["COMBOBOX_INDEX"][ self.gameTypeCmb.current()][1] res = self.get_list_of_game_styles() if res['Result'] == 'SUCCESS': game_styles = res['GameStyles'] self.set_game_styles_listbox(game_styles) self.get_icon() self.player.destroy() self.opponent.destroy() self.create_visuals() def get_icon(self): try: if WINDOWS: self.master.iconbitmap("assets/{0}/icon.ico".format( self.game_type)) else: self.master.iconbitmap("./assets/{0}/icon.xbm".format( self.game_type)) except Exception as e: print(e) def create_visuals(self): if self.game_type == self.config["NULL_GAME_TYPE_ID"]: self.player = null_visuals.NullVisuals( self.middleFrameRight) # Game Display Table self.opponent = null_visuals.NullVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["BATTLESHIPS_GAME_TYPE_ID"]: self.player = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.opponent = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["NOUGHTS_AND_CROSSES_GAME_TYPE_ID"]: self.player = noughts_and_crosses_visuals.NoughtsAndCrossesVisuals( self.middleFrameRight) # Game Display Table self.opponent = noughts_and_crosses_visuals.NoughtsAndCrossesVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config[ "TRAVELLING_SALESDRONE_GAME_TYPE_ID"]: self.player = travelling_salesdrone_visuals.TravellingSalesdroneVisuals( self.middleFrameRight) # Game Display Table self.opponent = travelling_salesdrone_visuals.TravellingSalesdroneVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["PREDICTIVE_TEXT_GAME_TYPE_ID"]: self.player = predictive_text_visuals.PredictiveTextVisuals( self.middleFrameRight) # Game Display Table self.opponent = predictive_text_visuals.PredictiveTextVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["TWIST_CUBE_GAME_TYPE_ID"]: self.player = twist_cube_visuals.TwistCubeVisuals( self.middleFrameRight) # Game Display Table self.opponent = twist_cube_visuals.TwistCubeVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["SLIDING_PUZZLE_GAME_TYPE_ID"]: self.player = sliding_puzzle_visuals.SlidingPuzzleVisuals( self.middleFrameRight) # Game Display Table self.opponent = sliding_puzzle_visuals.SlidingPuzzleVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["BLURRY_WORD_GAME_TYPE_ID"]: self.player = blurry_word_visuals.MicrosoftCognitiveChallengeVisuals( self.middleFrameRight) # Game Display Table self.opponent = blurry_word_visuals.MicrosoftCognitiveChallengeVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["MASTERMIND_GAME_TYPE_ID"]: self.player = mastermind_visuals.MastermindVisuals( self.middleFrameRight) # Game Display Table self.opponent = mastermind_visuals.MastermindVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["WAREHOUSE_LOGISTICS_GAME_TYPE_ID"]: self.player = warehouse_logistics_visuals.WarehouseLogisticsVisuals( self.middleFrameRight) # Game Display Table self.opponent = warehouse_logistics_visuals.WarehouseLogisticsVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["FOUR_IN_A_ROW_GAME_TYPE_ID"]: self.player = four_in_a_row_visuals.FourInARowVisuals( self.middleFrameRight) # Game Display Table self.opponent = four_in_a_row_visuals.FourInARowVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["WHO_IS_WHO_GAME_TYPE_ID"]: self.player = who_is_who_visuals.WhoIsWhoVisuals( self.middleFrameRight) # Game Display Table self.opponent = who_is_who_visuals.WhoIsWhoVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["REVERSING_STONES_GAME_TYPE_ID"]: self.player = reversing_stones_visuals.ReversingStonesVisuals( self.middleFrameRight) # Game Display Table self.opponent = reversing_stones_visuals.ReversingStonesVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["CHECKERS_GAME_TYPE_ID"]: self.player = checkers_visuals.CheckersVisuals( self.middleFrameRight) # Game Display Table self.opponent = checkers_visuals.CheckersVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["GO_GAME_TYPE_ID"]: self.player = go_visuals.GoVisuals( self.middleFrameRight) # Game Display Table self.opponent = go_visuals.GoVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["LEXICO_GAME_TYPE_ID"]: self.player = lexico_visuals.LexicoVisuals( self.middleFrameRight) # Game Display Table self.opponent = lexico_visuals.LexicoVisuals( self.middleFrameRight) # Game Display Table elif self.game_type == self.config["DOMINOES_GAME_TYPE_ID"]: self.player = dominoes_visuals.DominoesVisuals( self.middleFrameRight) # Game Display Table self.opponent = dominoes_visuals.DominoesVisuals( self.middleFrameRight) # Game Display Table else: raise ValueError('INVALID GAME TYPE PARAMETER') self.player.grid(row=1, column=3) self.opponent.grid(row=1, column=4) def game_loop(self): """Loop through finding and playing games.""" while True: self.clear_all_boards() mover.persistentData = {} self.find_game() self.update_balance() if self.game_cancelled: break self.play_game() self.update_balance() if self.close_after_game: self.close_button.invoke() if self.game_cancelled: break if not self.play_again.get(): break self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind('<Return>', self.find_game_double_clicked) self.game_styles_listbox.config(state=ENABLED) self.game_cancelled = False def find_game(self): """Find a game.""" offer_game_res = self.offer_game() if offer_game_res['Result'] == 'INVALID_LOGIN_OR_PASSWORD': self.cancel_stop_game_clicked() if 'ErrorMessage' in offer_game_res and offer_game_res[ 'ErrorMessage'] == 'Check of OpponentId failed': self.resultText.config(text='Invalid Opponent ID') else: self.resultText.config(text='Invalid login or password') elif offer_game_res['Result'] == 'INSUFFICIENT_BALANCE': self.cancel_stop_game_clicked() self.resultText.config(text='Insufficient balance') elif offer_game_res['Result'] == 'BOT_IS_INACTIVE': self.cancel_stop_game_clicked() self.resultText.config(text='Bot is inactive') else: self.player_key = offer_game_res['PlayerKey'] if offer_game_res['Result'] == 'WAITING_FOR_GAME': self.wait_for_game() def offer_game(self): """Offer a game.""" self.cancel_game( ) # Cancel the last outstanding game offer that was made opponent_id = self.specify_opponent_cmb.get() if len(opponent_id) == 0: opponent_id = None try: game_style_id = self.game_style_ids[int( self.game_styles_listbox.curselection()[0])] except IndexError: self.game_styles_listbox.select_set( GAME_STYLE_LISTBOX_DEFAULT_SELECTION) game_style_id = self.game_style_ids[0] req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'GameStyleId': game_style_id, 'DontPlayAgainstSameUser': self.do_not_play_same_user.get(), 'DontPlayAgainstSameBot': False, 'OpponentId': opponent_id } url = self.config["BASE_URL"] + self.config["OFFER_GAME_EXTENSION"] return DemoClient.make_api_call(url, req) def wait_for_game(self): """Wait for game to start.""" self.resultText.config(text='Waiting for game') while True: if self.game_cancelled: self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind('<Return>', self.find_game_double_clicked) self.game_styles_listbox.config(state=ENABLED) break poll_results = self.poll_for_game_state() if poll_results['Result'] == 'SUCCESS': break if poll_results['Result'] == 'INVALID_PLAYER_KEY' or poll_results[ 'Result'] == 'GAME_HAS_ENDED' or poll_results[ 'Result'] == 'GAME_WAS_STOPPED': self.game_cancelled = True time.sleep(2) def play_game(self): """Play a game.""" self.resultText.config(text='Playing game') self.in_game = True poll_results = self.poll_for_game_state() if poll_results["Result"] != "SUCCESS": return game_state = poll_results['GameState'] title = format('Game ID: ' + str(game_state['GameId'])) title += format(' / Style: ' + str(self.game_style_ids[int( self.game_styles_listbox.curselection()[0])])) title += "\n" versus = format(self.bot_id + ' vs ' + game_state['OpponentId']) self.clear_game_title_text() self.set_game_title_text(title, "") self.set_game_title_text(versus, "bold") self.middleFrame.update() while True: if self.game_cancelled: break if game_state['IsMover']: self.resultText.config(text='Playing Game - Your Turn') move = mover.calculate_move(self.game_type, game_state) move_results = self.make_move(move) if move_results['Result'] == 'INVALID_MOVE': self.resultText.config(text="Invalid Move") elif move_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + move_results['Result']) print(str(move_results)) print("Game ended") break else: game_state = move_results['GameState'] else: self.resultText.config(text="Playing Game - Opponent's Turn") # ---- Code here will be called on your opponent's turn ---- # ---------------------------------------------------------- poll_results = self.poll_for_game_state() if poll_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + poll_results['Result']) break game_state = poll_results['GameState'] if game_state['GameStatus'] != 'RUNNING': break self.middleFrameRight.update() try: if int(self.thinking_time_entry.get()) > 0: time.sleep((int(self.thinking_time_entry.get()) / 1000)) else: time.sleep(0.1) except ValueError: time.sleep(0.1) self.set_in_game(False) def make_move(self, move): """Make a move.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key, 'Move': move } url = self.config["BASE_URL"] + self.config["MAKE_MOVE_EXTENSION"] result = DemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: print(result) try: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) except Exception as e: print("Gamestate error: " + str(e)) return result def poll_for_game_state(self): """Poll the server for the latest GameState.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'PlayerKey': self.player_key } url = self.config["BASE_URL"] + self.config[ "POLL_FOR_GAME_STATE_EXTENSION"] result = DemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) return result def cancel_stop_game_clicked(self): self.game_cancelled = True self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind('<Return>', self.find_game_double_clicked) self.game_styles_listbox.config(state=ENABLED) def cancel_game(self): print("Cancelling last game offer") if self.player_key is None: return req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key } url = self.config["BASE_URL"] + self.config[ "CANCEL_GAME_OFFER_EXTENSION"] DemoClient.make_api_call(url, req) try: self.resultText.config(text='Cancelled game') except Exception as e: print(str(e) + " -- Demo client has been closed") def update_balance(self): res = self.get_list_of_game_styles() self.set_balance(res['Balance']) @staticmethod def make_api_call(url, req): """Make an API call.""" while True: try: res = requests.post(url, json=req, headers=API_CALL_HEADERS, timeout=60.0) try: jres = res.json() if 'Result' in jres: return jres time.sleep(0.1) except ValueError: time.sleep(0.1) except requests.ConnectionError: time.sleep(0.1) except requests.Timeout: time.sleep(0.1) except requests.HTTPError: time.sleep(0.1) except BaseException as e: # Bad code but needed for testing purposes print(e) time.sleep(0.1)
combo1 = Combobox(fra, values=("Apple","Orange","Melon")) combo1.grid(row=2, column=1, padx=5, pady=5) combo1.set('Apple') lab2 = Label(fra, text='Normal Widget') lab2.grid(row=2, column=0, padx=5, pady=5) ''' # try uncommenting these lines, and comment out the cb lines following combo2 = Combobox(fra, style="Custom." + tWidg, values=("Milk","Water","Juice")) combo2.grid(row=3, column=0, padx=5, pady=5) combo2.option_add('*TCombobox*Listbox.font', element_options['font']) combo2.set('Milk') # this affects all comboboxes ''' cb = CustomBox(fra, font=element_options['font'], style="Custom." + tWidg, values=("Milk","Water","Juice")) cb.grid(row=3, column=1, padx=5, pady=5) cb.set('Milk') lab3 = Label(fra, text='Widget with Style') lab3.grid(row=3, column=0, padx=5, pady=5) lab4 = Label(fra, text='Widget Layout') lab4.grid(row=4, column=0, padx=5, pady=5) mess = Message(fra, text=out, width=250) mess.grid(row=5, column=0, padx=5, pady=5) root.mainloop()
class BattleshipsDemoClient(Frame): def __init__(self, tk, args): Frame.__init__(self, tk) # empty string for platform's default settings locale.setlocale(locale.LC_ALL, '') self.master = tk tk.title(APP_TITLE) tk.resizable(False, False) try: if WINDOWS: tk.iconbitmap("200x200/icon.ico") else: tk.iconbitmap("@200x200/icon.xbm") except Exception as e: print(e) atexit.register(self.cancel_game) # Init class data fields that we use for storing info that we need for using the API self.bot_id = None self.bot_password = None self.logged_in = False self.game_style_ids = [] self.gameChips = 0 self.gameDeals = 0 self.gameStake = 0 self.gamePrize = 0 self.player_key = None self.play_again = BooleanVar() self.do_not_play_same_user = BooleanVar() self.close_after_game = False self.game_cancelled = False self.in_game = False self.topFrame = Frame(tk, padx=12, pady=12) self.middleFrame = Frame(tk, padx=12) self.middleFrameLeft = Frame(self.middleFrame) self.middleFrameRight = Frame(self.middleFrame) self.middleFrameRighter = Frame(self.middleFrame) self.topFrame.grid(row=0, sticky=W + E) self.middleFrame.grid(row=1, sticky=W) self.middleFrameLeft.grid(row=1, column=0) self.middleFrameRight.grid(row=1, column=1) self.middleFrameRighter.grid(row=1, column=2) # =================================== # Create form elements # Top Frame Elements self.botNameLabel = Label(self.topFrame, text="Bot Name:") self.bot_id_entry = Entry(self.topFrame) self.bot_id_entry.bind('<Return>', self.log_in_if_not) self.bot_id_entry.focus() self.passwordLabel = Label(self.topFrame, text="Password:"******"Login", command=self.log_in_out_clicked) self.balanceLabel = Label(self.topFrame, text="Bot Balance:") self.balance = Label(self.topFrame, text="0") self.close_button = Button(self.topFrame, text="Close", padx=2, command=tk.destroy) # Middle Frame Elements # Middle Frame LEFT Elements self.gameStyleLabel = Label(self.middleFrameLeft, font=(None, 18), pady=0, text="Game Style Selection") self.opponentLabel = Label(self.middleFrameLeft, text="Specify Opponent (optional):") self.specify_opponent_entry = Entry(self.middleFrameLeft) self.do_not_play_same_user_check = Checkbutton( self.middleFrameLeft, text='Don\'t play another bot in same user account as me', var=self.do_not_play_same_user) self.game_styles_listbox = Listbox(self.middleFrameLeft, background='#FFFFFF', height=8) self.game_styles_listbox.bind('<Double-1>', self.find_game_double_clicked) self.game_styles_listbox.bind( '<Return>', self.find_game_double_clicked ) # Not a double click but we want it to do the same thing self.refresh_game_styles_button = Button( self.middleFrameLeft, text="Refresh Game Styles", command=self.refresh_game_styles_clicked) self.thinkingTimeLabel = Label(self.middleFrameLeft, text="Add \"Thinking Time\" (ms):") self.thinking_time_entry = Entry(self.middleFrameLeft) self.auto_play_next_game_check = Checkbutton( self.middleFrameLeft, text='Play another game when complete', var=self.play_again) self.cancel_stop_game_button = Button( self.middleFrameLeft, text=CANCEL_GAME_TEXT, command=self.cancel_stop_game_clicked) self.find_game_button = Button(self.middleFrameLeft, text="Find Game", command=self.find_game_clicked) self.resultText = Message( self.middleFrameLeft, width=300, text="This is where the informational messages will appear") self.spacerLabel = Label(self.middleFrameLeft, text=" ") # Middle Frame RIGHT Elements self.gameTitleLabel = Label(self.middleFrameRight, text="Game Title") self.gameTitleText = Text(self.middleFrameRight, height=3, background='white', spacing1=3, pady=0) self.player = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.opponent = battleships_visuals.BattleshipsVisuals( self.middleFrameRight) # Game Display Table self.gameActionLabel = Label(self.middleFrameRight, text="") # =================================== # Set initial element states self.set_gamestyle_controls_states(DISABLED) self.cancel_stop_game_button.config(state=DISABLED) self.game_styles_listbox.config(background='white') self.thinking_time_entry.insert(0, 100) self.gameTitleText.config(state=DISABLED) self.set_balance(0) self.gameTitleText.tag_configure("center", justify='center') self.gameTitleText.tag_configure("bold", font='-weight bold') # =================================== # Form Layout # Top Frame Form Layout self.topFrame.grid_rowconfigure(0, weight=1) self.botNameLabel.grid(row=0, column=0, sticky=E) self.bot_id_entry.grid(row=0, column=1, sticky=W) self.passwordLabel.grid(row=0, column=2, sticky=E) self.bot_password_entry.grid(row=0, column=3, sticky=W) self.log_in_out_button.grid(row=0, column=4, sticky=E) self.topFrame.grid_columnconfigure(5, weight=1) self.balanceLabel.grid(row=0, column=5, sticky=E) self.balance.grid(row=0, column=6, sticky=W) self.close_button.grid(row=0, column=7, sticky=E, padx=(50, 0)) # Middle Frame Form Layout self.middleFrame.grid_rowconfigure(0, weight=1) self.gameStyleLabel.grid(row=0, column=0, columnspan=1, sticky=W + E) self.spacerLabel.grid(row=0, column=2, sticky=E) self.opponentLabel.grid(row=2, column=0, sticky=W, pady=4) self.specify_opponent_entry.grid(row=2, column=0, sticky=E, pady=4) self.do_not_play_same_user_check.grid(row=3, column=0, columnspan=1, sticky='we', pady=4) self.game_styles_listbox.grid(row=4, column=0, columnspan=1, sticky='we', pady=4) self.find_game_button.grid(row=5, column=0, pady=4, sticky=W) self.refresh_game_styles_button.grid(row=5, column=0, columnspan=1, sticky='', pady=4) self.cancel_stop_game_button.grid(row=5, column=0, sticky=E) self.thinkingTimeLabel.grid(row=6, column=0, sticky=W, pady=4) self.thinking_time_entry.grid(row=6, column=0, sticky=E, pady=4) self.auto_play_next_game_check.grid(row=7, column=0, columnspan=1, sticky=W, pady=4) self.resultText.grid(row=9, column=0, columnspan=2, sticky=W, pady=4) self.middleFrame.grid_columnconfigure(9, weight=1) self.gameTitleLabel.grid(row=0, column=3) self.gameTitleText.grid(row=0, column=3, columnspan=2) self.player.grid(row=1, column=3) self.opponent.grid(row=1, column=4) self.gameActionLabel.grid(row=11, column=3, sticky='w') if args.botid is not None: self.auto_play(args) def auto_play(self, args): self.bot_id_entry.insert(0, args.botid) self.bot_password_entry.insert(0, args.password) self.log_in_out_clicked() self.thinking_time_entry.insert(0, args.timeout) if args.playanothergame: self.auto_play_next_game_check.select() if args.dontplaysameuserbot: self.do_not_play_same_user_check.select() if args.closeaftergame: self.close_after_game = True i = 0 for i in range(self.game_styles_listbox.size()): if args.gamestyle in str(self.game_styles_listbox.get(i)): break self.game_styles_listbox.select_set(i, i) self.find_game_clicked() def log_in_out_clicked(self): """Click handler for the 'Login'/'Logout' button.""" # This means we're logging out if self.logged_in: self.resultText.config(text='Logged Out') self.master.title(APP_TITLE + " (Not Logged In)") self.cancel_game() self.bot_id = 'housebot-competition' self.bot_password = None self.clear_game_title_text() self.gameActionLabel.config(text="") self.reset_game_styles_listbox() self.clear_all_boards() self.opponent.delete("all") self.log_in_out_button.config(text='Login') self.set_login_controls_states(ENABLED) self.set_gamestyle_controls_states(DISABLED) self.logged_in = False self.bot_password_entry.delete(0, 'end') self.set_balance(0) # This means we're logging in else: self.bot_id = self.bot_id_entry.get() self.bot_password = '******' res = self.get_list_of_game_styles() if res['Result'] == 'SUCCESS': self.resultText.config(text='Logged In') game_styles = res['GameStyles'] self.master.title(self.bot_id + " - " + APP_TITLE) self.set_login_controls_states(DISABLED) self.set_gamestyle_controls_states(ENABLED) self.set_game_styles_listbox(game_styles) self.set_balance(res['Balance']) self.log_in_out_button.config(text='Logout') self.logged_in = True else: messagebox.showerror( 'Error', 'Invalid login attempt. Please check the username and password entered.' ) def log_in_if_not(self, _): if not self.logged_in: self.log_in_out_clicked() def clear_all_boards(self): self.player.delete("all") self.opponent.delete("all") self.player.myBoard = None self.opponent.oppBoard = None def set_in_game(self, value): self.in_game = value def set_game_title_text(self, text, tag): self.gameTitleText.config(state=ENABLED) self.gameTitleText.insert("end", text, ("center", tag)) self.gameTitleText.config(state=DISABLED) def clear_game_title_text(self): self.gameTitleText.config(state=ENABLED) self.gameTitleText.delete("1.0", "end") self.gameTitleText.config(state=DISABLED) def set_login_controls_states(self, state): self.bot_id_entry.config(state=state) self.bot_password_entry.config(state=state) def set_gamestyle_controls_states(self, state): self.specify_opponent_entry.config(state=state) self.do_not_play_same_user_check.config(state=state) self.game_styles_listbox.config(state=state) self.find_game_button.config(state=state) self.refresh_game_styles_button.config(state=state) self.auto_play_next_game_check.config(state=state) self.thinking_time_entry.config(state=state) self.opponentLabel.config(state=state) self.thinkingTimeLabel.config(state=state) self.balanceLabel.config(state=state) self.balance.config(state=state) self.gameStyleLabel.config(state=state) self.game_styles_listbox.config(state=state) self.player.config(state=state) self.opponent.config(state=state) def set_balance(self, balance): """Set the balance field""" self.balance['text'] = int_with_commas(balance) self.balance['text'] += ' sat' def get_list_of_game_styles(self): """Get list of game styles from the server.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'GameTypeId': BATTLESHIPS_GAME_TYPE_ID } url = BASE_URL + GET_LIST_OF_GAME_STYLES_EXTENSION return BattleshipsDemoClient.make_api_call(url, req) def set_game_styles_listbox(self, game_styles): """Set the content of the game styles listbox with a list of GameStyle dictionaries. Keyword Arguments: game_styles -- The list of GameStyle dictionaries, this should be obtained through get_list_of_game_styles(). """ self.reset_game_styles_listbox() for index, game_style in enumerate(game_styles): self.game_styles_listbox.insert( index, GAME_STYLE_LISTBOX_TEXT.format( game_style['GameStyleId'], game_style['Stake'], game_style['GameTypeSpecificInfo']['Ships'], game_style['GameTypeSpecificInfo']['Board Size'], game_style['GameTypeSpecificInfo']['Timeout ms'], game_style['GameTypeSpecificInfo']['DealsTotal'], game_style['GameTypeSpecificInfo']['PercentageLand'], game_style['GameTypeSpecificInfo']['RandomLand'])) self.game_style_ids.append(game_style['GameStyleId']) # self.game_styles_listbox.select_set(GAME_STYLE_LISTBOX_DEFAULT_SELECTION) def reset_game_styles_listbox(self): """Clear the content of the game styles listbox.""" if self.game_styles_listbox.size() != 0: self.game_styles_listbox.delete(0, 'end') self.game_style_ids = [] def refresh_game_styles_clicked(self): """Click handler for the 'Refresh Game Styles' button.""" res = self.get_list_of_game_styles() game_styles = res['GameStyles'] self.set_game_styles_listbox(game_styles) def find_game_clicked(self): """Click handler for the 'Find Game' button""" self.find_game_button.config(state=DISABLED) self.cancel_stop_game_button.config(state=ENABLED) self.clear_all_boards() # Here we dispatch the work to a separate thread, to keep the GUI responsive. if not MAC: threading.Thread(target=self.game_loop, daemon=True).start() else: self.game_loop() # Doesn't work on MACs def find_game_double_clicked(self, _): self.find_game_clicked() def game_loop(self): """Loop through finding and playing games.""" while True: self.clear_all_boards() self.find_game() if self.game_cancelled: break self.play_game() if self.close_after_game: self.close_button.invoke() if self.game_cancelled: break if not self.play_again.get(): break self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) self.game_cancelled = False def find_game(self): """Find a game.""" offer_game_res = self.offer_game() if offer_game_res['Result'] == 'INVALID_LOGIN_OR_PASSWORD': self.cancel_stop_game_clicked() if 'ErrorMessage' in offer_game_res and offer_game_res[ 'ErrorMessage'] == 'Check of OpponentId failed': self.resultText.config(text='Invalid Opponent ID') else: self.resultText.config(text='Invalid login or password') elif offer_game_res['Result'] == 'INSUFFICIENT_BALANCE': self.cancel_stop_game_clicked() self.resultText.config(text='Insufficient balance') elif offer_game_res['Result'] == 'BOT_IS_INACTIVE': self.cancel_stop_game_clicked() self.resultText.config(text='Bot is inactive') else: self.player_key = offer_game_res['PlayerKey'] if offer_game_res['Result'] == 'WAITING_FOR_GAME': self.wait_for_game() def offer_game(self): """Offer a game.""" opponent_id = self.specify_opponent_entry.get() if len(opponent_id) == 0: opponent_id = None try: game_style_id = self.game_style_ids[int( self.game_styles_listbox.curselection()[0])] except IndexError: self.game_styles_listbox.select_set( GAME_STYLE_LISTBOX_DEFAULT_SELECTION) game_style_id = self.game_style_ids[0] req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'GameStyleId': game_style_id, 'DontPlayAgainstSameUser': self.do_not_play_same_user.get(), 'DontPlayAgainstSameBot': False, 'OpponentId': opponent_id } url = BASE_URL + OFFER_GAME_EXTENSION return BattleshipsDemoClient.make_api_call(url, req) def wait_for_game(self): """Wait for game to start.""" self.resultText.config(text='Waiting for game') while True: if self.game_cancelled: self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) break poll_results = self.poll_for_game_state() if poll_results['Result'] == 'SUCCESS': break if poll_results['Result'] == 'INVALID_PLAYER_KEY' or poll_results[ 'Result'] == 'GAME_HAS_ENDED' or poll_results[ 'Result'] == 'GAME_WAS_STOPPED': self.game_cancelled = True time.sleep(2) def play_game(self): """Play a game.""" self.resultText.config(text='Playing game') self.in_game = True poll_results = self.poll_for_game_state() if poll_results["Result"] != "SUCCESS": return game_state = poll_results['GameState'] title = format('Game ID: ' + str(game_state['GameId'])) game_style_details = self.game_styles_listbox.get('active').split( " | ") title += format(' / Style: ' + str(self.game_style_ids[int( self.game_styles_listbox.curselection()[0])])) title += format(' / Land: ' + game_style_details[6].split(" ")[2] + '%') title += format(' / Deals: ' + game_style_details[5].split(" ")[1]) title += format(' / ' + game_style_details[7]) title += "\n" versus = format(self.bot_id + ' vs ' + game_state['OpponentId']) self.clear_game_title_text() self.set_game_title_text(title, "") self.set_game_title_text(versus, "bold") self.middleFrame.update() while True: if self.game_cancelled: break if game_state['IsMover']: self.resultText.config(text='Playing Game - Your Turn') move = battleships_move.calculateMove(game_state) move_results = self.make_move(move) if move_results['Result'] == 'INVALID_MOVE': self.resultText.config(text="Invalid Move") elif move_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + move_results['Result']) print("Game ended") break else: game_state = move_results['GameState'] else: self.resultText.config(text="Playing Game - Opponent's Turn") # ---- Code here will be called on your opponent's turn ---- # ---------------------------------------------------------- poll_results = self.poll_for_game_state() if poll_results['Result'] != 'SUCCESS': self.resultText.config(text='Game has ended: ' + poll_results['Result']) break game_state = poll_results['GameState'] if game_state['GameStatus'] != 'RUNNING': break self.middleFrameRight.update() try: if int(self.thinking_time_entry.get()) > 0: time.sleep((int(self.thinking_time_entry.get()) / 1000)) else: time.sleep(0.1) except ValueError: time.sleep(0.1) self.set_in_game(False) def make_move(self, move): """Make a move.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key, 'Move': move } url = BASE_URL + MAKE_MOVE_EXTENSION result = BattleshipsDemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: print(result) try: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) except Exception as e: print("Gamestate error: " + str(e)) return result def poll_for_game_state(self): """Poll the server for the latest GameState.""" req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'MaximumWaitTime': 1000, 'PlayerKey': self.player_key } url = BASE_URL + POLL_FOR_GAME_STATE_EXTENSION result = BattleshipsDemoClient.make_api_call(url, req) if result['Result'] == 'SUCCESS' or "GAME_HAS_ENDED" in result[ 'Result']: self.player.draw_game_state(result['GameState'], True) self.opponent.draw_game_state(result['GameState'], False) return result def cancel_stop_game_clicked(self): self.game_cancelled = True self.cancel_game() self.find_game_button.config(state=ENABLED) self.cancel_stop_game_button.config(state=DISABLED, text=CANCEL_GAME_TEXT) def cancel_game(self): if self.player_key is None: return req = { 'BotId': self.bot_id, 'BotPassword': self.bot_password, 'PlayerKey': self.player_key } url = BASE_URL + CANCEL_GAME_OFFER_EXTENSION BattleshipsDemoClient.make_api_call(url, req) try: self.resultText.config(text='Cancelled game') except Exception as e: print(str(e) + " -- resultText Message object no longer exists") @staticmethod def make_api_call(url, req): """Make an API call.""" while True: try: res = requests.post(url, json=req, headers=API_CALL_HEADERS, timeout=60.0) try: jres = res.json() if 'Result' in jres: return jres time.sleep(0.1) except ValueError: time.sleep(0.1) except requests.ConnectionError: time.sleep(0.1) except requests.Timeout: time.sleep(0.1) except requests.HTTPError: time.sleep(0.1) except BaseException as e: # Bad code but needed for testing purposes print(e) time.sleep(0.1)
class Wt_Select_Dialog(_Dialog): def body(self, master): dialogframe = Frame(master, width=446, height=152) self.dialogframe = dialogframe dialogframe.pack() self.make_Button_1(self.dialogframe) # edit below self.make_Button_2(self.dialogframe) # edit below self.make_Button_3(self.dialogframe) # edit below self.make_Button_4(self.dialogframe) # edit below self.make_Button_5(self.dialogframe) # edit below self.make_Button_6(self.dialogframe) # edit below self.make_Frame_1(self.dialogframe) # edit below self.make_Label_1(self.dialogframe) # edit below self.make_Message_1(self.dialogframe) # edit below self.make_Message_2(self.dialogframe) # edit below self.make_Message_3(self.dialogframe) # edit below self.make_Label_2(self.Frame_1) # edit below self.make_Spinbox_1(self.Frame_1) # edit below def make_Button_1(self, frame): self.Button_1 = Button(frame, text="1", width="6") self.Button_1.grid(row=3, column=1) self.Button_1.bind("<ButtonRelease-1>", self.Button_1_Click) def make_Button_2(self, frame): self.Button_2 = Button(frame, text="2", width="6") self.Button_2.grid(row=3, column=2) self.Button_2.bind("<ButtonRelease-1>", self.Button_2_Click) def make_Button_3(self, frame): self.Button_3 = Button(frame, text="3", width="6") self.Button_3.grid(row=3, column=3) self.Button_3.bind("<ButtonRelease-1>", self.Button_3_Click) def make_Button_4(self, frame): self.Button_4 = Button(frame, text="4", width="6") self.Button_4.grid(row=3, column=4) self.Button_4.bind("<ButtonRelease-1>", self.Button_4_Click) def make_Button_5(self, frame): self.Button_5 = Button(frame, text="5", width="6") self.Button_5.grid(row=3, column=5) self.Button_5.bind("<ButtonRelease-1>", self.Button_5_Click) def make_Button_6(self, frame): self.Button_6 = Button(frame, text="0", width="6") self.Button_6.grid(row=3, column=0) self.Button_6.bind("<ButtonRelease-1>", self.Button_6_Click) def make_Frame_1(self, frame): self.Frame_1 = Frame(frame, width="60", height="50") self.Frame_1.grid(row=5, column=0, columnspan="6") def make_Label_1(self, frame): self.Label_1 = Label(frame, text="Select Weight for %s" % self.label_text, width="40", font="Times\ New\ Roman 14 bold roman") self.Label_1.grid(row=1, column=0, columnspan="6") def make_Message_1(self, frame): self.Message_1 = Message( frame, text= "Weight affects how widgets expand and contract on window resize.", width="400") self.Message_1.grid(row=6, column=0, columnspan="6") def make_Message_2(self, frame): self.Message_2 = Message( frame, text= "Each widget will still need to set the sticky property (e.g. ns, ew, nsew)", width="400") self.Message_2.grid(row=7, column=0, columnspan="6") def make_Message_3(self, frame): self.Message_3 = Message( frame, width="400", text="Use numbered \"Quick-Set\" buttons or set Spinbox and hit OK." ) self.Message_3.grid(row=2, column=0, columnspan="6") def make_Label_2(self, frame): self.Label_2 = Label(frame, text="Select any Value", width="15") self.Label_2.grid(row=2, column=1) def make_Spinbox_1(self, frame): self.Spinbox_1 = Spinbox(frame, to="100", text="Spinbox_1", width="10", from_="1", font="Courier\ New 14 normal roman") self.Spinbox_1.grid(row=2, column=2) self.Spinbox_1_StringVar = StringVar() self.Spinbox_1.configure(textvariable=self.Spinbox_1_StringVar, to="10", from_="1") self.Spinbox_1_StringVar.set("6") self.Spinbox_1_StringVar_traceName = self.Spinbox_1_StringVar.trace_variable( "w", self.Spinbox_1_StringVar_Callback) def Button_1_Click(self, event): #bind method for component ID=Button_1 self.Spinbox_1_StringVar.set("1") self.ok() def Button_2_Click(self, event): #bind method for component ID=Button_2 self.Spinbox_1_StringVar.set("2") self.ok() def Button_3_Click(self, event): #bind method for component ID=Button_3 self.Spinbox_1_StringVar.set("3") self.ok() def Button_4_Click(self, event): #bind method for component ID=Button_4 self.Spinbox_1_StringVar.set("4") self.ok() def Button_5_Click(self, event): #bind method for component ID=Button_5 self.Spinbox_1_StringVar.set("5") self.ok() def Button_6_Click(self, event): #bind method for component ID=Button_6 self.Spinbox_1_StringVar.set("0") self.ok() def Spinbox_1_StringVar_Callback(self, varName, index, mode): pass def validate(self): self.result = {} # return a dictionary of results self.result["weight"] = self.Spinbox_1_StringVar.get() return 1 def apply(self): pass
"""Message Widow. Stand-alone example from Tk Assistant. stevepython.wordpress.com""" from tkinter import Message, Tk root = Tk() root.title('Message window example') msg_text = 'Whoever invented auto-correct ' \ 'should burn in hello.' msg = Message(root, text=msg_text) msg.config(bg='springgreen', font=('verdant', 24, 'italic')) msg.grid() root.mainloop()
combo1 = Combobox(fra, values=("Apple", "Orange", "Melon")) combo1.grid(row=2, column=1, padx=5, pady=5, sticky='ne') combo1.set('Apple') lab2 = Label(fra, text='Normal Widget ►') lab2.grid(row=2, column=0, padx=5, pady=5) ''' # try uncommenting these lines, and comment out the cb lines following combo2 = Combobox(fra, style="Custom." + tWidg, values=("Milk","Water","Juice")) combo2.grid(row=3, column=0, padx=5, pady=5) combo2.option_add('*TCombobox*Listbox.font', element_options['font']) combo2.set('Milk') # this affects all comboboxes ''' cb = CustomBox(fra, font=element_options['font'], style="Custom." + tWidg, values=("Milk", "Water", "Juice")) cb.grid(row=3, column=1, padx=5, pady=5, sticky='ne') cb.set('Milk') lab3 = Label(fra, text='Widget with Style ►') lab3.grid(row=3, column=0, padx=5, pady=5) lab4 = Label(fra, text='Widget Layout ▼') lab4.grid(row=4, column=0, padx=5, pady=5) mess = Message(fra, text=out, width=700) mess.grid(row=5, column=0, padx=5, pady=5, sticky='news') root.mainloop()
class Tutorial(Frame): """ This is a simple walkthrough of the functionality of the program. It simply displays images and text, page by page. """ def __init__(self): super().__init__(Toplevel()) self.master.title('Tutorial') self.pack(padx=20, pady=20) self._imagepath = './spirogen/interface/settings/tutorial/images/' self.assetpath = '' p = './spirogen/interface/settings/tutorial/tutorial_pages.json' with open(p, 'r') as file: self.tutdata = json.load(file) self.h1 = Font(family='TkDefaultFont', size=40, weight='bold') # Big heading font self.h2 = Font(family='TkDefaultFont', size=20, weight='bold') self._currentindex = -1 self._image = None self._titletext = None self._text = None self.next() nextbtn = Button(self, text="Next", command=self.next, bg='blue', height=4, width=10) nextbtn.grid(row=220, column=200, padx=30, pady=30) backbtn = Button(self, text="Back", command=self.back, bg='blue', height=4, width=10) backbtn.grid(row=220, column=10, padx=30, pady=30) @property def path(self): return self._imagepath + self.tutdata[self._currentindex]['image'] @property def indexinrange(self): return 0 <= self._currentindex < len(self.tutdata) def next(self): # goes to the next page self._currentindex += 1 if self.indexinrange: self.load_page() else: self.master.destroy() def back(self): # goes to the previous page if not self._currentindex == 0: self._currentindex -= 1 self.load_page() def load_page(self): image = Image.open(self.path) # get the text and image data from the current page: currentpage = self.tutdata[self._currentindex] # image = resize_img(image) photo = ImageTk.PhotoImage(image) # cleanup the last page shown: if self._image: self._image.grid_forget() if self._text: self._text.grid_forget() if self._titletext: self._titletext.grid_forget() # if the image is a gif: if '.gif' in self.path: self._image = GifPlayer(self, borderwidth=2, relief="solid") # self.image.image = photo # keep a reference! self._image.grid(row=0, column=0, columnspan=205, rowspan=205) self._image.load(self.path) # if it's just a still image: else: self._image = Label(self, image=photo, borderwidth=2, relief="solid") self._image.image = photo # keep a reference! self._image.grid(row=0, column=0, columnspan=205, rowspan=205) # grab the text: title = currentpage['title'] text = currentpage['text'] self._titletext = Message(self, text=title, font=self.h1, width=500, justify='center') self._text = Message(self, text=text, font=self.h2, width=500, justify='center') # if this is the first or last page, we want the text below the image: if "Welcome" in self.path: self._titletext.grid(row=210, column=0, columnspan=205, pady=20) self._text.grid(row=215, column=0, columnspan=205, pady=20) # otherwise, we want it to the side: else: self._titletext.grid(row=5, column=300, columnspan=205, pady=60, padx=20) self._text.grid(row=10, column=300, columnspan=205, pady=60, padx=20) def goto(self, page): self._currentindex = page - 1 self.next()
class PasswordWindow(Toplevel): def __init__(self, master, success, failure): Toplevel.__init__(self, master) self.geometry('+%d+%d' % (master.winfo_x(), master.winfo_y())) self.title('Nescient password request:') self.lock_image = PhotoImage(data=LOCK_DATA) try: self.tk.call('wm', 'iconphoto', self._w, self.lock_image) except Exception: pass self.resizable(False, False) self.success = success self.failure = failure self.grab_set() self.focus_set() self.protocol('WM_DELETE_WINDOW', self.close) self.bind('<Return>', self.test_submit) self.grid() self.lock = Label(self, image=self.lock_image) self.lock_text = Message( self, text='Please enter the password with which to pack/unpack files:', width=256) self.label1 = Label(self, text='Insert password:'******'*', bg='white', fg='black') self.password.focus_set() self.label2 = Label(self, text='Verify password:'******'*', validate='key', validatecommand=(vcmd, '%P'), bg='white', fg='black') self.button = Button(self, text='Submit', state=DISABLED, command=lambda: self.close(self.password.get())) self.lock.grid(column=0, row=0) self.lock_text.grid(column=1, row=0) self.label1.grid(column=0, row=1, padx=5, pady=5) self.password.grid(column=1, row=1, padx=2, pady=5) self.label2.grid(column=0, row=2, padx=5, pady=5) self.password2.grid(column=1, row=2, padx=2, pady=5) self.button.grid(column=0, row=3, columnspan=2) def test_submit(self, *args): if self.button.cget('state') == NORMAL: self.close(self.password.get()) def can_submit(self, password2): password = self.password.get() if password == password2 and password != '': self.button.config(state=NORMAL) else: self.button.config(state=DISABLED) return True def close(self, password=None): self.grab_release() self.master.grab_set() self.master.focus_force() if password: self.success(password) else: self.failure(password) self.destroy()
class MyApp(): def open_file(self): name = askopenfilename(title="Choose a file.") print('Parsing', name) left_image = ImageTk.PhotoImage(Image.fromarray(resize(name, 400))) self.ipanel1.configure(image=left_image) self.ipanel1.image = left_image right_image = ImageTk.PhotoImage(Image.fromarray(get_crop(name, 200))) self.ipanel2.configure(image=right_image) self.ipanel2.image = right_image process_file = 'to_process512x512.png' get_crop(name, save_to=process_file) best_label, results = process_one_file(process_file, model) print(best_label, results) _text = ' '.join(('Best match:', best_label)) self.result_label.configure(text=_text) self.result_label.text = _text ordered_list = list(results.items()) ordered_list.sort(key=lambda x: -x[1]) _text = '\n'.join('{} - {}%'.format(k, str(round(v*100, 2))) for k, v in ordered_list) self.results_label.configure(text=_text) self.results_label.text = _text def __init__(self): font_style = ("Helvetica", 16) self.root = Tk() self.root.geometry("900x700") self.label = ttk.Label(self.root, text="What camera made the picture?", foreground="black", font=font_style) self.label.grid(row=0, column=0) self.crop_label = ttk.Label(self.root, text='NN uses crop 512x512', font=font_style) self.crop_label.grid(row=0, column=2, pady=(10,0)) img1 = ImageTk.PhotoImage(Image.fromarray(resize('iphone6.png', 400))) self.ipanel1 = ttk.Label(self.root, image=img1) self.ipanel1.grid(row=1, column=0, padx=(10, 10)) self.help_text = ttk.Label(self.root, text='==================>') self.help_text.grid(row=1, column=1) img2 = ImageTk.PhotoImage(Image.fromarray(get_crop('iphone6.png', 200))) self.ipanel2 = ttk.Label(self.root, image=img2) self.ipanel2.grid(row=1, column=2, padx=(10, 10)) self.result_label = ttk.Label(self.root, text='Results:', font=font_style) self.result_label.grid(row=2, column=0) self.results_label = Message(self.root, text='', font=("Helvetica", 10)) self.results_label.grid(row=3, column=0) self.menu = Menu(self.root) self.root.config(menu=self.menu) file = Menu(self.menu) file.add_command(label='Open', command=self.open_file) file.add_command(label='Exit', command=lambda: exit()) self.menu.add_cascade(label='File', menu=file) self.root.mainloop()
class YoutubeAudioDownloader: def __init__(self): self.root = Tk() winWidth = int(self.root.winfo_screenwidth() * WIN_WIDTH_RATIO) self.root.geometry("{}x{}".format(winWidth, WIN_HEIGHT)) self.msg = Message(self.root, aspect=winWidth - 10) self.msg.grid(row=2, column=0, columnspan=2, padx=2) self.msgText = '' if os.name == 'posix': configFilePathName = '/storage/emulated/0/Android/data/ru.iiec.pydroid3/files/youtube_audio_download/audiodownload.ini' else: configFilePathName = 'D:\\Development\\Python\\youtube_audio_download\\audiodownload.ini' self.configMgr = ConfigManager(configFilePathName) self.emailLst = self.configMgr.getEmailLst() # format = "%(asctime)s: %(message)s" # logging.basicConfig(format=format, level=logging.INFO,datefmt="%H:%M:%S") # logging.info(self.emailLst) def getPlaylistUrlFromClipboard(self): playlistUrl = None try: playlistUrl = self.root.clipboard_get() except TclError as e: # playlistUrl remains None pass return playlistUrl def displayError(self, msg): return msgb.showerror(message=msg) def getConfirmation(self, msg): return msgb.askquestion(message=msg) def doDownload(self): playlistUrl = self.getPlaylistUrlFromClipboard() if playlistUrl == None: self.displayError('Playlist URL not in clipboard. Program closed.') return playlist = None try: playlist = Playlist(playlistUrl) playlist._video_regex = re.compile(r"\"url\":\"(/watch\?v=[\w-]*)") except KeyError as e: self.displayError('Playlist URL not in clipboard. Program closed.') return except http.client.InvalidURL as e: self.displayError(str(e)) return playlistTitle = playlist.title() if 'Oops' in playlistTitle: self.displayError( 'The URL obtained from clipboard is not pointing to a playlist. Program closed.' ) return playlistName, timeInfo = self.splitPlayListTitle(playlistTitle) targetAudioDir = AUDIO_DIR + DIR_SEP + playlistName if not os.path.isdir(targetAudioDir): targetAudioDirList = targetAudioDir.split(DIR_SEP) targetAudioDirShort = DIR_SEP.join(targetAudioDirList[-2:]) if self.getConfirmation( "Directory\n{}\nwill be created.\n\nContinue with download ?" .format(targetAudioDirShort)) != 'yes': return os.makedirs(targetAudioDir) for video in playlist.videos: audioStream = video.streams.get_by_itag(YOUTUBE_STREAM_AUDIO) videoTitle = video.title self.msgText = self.msgText + 'downloading ' + videoTitle + '\n' self.msg.configure(text=self.msgText) self.root.update() audioStream.download(output_path=targetAudioDir) for file in [ n for n in os.listdir(targetAudioDir) if re.search('mp4', n) ]: mp4FilePathName = os.path.join(targetAudioDir, file) mp3FilePathName = os.path.join(targetAudioDir, os.path.splitext(file)[0] + '.mp3') if timeInfo: timeStartSec, timeEndSec = self.splitTimeInfo(timeInfo) import moviepy.editor as mp # not working on Android clip = mp.AudioFileClip(mp4FilePathName).subclip( timeStartSec, timeEndSec) # disable if do not want any clipping clip.write_audiofile(mp3FilePathName) clip.close() os.remove(mp4FilePathName) else: if os.path.isfile(mp3FilePathName): os.remove(mp3FilePathName) os.rename(mp4FilePathName, mp3FilePathName) def splitPlayListTitle(self, playlistTitle): pattern = r"(.+) ([\d\./]+)" playlistName = None timeInfo = None match = re.match(pattern, playlistTitle) if match: playlistName = match.group(1) timeInfo = match.group(2) else: # no time info provided in the play list title playlistName = playlistTitle return playlistName, timeInfo def splitTimeInfo(self, timeInfo): timeLst = timeInfo.split('/') timeStartHHMMSS = timeLst[0].split('.') timeEndHHMMSS = timeLst[1].split('.') timeStartSec = int(timeStartHHMMSS[0]) * 3600 + int( timeStartHHMMSS[1]) * 60 + int(timeStartHHMMSS[2]) timeEndSec = int(timeEndHHMMSS[0]) * 3600 + int( timeEndHHMMSS[1]) * 60 + int(timeEndHHMMSS[2]) return timeStartSec, timeEndSec
class App: def __init__(self, master): master.minsize(width=300, height=80) self.savedRealmName = [] self.savedRealmAddress = [] self.selectRealmButton = [] self.removeRealmButton = [] self.rlmManager = RealmManager() self.cfgManager = ConfigManager() if not self.cfgManager.hasGameFolder(): newGameFolder = chooseGameFolder() # Force user to choose a game folder while newGameFolder is None: isCanceled = simpledialog.askretrycancel( 'Question', 'You need to select a game folder', parent=root) if isCanceled: root.destroy() return newGameFolder = chooseGameFolder() self.cfgManager.updateGameFolder(newGameFolder) self.mainFrame = Frame(master, width=300, height=100) self.mainFrame.grid(row=0, column=0, padx=20) self.title = Message(self.mainFrame, text='WoW Realm Changer', width=400, font=('Helvetica', 18, 'bold')) self.title.grid() inputFrame = Frame(self.mainFrame) inputFrame.grid(row=1, column=0) self.realmInputLabel = Message(inputFrame, text='set realmlist:', width=100, font=('Helvetica', 11)) self.realmInputLabel.grid(row=1, column=1) self.realmAddressInput = Entry(inputFrame) self.realmAddressInput.grid(row=1, column=2) self.saveButton = Button(inputFrame, text='SAVE', command=self.addRealm) self.saveButton.grid(row=1, column=4) self.currentRealmFrame = Frame(self.mainFrame) self.currentRealmFrame.grid(row=2, column=0) self.realmInitText = Message(self.currentRealmFrame, text=self.rlmManager.currentRealm(), width=300, font=('Helvetica', 11)) self.realmInitText.grid(row=2, column=0) self.buildSavedRealmsList() def buildSavedRealmsList(self): self.savedRealmsFrame = Frame(self.mainFrame) self.savedRealmsFrame.grid(row=3, pady=(20, 10)) self.savedRealmsMessage = Message(self.savedRealmsFrame, text='Saved Realms', width=300, font=('Helvetica', 15, 'bold')) self.savedRealmsMessage.grid() for idx, realm in enumerate(self.cfgManager.savedRealms()): self.addRealmRow(realm) def setActiveRealm(self, realm): self.rlmManager.changeActiveRealm(realm) self.realmInitText.configure(text='Realm changed to: ' + realm['name']) def removeSavedRealm(self, idx): self.cfgManager.removeRealm(idx) self.removeRealmRow(idx) def addRealm(self): realmName = simpledialog.askstring('Input', 'What is the name of the realm?', parent=root) realmAddress = self.realmAddressInput.get() realm = {'address': realmAddress, 'name': realmName} self.cfgManager.addRealm(realm) self.addRealmRow(realm) def removeRealmRow(self, index): self.savedRealmName[index].destroy() self.savedRealmAddress[index].destroy() self.selectRealmButton[index].destroy() self.removeRealmButton[index].destroy() def addRealmRow(self, realm): if not realm: return index = len(self.savedRealmName) name = realm['name'] address = realm['address'] self.savedRealmName.append( Message(self.savedRealmsFrame, text=name, width=250)) self.savedRealmName[index].grid(column=0, row=index + 1) self.savedRealmAddress.append( Message(self.savedRealmsFrame, text=address, width=250)) self.savedRealmAddress[index].grid(column=1, row=index + 1) self.selectRealmButton.append( Button(self.savedRealmsFrame, text='SET', command=lambda rlm=realm: self.setActiveRealm(rlm))) self.selectRealmButton[index].grid(column=2, row=index + 1) self.removeRealmButton.append( Button(self.savedRealmsFrame, text='REMOVE', command=lambda idx=index: self.removeSavedRealm(idx))) self.removeRealmButton[index].grid(column=3, row=index + 1) self.totalRealmItems = index + 1