def joinGame(self): self.app.title('JOIN') self.mode = "join" self.destroyMenu() waiting = Label(self.app, text="waiting for player 1!") waiting.grid(row=0, column=0, sticky="WE", pady=150, padx=150) ### connection!! self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.s.connect((self.TCP_IP, self.TCP_PORT)) self.s.send("ur the host!!") data = self.s.recv(self.BUFFER_SIZE) print(data) #setting up the menu stuff waiting.destroy() self.createGrid() #make the player wait!! self.waitForMove()
def hostGame(self): self.app.title('HOST') self.mode = "host" self.destroyMenu() waiting = Label(self.app, text="waiting for player 2!") waiting.grid(row=0, column=0, sticky="WE", pady=150, padx=150) ### connection!! self.sh = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.sh.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.sh.bind((self.TCP_IP, self.TCP_PORT)) self.sh.listen(1) self.conn, self.addr = self.sh.accept() data = self.conn.recv(self.BUFFER_SIZE) print(data) self.conn.send("ur gonna join") #setting up the menu stuff waiting.destroy() self.createGrid()
def run(self, robotip=DEFAULT_IP, imagename="image", port=9559): # Opens a tkinter window showing application ''' :param robotip: ip of bot :type: string :param port: port of bot on ip :type: int ''' #try: if __name__ == "__main__": try: tkinst = Tk() frame = Frame(tkinst, height=640, width=480) frame.bind("<Key>", move) frame.pack() subscriberID = self.vidproxy.subscribe( "subscriberID", 0, 11, 10) # 0,11,10 is correct numbers while True: image = self.vidproxy.getImageRemote(subscriberID) im = fromstring("RGB", (image[0], image[1]), str(bytearray(image[6]))) im.save(imagename + ".jpg") showimage = ImageTk.PhotoImage( Image.open(imagename + ".jpg").resize( (image[0] * 4, image[1] * 4), Image.ANTIALIAS)) w = Label(frame, image=showimage) w.image = showimage w.pack() tkinst.update() w.destroy() except Exception, e: print(str(e)) self.vidproxy.unsubscribe(subscriberID)
class Example(Frame): def __init__(self, parent, queue, musicplayer, endCommand): Frame.__init__(self, parent) self.parent = parent self.weight = 500 self.height = 400 self.queue = queue self.musicplayer = musicplayer self.endCommand = endCommand self.pictures = [ "hd_1.jpg", "hd_2.jpg", "hd_3.jpg", "hd_4.jpg", "hd_5.jpg" ] self.centerWindow() self.initUI() ''' self.showPic = 1 self.playSlides() ''' def initUI(self): self.parent.title("Example") self.pack(fill=BOTH, expand=1) self.style = Style() self.style.theme_use("default") frame = Frame(self, relief=Tkinter.RAISED, borderwidth=1) frame.pack(fill=BOTH, expand=1) #okButton = Button(self, text = "OK") #okButton.place(x = self.width - 200, y = self.height - 100) #quitButton = Button(self.parent, text = "QUIT", command = self.endCommand) #quitButton.place(x = self.width - 100, y = self.height - 100) scale = 0.75 self.wow_pic = Image.open("hd_1.jpg") self.wow_pic = self.wow_pic.resize((self.width, self.height)) self.wow_pic_tk = ImageTk.PhotoImage(self.wow_pic) self.label_wow_pic = Label(self, image=self.wow_pic_tk) self.label_wow_pic.image = self.wow_pic_tk self.label_wow_pic.place(x=0, y=0) info_x = int(self.width * scale) + 20 #label_text_area = Tkinter.Label(self, text = "Message received:") #label_text_area.place(x = info_x, y = 10) #self.text_area = Tkinter.Text(self, height = 10, width = 40) #self.text_area.place(x = info_x, y = 30) def centerWindow(self): self.width = self.parent.winfo_screenwidth() self.height = self.parent.winfo_screenheight() self.queue.put("Width: " + str(self.width) + " Height: " + str(self.height)) self.parent.geometry('%dx%d+%d+%d' % (self.width, self.height, 0, 0)) def insertText(self, str): self.text_area.insert(Tkinter.INSERT, "\n" + str) def showPicture(self, img_name): self.label_wow_pic.destroy() scale = 0.75 self.wow_pic = Image.open(img_name) self.wow_pic = self.wow_pic.resize( (int(self.width * scale), int(self.height * scale))) self.wow_pic_tk = ImageTk.PhotoImage(self.wow_pic) self.label_wow_pic = Label(self, image=self.wow_pic_tk) self.label_wow_pic.image = self.wow_pic_tk self.label_wow_pic.place(x=10, y=10) def playMusic(self): pygame.mixer.init() pygame.mixer.music.load("1.mp3") pygame.mixer.music.play() def pauseMusic(self): self.musicthread = threading.Thread(target=self.musicplayer.play) self.musicthread.start() def playSlides(self): self.showPic = 1 self.currentSlideNo = 0 self.showSlidesThread = threading.Thread(target=self.playSlidesClock) self.showSlidesThread.start() def playSlidesClock(self): #self.queue.put("next_picture"); while True: if (self.showPic == 0): break self.queue.put("next_picture") time.sleep(5) def nextSlide(self): self.currentSlideNo = (self.currentSlideNo + 1) % len(self.pictures) self.showPicture(self.pictures[self.currentSlideNo]) def processIncoming(self): while self.queue.qsize(): try: msg = self.queue.get(0) print "From queue, get msg:", msg if (msg == "show_text"): self.insertText("I need to show a text") elif (msg == "show_picture"): self.showPic = 1 self.playSlides() elif (msg == "play_music"): self.playMusic() elif (msg == "pause_music"): self.pauseMusic() elif (msg == "next_picture"): self.nextSlide() else: self.insertText(msg) except: pass
class IntroView(Frame): def __init__(self, controller, parent): # formerly init_intro_nav(): ''' using class objects for all these vars now global intro_nav, background_frame, can, button_load_game\ , button_new_game, button_quit, intro_fill_bottom\ , label_version, title_image_res\ , intro_top_padding, intro_btm_padding ''' self.controller = controller self.parent = parent self.app = self.controller.app # declare vars self.background_frame = 0 self.intro_nav = 0 self.intro_top_padding = 0 def build(self): # prev: build_intro_nav # frame setup conf = self.app.conf self.background_frame = Frame(self.parent, height=self.parent.sh, width=self.parent.sw , background=conf.window_background) self.intro_nav = Frame(self.background_frame, height=500, width=500 , background=conf.intro_background) # elements self.intro_top_padding = Canvas(self.intro_nav) self.intro_top_padding.configure(height=conf.intro_padding_height , background=conf.intro_background , highlightbackground=conf.intro_background) self.title_image_resource = Image.open(conf.title_image_path) self.title_image_res = ImageTk.PhotoImage(self.title_image_resource) self.can = Canvas(self.intro_nav, background=conf.intro_background , highlightbackground=conf.intro_background) self.can.title_image_res = self.title_image_res self.can.config(width=self.title_image_res.width(), height=self.title_image_res.height()) self.button_new_game = Button(self.intro_nav, text="New Game" , command=self.controller.event_button_new_game , bg=conf.intro_background) self.button_new_game.config(highlightbackground=conf.intro_background) self.button_load_game = Button(self.intro_nav, text="Load Game" , command=self.controller.event_button_load_game , bg=conf.intro_background) self.button_load_game.config(highlightbackground=conf.intro_background) self.button_load_game.config(state='disabled') self.button_quit = Button(self.intro_nav, text="Quit" , command=self.controller.event_button_quit , bg=conf.intro_background) self.button_quit.config(highlightbackground=conf.intro_background) self.label_version = Label(self.intro_nav, bg=conf.intro_background, text=conf.version) self.intro_btm_padding = Canvas(self.intro_nav) self.intro_btm_padding.configure(height=conf.intro_padding_height , background=conf.intro_background , highlightbackground=conf.intro_background) def hide(self): # formerly hide_intro_nav self.intro_nav.destroy() self.background_frame.destroy() self.can.destroy() self.button_load_game.destroy() self.button_new_game.destroy() self.button_quit.destroy() self.label_version.destroy() self.title_image_res.__del__() self.intro_top_padding.destroy() self.intro_btm_padding.destroy() def draw(self): # formerly draw_intro_nav() # frame setup self.intro_top_padding.pack() self.background_frame.pack(fill='both') self.intro_nav.pack(fill='both', padx=(self.parent.sw/2)-250, pady=(self.parent.sh/2)-250) self.app.debug(("Drew Intro, padding: (", (self.parent.sw/2)-250, ",", (self.parent.sh/2)-250, ")")) # elements self.can.pack(fill='both', side='top', padx=50, pady=50) self.can.create_image(2, 2, image=self.title_image_res, anchor='nw') self.button_new_game.pack(fill="x", padx=50) self.button_load_game.pack(fill="x", padx=50) self.button_quit.pack(fill="x", padx=50) self.label_version.pack(fill='y', padx=10, pady=10) self.intro_btm_padding.pack() '''
class WelcomeScreen(Frame): def __init__(self, parent, mw): Frame.__init__(self, parent) parent.configure(bg="MediumTurquoise") self.parent = parent self.mw = mw # change font size depending on screen dimension screen_width = self.parent.winfo_screenwidth() screen_height = self.parent.winfo_screenheight() # projector setting if screen_width == 1280: self.customFont1 = tkFont.Font(family="LMMono10", size=20) self.customFont = tkFont.Font(family="Pupcat", size=20, weight=tkFont.BOLD) self.customFont2 = tkFont.Font(family="LMMono10", size=14) # single screen setting elif screen_width == 1920: self.customFont1 = tkFont.Font(family="LMMono10", size=18) self.customFont = tkFont.Font(family="Pupcat", size=16, weight=tkFont.BOLD) self.customFont2 = tkFont.Font(family="LMMono10", size=14) # double screen setting else: self.customFont1 = tkFont.Font(family="LMMono10", size=18) self.customFont = tkFont.Font(family="Pupcat", size=16, weight=tkFont.BOLD) self.customFont2 = tkFont.Font(family="LMMono10", size=14) self.initLogo() self.initToolbar() self.initScreen() def initLogo(self): self.topFrame = Frame(self.parent, relief=FLAT, background="MediumTurquoise") img = Image.open("./Graphics/logo.png") logoImg = ImageTk.PhotoImage(img) # make the logo the current item held in the topFrame self.currItem = Label(self.topFrame, relief=FLAT, background="MediumTurquoise", image=logoImg) self.currItem.image = logoImg self.currItem.pack() self.topFrame.grid(row=0) def initToolbar(self): toolbar = Frame(self.parent, relief=FLAT, background="MediumTurquoise") playButton = Button(toolbar, text="Play Game!", relief=RAISED, bg="Turquoise", activebackground="yellow", font=self.customFont, command=self.openStartWindow) playButton.grid(row=0, column=0, padx=BUTTON_PAD_X) helpButton = Button(toolbar, text="Getting Started", relief=RAISED, bg="Turquoise", activebackground="yellow", font=self.customFont, command=self.openGettingStartedWindow) helpButton.grid(row=0, column=1, padx=BUTTON_PAD_X) aboutButton = Button(toolbar, text="About", relief=RAISED, bg="Turquoise", activebackground="yellow", font=self.customFont, command=self.openAboutWindow) aboutButton.grid(row=0, column=2, padx=BUTTON_PAD_X) quitButton = Button(toolbar, text="Quit", relief=RAISED, bg="Turquoise", activebackground="yellow", font=self.customFont, command=self.onExit) quitButton.grid(row=0, column=3, padx=BUTTON_PAD_X) toolbar.grid(row=1) def initScreen(self): self.parent.grid_columnconfigure(0, minsize=DIM_X) self.parent.grid_rowconfigure(0, minsize=740) self.parent.grid_propagate(False) self.parent.resizable(width=False, height=False) # make the about text box the current item held in the topFrame def initAboutBox(self): file = open("../support/help/about", "r") gttext = file.read() self.currItem = Label(self.topFrame, bg="MediumTurquoise", relief=FLAT, font=self.customFont1, width=NUM_CHARS, height=NUM_ROWS, text=gttext) self.currItem.pack() self.topFrame.grid(row=0) # make the getting started text box the current item held in the topFrame def initGettingStartedBox(self): file = open("../support/help/gettingstarted", "r") abouttext = file.read() self.currItem = Label(self.topFrame, bg="MediumTurquoise", relief=FLAT, font=self.customFont2, width=NUM_CHARS, height=NUM_ROWS+7, text=abouttext) self.currItem.grid(row=0, column=0) self.topFrame.grid(row=0) def openStartWindow(self): frame = Frame(bg="") frame.pack() popup = StartPopupWindow(self) def openGettingStartedWindow(self): # first, destroy the current item held in the topFrame self.currItem.destroy() # then, make a new getting started box in the topFrame self.initGettingStartedBox() def openAboutWindow(self): # first, destroy the current item held in the topFrame self.currItem.destroy() # then, make a new about box in the topFrame self.initAboutBox() def onExit(self): self.parent.destroy() def createEnvt(self, username): self.mw.createNewEnvt(username)
class CallTip: def __init__(self, widget): self.widget = widget self.tipwindow = self.label = None self.parenline = self.parencol = None self.lastline = None self.hideid = self.checkhideid = None self.checkhide_after_id = None def position_window(self): """Check if needs to reposition the window, and if so - do it.""" curline = int(self.widget.index("insert").split('.')[0]) if curline == self.lastline: return self.lastline = curline self.widget.see("insert") if curline == self.parenline: box = self.widget.bbox("%d.%d" % (self.parenline, self.parencol)) else: box = self.widget.bbox("%d.0" % curline) if not box: box = list(self.widget.bbox("insert")) # align to left of window box[0] = 0 box[2] = 0 x = box[0] + self.widget.winfo_rootx() + 2 y = box[1] + box[3] + self.widget.winfo_rooty() self.tipwindow.wm_geometry("+%d+%d" % (x, y)) def showtip(self, text, parenleft, parenright): """Show the calltip, bind events which will close it and reposition it. """ # Only called in CallTips, where lines are truncated self.text = text if self.tipwindow or not self.text: return self.widget.mark_set(MARK_RIGHT, parenright) self.parenline, self.parencol = map( int, self.widget.index(parenleft).split(".")) self.tipwindow = tw = Toplevel(self.widget) self.position_window() # remove border on calltip window tw.wm_overrideredirect(1) try: # This command is only needed and available on Tk >= 8.4.0 for OSX # Without it, call tips intrude on the typing process by grabbing # the focus. tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except TclError: pass self.label = Label(tw, text=self.text, justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font=self.widget['font']) self.label.pack() self.checkhideid = self.widget.bind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhide_event) for seq in CHECKHIDE_SEQUENCES: self.widget.event_add(CHECKHIDE_VIRTUAL_EVENT_NAME, seq) self.widget.after(CHECKHIDE_TIME, self.checkhide_event) self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) for seq in HIDE_SEQUENCES: self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq) def checkhide_event(self, event=None): if not self.tipwindow: # If the event was triggered by the same event that unbinded # this function, the function will be called nevertheless, # so do nothing in this case. return curline, curcol = map(int, self.widget.index("insert").split('.')) if curline < self.parenline or \ (curline == self.parenline and curcol <= self.parencol) or \ self.widget.compare("insert", ">", MARK_RIGHT): self.hidetip() else: self.position_window() if self.checkhide_after_id is not None: self.widget.after_cancel(self.checkhide_after_id) self.checkhide_after_id = \ self.widget.after(CHECKHIDE_TIME, self.checkhide_event) def hide_event(self, event): if not self.tipwindow: # See the explanation in checkhide_event. return self.hidetip() def hidetip(self): if not self.tipwindow: return for seq in CHECKHIDE_SEQUENCES: self.widget.event_delete(CHECKHIDE_VIRTUAL_EVENT_NAME, seq) self.widget.unbind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhideid) self.checkhideid = None for seq in HIDE_SEQUENCES: self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq) self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideid) self.hideid = None self.label.destroy() self.label = None self.tipwindow.destroy() self.tipwindow = None self.widget.mark_unset(MARK_RIGHT) self.parenline = self.parencol = self.lastline = None def is_active(self): return bool(self.tipwindow)
class Game: def __init__(self): self.root = Tk() self.frame1 = None self.frame2 = None self.w = None self.scoreC = None self.score = 0 self.hor = True self.upid = self.downid = self.rightid = self.leftid = 0 self.head = -1 self.time = 700 def home(self): self.frame1 = Frame(self.root, width=750, height=350, padx=250, bg="black") self.frame2 = Frame(self.root, height=250, width=750, bg="black", padx=25) self.root.wm_minsize(width=750, height=666) self.root.configure(bg="black") self.frame1.pack_propagate(0) self.frame1.update() self.frame1.configure(pady=self.frame1.cget("height") / 2.5) logo = PhotoImage(file="Game_Logo.gif") starth = Button(self.frame1, text="Hard", bg="orange", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(40)) startm = Button(self.frame1, text="Medium", bg="teal", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(60)) starte = Button(self.frame1, text="Easy", bg="orange", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(75)) self.frame2.pack_propagate(0) exp = """ This is a game in which the arrow keys are used to move the snake around and to get points""" exf = Font(family="comic sans MS", size=20) Label(self.frame2, image=logo, bg="black", text=exp, padx=10).pack(side="right") Label(self.frame2, fg="white", bg="black", text=exp, justify="left", font=exf).pack(side="left") starte.grid(row=0, columnspan=2) startm.grid(row=0, columnspan=2, column=4, padx=18) starth.grid(row=0, columnspan=2, column=8) head = Font(family="comic sans MS", size=30) self.H=Label(self.root, text="SNAKES", font=head, fg="orange", bg="black", pady=10) self.H.pack() self.frame2.pack(expand=True) self.frame1.pack(expand=True) self.root.mainloop() def callgame(self, time): self.time = time self.game() def calldown(self, key): if self.hor: self.w.after_cancel(self.leftid) self.w.after_cancel(self.rightid) self.down(0) def callup(self, key): if self.hor: self.w.after_cancel(self.leftid) self.w.after_cancel(self.rightid) self.up(0) def callright(self, key): if not self.hor: self.w.after_cancel(self.upid) self.w.after_cancel(self.downid) self.right(0) def callleft(self, key): if not self.hor: self.w.after_cancel(self.upid) self.w.after_cancel(self.downid) self.left(0) def game(self): self.score = 0 self.w = Canvas(self.root, width=750, height=500, relief="flat", highlightbackground="grey", highlightthickness=10) self.frame1.destroy() self.frame2.destroy() self.root.configure(width=1000, padx=10) self.root.pack_propagate(0) self.w.configure(background="black") self.w.pack(side="left") self.w.create_line(300, 250, 450, 250, width=10, fill="teal") self.scoreC = Label(self.root, text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35, font=Font(family="comic sans MS", size=25)) self.head = self.w.create_line(450, 250, 455, 250, width=10, fill="white") self.scoreC.pack(side="top") self.root.bind("<Up>", self.callup) self.root.bind("<Down>", self.calldown) self.root.bind("<Right>", self.callright) self.root.bind("<Left>", self.callleft) self.createFood() self.right(0) def down(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-1] += 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-3] -= 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] + 5, width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = False if not end: self.downid = self.w.after(self.time, self.down, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def up(self, i): crd = self.w.coords(1) if len(crd)>0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-1] -= 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-3] += 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] - 5, width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = False if not end: self.upid = self.w.after(self.time, self.up, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def right(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-2] += 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-4] -= 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] + 5, crd[-1], width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = True if not end: self.rightid = self.w.after(self.time, self.right, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def left(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-2] -= 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-4] += 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] - 5, crd[-1], width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = True if not end: self.leftid = self.w.after(self.time, self.left, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def createFood(self): # self.w.delete(self.food) #deleting old food. crd = self.w.coords(1) ext = [] for i in crd: ext.append(i) for j in range(-50, 50): ext.append(i + j) randx = random.randrange(20, 730) randy = random.randrange(20, 480) while randx not in ext and randy not in ext: randx = random.randrange(20, 730) randy = random.randrange(20, 480) self.food = self.w.create_line(randx, randy, randx + 12, randy, width=10, fill="yellow") def checkEaten(self): headcoords = self.w.coords(self.head) foodcoords = self.w.coords(self.food) # self.w.delete(self.food) flag = False # print(headcoords[-4]) # print(foodcoords[-4]) # print(foodcoords[-2]) if int(headcoords[-4]) in range(int(foodcoords[-4]) - 7, int(foodcoords[-2]) + 7) and int( headcoords[-3]) in range(int(foodcoords[-1]) - 10, int(foodcoords[-1] + 10)): flag = True if flag: self.grow() self.score += 10 self.scoreC.configure(text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35, font=Font(family="comic sans MS", size=25)) self.w.delete(self.food) self.createFood() def grow(self): crd = self.w.coords(1) if crd[0] != crd[2]: # horizontal condition if crd[0] < crd[2]: crd[0] -= 20 else: crd[0] += 20 self.w.coords(1, *crd) else: if crd[3] < crd[1]: crd[1] += 20 else: crd[1] -= 20 self.w.coords(1, *crd) def end(self): crd = self.w.coords(1) h = self.w.coords(self.head) a = 0 while a < len(crd) - 2: if crd[a] == crd[a + 2]: if (h[0] == crd[a] and crd[a + 1] < h[1] < crd[a + 3]) or ( h[0] == crd[a] and crd[a + 1] > h[1] > crd[a + 3]): return True else: if (h[1] == crd[a + 1] and crd[a] < h[0] < crd[a + 2]) or (h[1] == crd[a + 1] and crd[a] > h[0] > crd[a + 2]): return True a += 2 if (h[0] == 0 and 0 < h[1] < 500) or (h[1] == 0 and 0 < h[0] < 750) or (h[1] == 510 and 0 < h[0] < 750) or (h[0] == 760 and 0<h[1]<500): return True return False def callhome(self): self.w.destroy() self.start.destroy() self.H.destroy() self.scoreC.destroy() self.home()
class MsgBinder(object): def __init__(self, frame, **kwargs): text = get_dict_item(kwargs, 'text', 'None') font = get_dict_item(kwargs, 'font', 'Arial') width = get_dict_item(kwargs, 'width', '+10') height = get_dict_item(kwargs, 'height', '+5') self.fg = get_dict_item(kwargs, 'fg', 'black') self.fg_hov = get_dict_item(kwargs, 'fg_hov', '') self.bg = get_dict_item(kwargs, 'bg', '') self.bg_hov = get_dict_item(kwargs, 'bg_hov', '') self.function = get_dict_item(kwargs, 'func', 'False') self.function_exc = get_dict_item(kwargs, 'command', 'False') self.img = get_dict_item(kwargs, 'img', '') self.img_hov = get_dict_item(kwargs, 'img_hov', '') if self.img == '': self.msg = Message(frame, text=text) self.msg.config(bg=self.bg, fg=self.fg, width=width, font=font) else: self.msg = Label(frame, image=self.img, width=width, background=self.bg) self.msg.bind("<Enter>", self._enter) self.msg.bind("<Leave>", self._leave) self.msg.bind("<Button-1>", self._click) def destroy(self): self.msg.destroy() def bind(self, func): self.msg.bind(func) def pack(self, **kwargs): side = get_dict_item(kwargs, 'side', 'top') anchor = get_dict_item(kwargs, 'anchor', 'nw') padx = get_dict_item(kwargs, 'padx', '0') pady = get_dict_item(kwargs, 'pady', '0') self.msg.pack(side=side, anchor=anchor, padx=padx, pady=pady) def _enter(self, event): self.msg.config(cursor="hand2") if self.fg_hov != '': self.msg.config(fg=self.fg_hov) if self.bg_hov != '': self.msg.config(bg=self.bg_hov) if self.img_hov != '': self.msg.config(image=self.img_hov) def _leave(self, event): self.msg.config(cursor="") if self.fg_hov != '': self.msg.config(fg=self.fg) if self.bg_hov != '': self.msg.config(bg=self.bg) if self.img_hov != '': self.msg.config(image=self.img) def _click(self, event): if self.function == 'func': self.function_exc() elif self.function == 'link' and self.function_exc != 'none': open_address_in_webbrowser(self.function_exc) def configure(self, **kwargs): self.bg = get_dict_item(kwargs, 'bg', '') self.msg.config(bg=self.bg)
class Game: def __init__(self): self.root = Tk() self.frame1 = None self.frame2 = None self.w = None self.scoreC = None self.score = 0 self.hor = True self.upid = self.downid = self.rightid = self.leftid = 0 self.head = -1 self.time = 700 def home(self): self.frame1 = Frame(self.root, width=750, height=350, padx=250, bg="black") self.frame2 = Frame(self.root, height=250, width=750, bg="black", padx=25) self.root.wm_minsize(width=750, height=666) self.root.configure(bg="black") self.frame1.pack_propagate(0) self.frame1.update() self.frame1.configure(pady=self.frame1.cget("height") / 2.5) logo = PhotoImage(file="logo.gif") starth = Button(self.frame1, text="Hard", bg="orange", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(40)) startm = Button(self.frame1, text="Medium", bg="teal", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(60)) starte = Button(self.frame1, text="Easy", bg="orange", padx=25, pady=5, font=Font(family="comic sans MS", size=10), command=lambda: self.callgame(75)) self.frame2.pack_propagate(0) exp = """ This is a game in which the arrow keys are used to move the snake around and to get points""" exf = Font(family="comic sans MS", size=20) Label(self.frame2, image=logo, bg="black", text=exp, padx=10).pack(side="right") Label(self.frame2, fg="white", bg="black", text=exp, justify="left", font=exf).pack(side="left") starte.grid(row=0, columnspan=2) startm.grid(row=0, columnspan=2, column=4, padx=18) starth.grid(row=0, columnspan=2, column=8) head = Font(family="comic sans MS", size=30) self.H = Label(self.root, text="SNAKES", font=head, fg="orange", bg="black", pady=10) self.H.pack() self.frame2.pack(expand=True) self.frame1.pack(expand=True) self.root.mainloop() def callgame(self, time): self.time = time self.game() def do_after_cancel(self, a, b): if a != 0: self.w.after_cancel(a) if b != 0: self.w.after_cancel(b) def calldown(self, key): if self.hor: self.do_after_cancel(self.leftid, self.rightid) self.down(0) def callup(self, key): if self.hor: self.do_after_cancel(self.leftid, self.rightid) self.up(0) def callright(self, key): if not self.hor: self.do_after_cancel(self.upid, self.downid) self.right(0) def callleft(self, key): if not self.hor: self.do_after_cancel(self.upid, self.downid) self.left(0) def game(self): self.score = 0 self.w = Canvas(self.root, width=750, height=500, relief="flat", highlightbackground="grey", highlightthickness=10) self.frame1.destroy() self.frame2.destroy() self.root.configure(width=1000, padx=10) self.root.pack_propagate(0) self.w.configure(background="black") self.w.pack(side="left") self.w.create_line(300, 250, 450, 250, width=10, fill="teal") self.scoreC = Label(self.root, text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35, font=Font(family="comic sans MS", size=25)) self.head = self.w.create_line(450, 250, 455, 250, width=10, fill="white") self.scoreC.pack(side="top") self.root.bind("<Up>", self.callup) self.root.bind("<Down>", self.calldown) self.root.bind("<Right>", self.callright) self.root.bind("<Left>", self.callleft) self.createFood() self.right(0) def down(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-1] += 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-3] -= 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] + 5, width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = False if not end: self.downid = self.w.after(self.time, self.down, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def up(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-1] -= 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-3] += 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2], crd[-1] - 5, width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = False if not end: self.upid = self.w.after(self.time, self.up, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def right(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-2] += 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-4] -= 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] + 5, crd[-1], width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = True if not end: self.rightid = self.w.after(self.time, self.right, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def left(self, i): crd = self.w.coords(1) if len(crd) > 0: if crd[0] == crd[2]: if crd[1] > crd[3]: # print("inside if1") crd[1] -= 10 if crd[1] < crd[3]: # print("inside if2") crd[1] += 10 else: if crd[0] > crd[2]: crd[0] -= 10 if crd[0] < crd[2]: crd[0] += 10 crd[-2] -= 10 if i == 0: crd.append(crd[-2]) crd.append(crd[-2]) crd[-4] += 10 if crd[0] == crd[2] and crd[1] == crd[3]: crd = crd[2:] self.w.coords(1, *crd) self.w.delete(self.head) self.head = self.w.create_line(crd[-2], crd[-1], crd[-2] - 5, crd[-1], width=10, fill="orange") end = self.end() self.checkEaten() i += 1 self.hor = True if not end: self.leftid = self.w.after(self.time, self.left, i) else: self.w.delete(1) self.w.delete(self.head) self.w.delete(self.food) self.start = Button(self.root, text="Start", bg="orange", padx=25, pady=25, font=Font(family="comic sans MS", size=15), command=lambda: self.callhome()) self.start.pack(side="bottom") def createFood(self): # self.w.delete(self.food) #deleting old food. crd = self.w.coords(1) ext = [] for i in crd: ext.append(i) for j in range(-50, 50): ext.append(i + j) randx = random.randrange(20, 730) randy = random.randrange(20, 480) while randx not in ext and randy not in ext: randx = random.randrange(20, 730) randy = random.randrange(20, 480) self.food = self.w.create_line(randx, randy, randx + 12, randy, width=10, fill="yellow") def checkEaten(self): headcoords = self.w.coords(self.head) foodcoords = self.w.coords(self.food) # self.w.delete(self.food) flag = False # print(headcoords[-4]) # print(foodcoords[-4]) # print(foodcoords[-2]) if int(headcoords[-4]) in range( int(foodcoords[-4]) - 7, int(foodcoords[-2]) + 7) and int(headcoords[-3]) in range( int(foodcoords[-1]) - 10, int(foodcoords[-1] + 10)): flag = True if flag: self.grow() self.score += 10 self.scoreC.configure(text="Score\n" + str(self.score), bg="black", fg="teal", padx=25, pady=35, font=Font(family="comic sans MS", size=25)) self.w.delete(self.food) self.createFood() def grow(self): crd = self.w.coords(1) if crd[0] != crd[2]: # horizontal condition if crd[0] < crd[2]: crd[0] -= 20 else: crd[0] += 20 self.w.coords(1, *crd) else: if crd[3] < crd[1]: crd[1] += 20 else: crd[1] -= 20 self.w.coords(1, *crd) def end(self): crd = self.w.coords(1) h = self.w.coords(self.head) a = 0 while a < len(crd) - 2: if crd[a] == crd[a + 2]: if (h[0] == crd[a] and crd[a + 1] < h[1] < crd[a + 3]) or ( h[0] == crd[a] and crd[a + 1] > h[1] > crd[a + 3]): return True else: if (h[1] == crd[a + 1] and crd[a] < h[0] < crd[a + 2]) or ( h[1] == crd[a + 1] and crd[a] > h[0] > crd[a + 2]): return True a += 2 if (h[0] == 0 and 0 < h[1] < 500) or (h[1] == 0 and 0 < h[0] < 750) or ( h[1] == 510 and 0 < h[0] < 750) or (h[0] == 760 and 0 < h[1] < 500): return True return False def callhome(self): self.w.destroy() self.start.destroy() self.H.destroy() self.scoreC.destroy() self.home()
class ToolTips(object): def __init__(self, root): self.root = root self.tip = Label() # holds the tool tip text self.btn_name = '' self.animation_delay = 500 # begin animation after 0.5 seconds self.animation_speed = 15 # call __animate every 0.015 seconds self._animation = None # holds a call to __animate self.buttons_clicked = [] # holds the button text of the buttons that need tooltips self.buttons = ['Home', 'Constraint', 'View', 'RUN', 'Misc', 'Schedule 1', 'Schedule 2', 'Schedule 3', 'Schedule 4', 'Schedule 5', 'Add Course Constraint', 'Add Instructor Constraint', 'Add Constraint'] # button name paired with tool tip description self.tips = {self.buttons[0] : 'Return home.', self.buttons[1] : 'Make a custom schedule.', self.buttons[2] : 'View the schedules.', self.buttons[3] : 'Generate schedules.', self.buttons[4] : 'Misc'} # x position of a tool tip self.tip_x_pos = {self.buttons[0] : 150, self.buttons[1] : 150, self.buttons[2] : 150, self.buttons[3] : 150, self.buttons[4] : 150} # y position of a tool tip self.tip_y_pos = {self.buttons[0] : 2, self.buttons[1] : 107, self.buttons[2] : 212, self.buttons[3] : 317, self.buttons[4] : 422} # create event listeners self.root.bind('<Enter>', self.__hover_on) self.root.bind('<Leave>', self.__hover_off) self.root.bind('<Button-1>', self.__on_click) def __hover_on(self, event): """ Changes the button color and displays tool tip """ try: button = event.widget self.btn_name = button['text'] if self.btn_name in self.buttons: if not (self.btn_name == 'RUN') and \ not (button in self.buttons_clicked): button['bg'] = 'white' self.__tool_tip() except: pass def __hover_off(self, event): """ Changes button color back to normal and deletes tool tip """ try: button = event.widget self.btn_name = button['text'] if self.btn_name in self.buttons: if not (self.btn_name == 'RUN') and \ not (button in self.buttons_clicked): button['bg'] = 'SystemButtonFace' self.__stop_animation() except: pass def __stop_animation(self): """ Stops an animation. """ # cancel queued call to self.__animate self.root.after_cancel(self._animation) self.tip.destroy() # destroy tool tip label def __on_click(self, event): """ Changes button color back to normal and deletes tool tip """ try: # stop animation when a button is clicked self.__stop_animation() button = event.widget self.btn_name = button['text'] if self.btn_name.split(' ')[0] == 'Schedule': if len(self.buttons_clicked) > 0: self.buttons_clicked[0]['bg'] = 'SystemButtonFace' del self.buttons_clicked[:] button['bg'] = 'green' self.buttons_clicked.append(button) if self.btn_name == 'RUN': self.buttons_clicked[0]['bg'] = 'SystemButtonFace' except: pass def __tool_tip(self): """ Creates a tool tip label """ self.tip = Label(self.root, width = 0, height = 2, padx = 10, text = '', bg = 'green') self.tip['text'] = self.tips[self.btn_name] self.tip.pack() # initially hide the tool tip label off the screen at a -x position self.tip.place(x = -(self.tip_x_pos[self.btn_name]), \ y = self.tip_y_pos[self.btn_name]) self.__animate() def __animate(self): """ Animates the width of a tool tip label """ try: if self.tip['width'] == 0: self._animation = self.root.after(self.animation_delay, self.__animate) elif self.tip['width'] == 1: self.tip.place(x = self.tip_x_pos[self.btn_name]) self._animation = self.root.after(self.animation_speed, self.__animate) elif self.tip['width'] <= 25: self._animation = self.root.after(self.animation_speed, self.__animate) self.tip['width'] += 1 except: pass
class CallTip(object): # Responsibility for ensuring single CallTip is CallTip's instance = None def __init__(self, widget, hideOnCursorBack=True): self.widget = widget self.tipwindow = self.label = None self.parenline = self.parencol = None self.lastline = None self.hideid = self.checkhideid = None self.checkhide_after_id = None # Flag to close window when cursor moves back self.hideOnCursorBack = hideOnCursorBack def position_window(self): """Check if needs to reposition the window, and if so - do it.""" curline = int(self.widget.index("insert").split('.')[0]) if curline == self.lastline: return self.lastline = curline self.widget.see("insert") if curline == self.parenline: box = self.widget.bbox("%d.%d" % (self.parenline, self.parencol)) else: box = self.widget.bbox("%d.0" % curline) if not box: box = list(self.widget.bbox("insert")) # align to left of window box[0] = 0 box[2] = 0 x = box[0] + self.widget.winfo_rootx() + 2 y = box[1] + box[3] + self.widget.winfo_rooty() self.tipwindow.wm_geometry("+%d+%d" % (x, y)) def showtip(self, text, parenleft, parenright, *moretext): """ Show the calltip, bind events which will close it and reposition it. If moretext is given, additional labels are shown. """ if CallTip.instance is not None: CallTip.instance.hidetip() CallTip.instance = None self.text = text if self.tipwindow or not self.text: return self.widget.mark_set(MARK_RIGHT, parenright) self.parenline, self.parencol = map( int, self.widget.index(parenleft).split(".")) self.tipwindow = tw = Toplevel(self.widget) self.position_window() # remove border on calltip window tw.wm_overrideredirect(1) # Need encompassing frame so extra labels are aligned to the left. frame = Frame(tw) frame.pack() try: # This command is only needed and available on Tk >= 8.4.0 for OSX # Without it, call tips intrude on the typing process by grabbing # the focus. tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except TclError: pass self.label = Label(frame, text=self.text, justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font=self.widget['font']) self.label.pack(anchor='w', side=LEFT, fill=BOTH) # It's nice to have the option for more text. for text in moretext: label = Label(frame, text=text, justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font=self.widget['font']) label.pack(anchor='w', side=LEFT, fill=BOTH) tw.lift() # work around bug in Tk 8.5.18+ (issue #24570) self.checkhideid = self.widget.bind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhide_event) for seq in CHECKHIDE_SEQUENCES: self.widget.event_add(CHECKHIDE_VIRTUAL_EVENT_NAME, seq) self.widget.after(CHECKHIDE_TIME, self.checkhide_event) self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) for seq in HIDE_SEQUENCES: self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq) CallTip.instance = self def safecompare(self): # For unknown reasons sometimes this compare fails try: return self.widget.compare("insert", ">", MARK_RIGHT) except: return 1 def checkhide_event(self, event=None): if not self.tipwindow: # If the event was triggered by the same event that unbinded # this function, the function will be called nevertheless, # so do nothing in this case. return curline, curcol = map(int, self.widget.index("insert").split('.')) if (curline != self.parenline or (self.hideOnCursorBack and ((curline == self.parenline and curcol < self.parencol) or self.safecompare()))): self.hidetip() else: self.position_window() if self.checkhide_after_id is not None: self.widget.after_cancel(self.checkhide_after_id) self.checkhide_after_id = \ self.widget.after(CHECKHIDE_TIME, self.checkhide_event) def hide_event(self, event): if not self.tipwindow: # See the explanation in checkhide_event. return self.hidetip() def hidetip(self): if not self.tipwindow: return for seq in CHECKHIDE_SEQUENCES: self.widget.event_delete(CHECKHIDE_VIRTUAL_EVENT_NAME, seq) self.widget.unbind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhideid) self.checkhideid = None for seq in HIDE_SEQUENCES: self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq) self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideid) self.hideid = None self.label.destroy() self.label = None self.tipwindow.destroy() self.tipwindow = None self.widget.mark_unset(MARK_RIGHT) self.parenline = self.parencol = self.lastline = None CallTip.instance = None def is_active(self): return bool(self.tipwindow)
def inicio(c): global ventana2, Labeli, Labelt, panel global img0, img1, imgF img0=PhotoImage(file="00.gif") # Reads photos img1=PhotoImage(file="11.gif") imgF=PhotoImage(file="FF.gif") if c: ventana2=Toplevel(ventana) ventana2.title("MANITOR") ventana2.configure(bg="white") ventana2.geometry("1000x600+5+40") Labelt=Label(ventana2,text='BIENVENIDO ', # ventana2 TEXTO fg="black",bg="white",font=("Helvetica 36 ")) ventana2.columnconfigure(0,weight=1) Labelt.grid(row=1,column=0) Labeli=Label(ventana2,image=img1) # ventana2 IMAGEN ventana2.columnconfigure(0,weight=1) ventana2.update() Labeli.grid(row=2,column=0) else:#Toda esta parte no es necesaria se podria borrar hasta el update, ya que es un estado inical que nunca se muestra igual que arriba Labelt.config(text='BIENVENIDO ') ventana2.update() Labeli=Label(ventana2,image=img1) ventana2.columnconfigure(0,weight=1) Labeli.grid(row=2,column=0) Labeli.config(image=img1) Labeli.image=img1 ventana2.update() ventana.iconify() # Turns window into an icon while 1: ## cur.execute("INSERT INTO manitor VALUES(nextval('usuario_sequence'), current_timestamp, ' inicio ')") Labeli.destroy() ventana2.update() Labelt.config(text='BIENVENIDO \n Por favor moje sus manos con agua') ventana2.update() video000 () ventana2.update() Labelt.config(text='Deposite jabón en la mano') ## cur.execute("INSERT INTO manitor VALUES(nextval('usuario_sequence'), current_timestamp, ' nuevo usuario ')") ventana2.update() def cero(): b,auxType = contadorMovimiento.funcionMovimientoEnRegion(y[1],3,2,lower,upper) instruction = falseType(b,auxType,Labelt,Labeli,img0,imgF) if not instruction: inicio(0) Thread(target=cero).start() Thread(target=video00()).start() ######################## instruccion 1 Labeli.destroy() Labelt.config(text='Frote las palmas de las manos \n entre sí') ventana2.update() def primero(): d,auxType = contadorMovimiento.funcionMovimientoEnRegion(y[1],3,2,lower,upper) instruction = falseType(d,auxType,Labelt,Labeli,img0,imgF) if not instruction: inicio(0) Thread(target=primero).start() Thread(target=video1()).start() ########################## instruccion2 ## ## Labeli.destroy() ## Labelt.config(text='Frote la palma de la mano derecha \n contra el dorso de la mano izquierda \n entrelazando los dedos y viceversa') ## panel = Label(ventana2) ## def segundo(): ## e,auxType = contadorMovimiento.funcionMovimientoEnRegion(y[1],10,2,lower,upper) ## instruction = falseType(e,auxType,Labelt,Labeli,img0,imgF) ## if not instruction: ## inicio(0) ## ## Thread(target=segundo).start() ## Thread(target=video1()).start() ## ## time.sleep(10) ######################## fin instrucciones ## Labeli=Label(ventana2,image=img12) ventana2.columnconfigure(0,weight=1) Labeli.grid(row=2,column=0) ventana2.update() Labelt.config(text='Sus manos son seguras') ## Labeli.config(image=img12) ## Labeli.image=img12 ventana2.update() time.sleep(5)
class KeyboardEntry: """Mixin class that can be used to add the ability to type values for widget. When the cursor enters the widget the focus is set to the widget and the widget that had the focus previousy is saved in .lastFocus. When the cursor leaves the widget focus is restored to self.lastFocus. key_cb(event) is called upon KeyRelease events. If this is the first keytroke an undecorated window is created next to the cursor and handleKeyStroke(event) is called. This method should be subclassed to modify the way the string is typed in (see thumbwheel.py for an example of handling numbers only). When the Return key is pressed, the entry window is destroyed and if the typed striong is not empty self.callSet(self.typedValue) is called. If the cursor moves out of the widget before Rrturn is pressed the value in the entry window is discarded and the entry window is destroyed. """ def __init__(self, widgets, callSet): # callSet is a function taking one argument (string) which will be # when the Returnm key is hit (if the typed string is not empty) # widgets is a list of Tkinter wigets for which <Enter>, <Leave> # <Return> and <KeyRelease> are handled. These widgets has to exist # before thsi constructor can be called assert callable(callSet) self.callSet = callSet for w in widgets: w.bind("<Enter>", self.enter_cb) w.bind("<Leave>", self.leave_cb) w.bind("<Return>", self.return_cb) w.bind("<KeyRelease>", self.key_cb) self.typedValue = '' # string accumulating valuescharacters typed self.lastFocus = None # widget to which the focus will be restored # when the mouse leaves the widget self.topEntry = None # top level for typing values self.typedValueTK = None #Tk label used as entry for value def key_cb(self, event=None): # call back function for keyboard events (except for Return) # handle numbers to set value key = event.keysym if key=='Return': return #print 'Key:', key if len(self.typedValue)==0 and self.topEntry is None: # create Tk label showing typed value x = event.x y = event.y #print 'create entry' self.topEntry = Toplevel() self.topEntry.overrideredirect(1) w = event.widget if event.x >= 0: self.topEntry.geometry('+%d+%d'%(w.winfo_rootx() + event.x+10, w.winfo_rooty() + event.y)) else: self.topEntry.geometry('+%d+%d'%(w.winfo_rootx() +10, w.winfo_rooty() )) self.typedValueTK = Label( master=self.topEntry, text='', relief='sunken', bg='yellow') self.typedValueTK.pack() self.handleKeyStroke(event) def leave_cb(self, event=None): # make sure widget gets keyboard events # print 'leave', event.widget if self.topEntry: self.typedValueTK.destroy() self.topEntry.destroy() self.topEntry = None self.typedValue = '' if self.lastFocus: #print 'restoring focus' if widgetsOnBackWindowsCanGrabFocus is False: lActiveWindow = self.lastFocus.focus_get() if lActiveWindow is not None \ and ( lActiveWindow.winfo_toplevel() != self.lastFocus.winfo_toplevel() ): return self.lastFocus.focus_set() self.lastFocus = None event.widget.config(cursor='') def enter_cb(self, event=None): # make sure widget gets keyboard events #print 'enter', event.widget if widgetsOnBackWindowsCanGrabFocus is False: lActiveWindow = event.widget.focus_get() if lActiveWindow is not None \ and ( lActiveWindow.winfo_toplevel() != event.widget.winfo_toplevel() ): return if self.lastFocus is None: #print 'setting focus' self.lastFocus = self.focus_lastfor() event.widget.focus_set() event.widget.config(cursor='xterm') def return_cb(self, event): # return should destroy the topEntry #print "return_cb" if self.typedValueTK is not None: self.typedValueTK.destroy() if self.topEntry is not None: self.topEntry.destroy() self.topEntry = None if len(self.typedValue): #print 'setting to', self.type(self.typedValue) self.callSet(self.typedValue) self.typedValue = '' ## TO BE SUBCLASSED def handleKeyStroke(self, event): # by default we handle delete character keys key = event.keysym if key=='BackSpace' or key=='Delete': self.typedValue = self.typedValue[:-1] self.typedValueTK.configure(text=self.typedValue)
class CallTip: def __init__(self, widget): self.widget = widget self.tipwindow = self.label = None self.parenline = self.parencol = None self.lastline = None self.hideid = self.checkhideid = None self.checkhide_after_id = None def position_window(self): """Check if needs to reposition the window, and if so - do it.""" curline = int(self.widget.index("insert").split('.')[0]) if curline == self.lastline: return self.lastline = curline self.widget.see("insert") if curline == self.parenline: box = self.widget.bbox("%d.%d" % (self.parenline, self.parencol)) else: box = self.widget.bbox("%d.0" % curline) if not box: box = list(self.widget.bbox("insert")) # align to left of window box[0] = 0 box[2] = 0 x = box[0] + self.widget.winfo_rootx() + 2 y = box[1] + box[3] + self.widget.winfo_rooty() self.tipwindow.wm_geometry("+%d+%d" % (x, y)) def showtip(self, text, parenleft, parenright): """Show the calltip, bind events which will close it and reposition it. """ # Only called in CallTips, where lines are truncated self.text = text if self.tipwindow or not self.text: return self.widget.mark_set(MARK_RIGHT, parenright) self.parenline, self.parencol = map( int, self.widget.index(parenleft).split(".")) self.tipwindow = tw = Toplevel(self.widget) self.position_window() # remove border on calltip window tw.wm_overrideredirect(1) try: # This command is only needed and available on Tk >= 8.4.0 for OSX # Without it, call tips intrude on the typing process by grabbing # the focus. tw.tk.call("::tk::unsupported::MacWindowStyle", "style", tw._w, "help", "noActivates") except TclError: pass self.label = Label(tw, text=self.text, justify=LEFT, background="#ffffe0", relief=SOLID, borderwidth=1, font = self.widget['font']) self.label.pack() tw.lift() # work around bug in Tk 8.5.18+ (issue #24570) self.checkhideid = self.widget.bind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhide_event) for seq in CHECKHIDE_SEQUENCES: self.widget.event_add(CHECKHIDE_VIRTUAL_EVENT_NAME, seq) self.widget.after(CHECKHIDE_TIME, self.checkhide_event) self.hideid = self.widget.bind(HIDE_VIRTUAL_EVENT_NAME, self.hide_event) for seq in HIDE_SEQUENCES: self.widget.event_add(HIDE_VIRTUAL_EVENT_NAME, seq) def checkhide_event(self, event=None): if not self.tipwindow: # If the event was triggered by the same event that unbinded # this function, the function will be called nevertheless, # so do nothing in this case. return curline, curcol = map(int, self.widget.index("insert").split('.')) if curline < self.parenline or \ (curline == self.parenline and curcol <= self.parencol) or \ self.widget.compare("insert", ">", MARK_RIGHT): self.hidetip() else: self.position_window() if self.checkhide_after_id is not None: self.widget.after_cancel(self.checkhide_after_id) self.checkhide_after_id = \ self.widget.after(CHECKHIDE_TIME, self.checkhide_event) def hide_event(self, event): if not self.tipwindow: # See the explanation in checkhide_event. return self.hidetip() def hidetip(self): if not self.tipwindow: return for seq in CHECKHIDE_SEQUENCES: self.widget.event_delete(CHECKHIDE_VIRTUAL_EVENT_NAME, seq) self.widget.unbind(CHECKHIDE_VIRTUAL_EVENT_NAME, self.checkhideid) self.checkhideid = None for seq in HIDE_SEQUENCES: self.widget.event_delete(HIDE_VIRTUAL_EVENT_NAME, seq) self.widget.unbind(HIDE_VIRTUAL_EVENT_NAME, self.hideid) self.hideid = None self.label.destroy() self.label = None self.tipwindow.destroy() self.tipwindow = None self.widget.mark_unset(MARK_RIGHT) self.parenline = self.parencol = self.lastline = None def is_active(self): return bool(self.tipwindow)
class KeyboardEntry: """Mixin class that can be used to add the ability to type values for widget. When the cursor enters the widget the focus is set to the widget and the widget that had the focus previousy is saved in .lastFocus. When the cursor leaves the widget focus is restored to self.lastFocus. key_cb(event) is called upon KeyRelease events. If this is the first keytroke an undecorated window is created next to the cursor and handleKeyStroke(event) is called. This method should be subclassed to modify the way the string is typed in (see thumbwheel.py for an example of handling numbers only). When the Return key is pressed, the entry window is destroyed and if the typed striong is not empty self.callSet(self.typedValue) is called. If the cursor moves out of the widget before Rrturn is pressed the value in the entry window is discarded and the entry window is destroyed. """ def __init__(self, widgets, callSet): # callSet is a function taking one argument (string) which will be # when the Returnm key is hit (if the typed string is not empty) # widgets is a list of Tkinter wigets for which <Enter>, <Leave> # <Return> and <KeyRelease> are handled. These widgets has to exist # before thsi constructor can be called assert callable(callSet) self.callSet = callSet for w in widgets: w.bind("<Enter>", self.enter_cb) w.bind("<Leave>", self.leave_cb) w.bind("<Return>", self.return_cb) w.bind("<KeyRelease>", self.key_cb) self.typedValue = '' # string accumulating valuescharacters typed self.lastFocus = None # widget to which the focus will be restored # when the mouse leaves the widget self.topEntry = None # top level for typing values self.typedValueTK = None #Tk label used as entry for value def key_cb(self, event=None): # call back function for keyboard events (except for Return) # handle numbers to set value key = event.keysym if key == 'Return': return #print 'Key:', key if len(self.typedValue) == 0 and self.topEntry is None: # create Tk label showing typed value x = event.x y = event.y #print 'create entry' self.topEntry = Toplevel() self.topEntry.overrideredirect(1) w = event.widget if event.x >= 0: self.topEntry.geometry('+%d+%d' % (w.winfo_rootx() + event.x + 10, w.winfo_rooty() + event.y)) else: self.topEntry.geometry('+%d+%d' % (w.winfo_rootx() + 10, w.winfo_rooty())) self.typedValueTK = Label(master=self.topEntry, text='', relief='sunken', bg='yellow') self.typedValueTK.pack() self.handleKeyStroke(event) def leave_cb(self, event=None): # make sure widget gets keyboard events # print 'leave', event.widget if self.topEntry: self.typedValueTK.destroy() self.topEntry.destroy() self.topEntry = None self.typedValue = '' if self.lastFocus: #print 'restoring focus' if widgetsOnBackWindowsCanGrabFocus is False: lActiveWindow = self.lastFocus.focus_get() if lActiveWindow is not None \ and ( lActiveWindow.winfo_toplevel() != self.lastFocus.winfo_toplevel() ): return self.lastFocus.focus_set() self.lastFocus = None event.widget.config(cursor='') def enter_cb(self, event=None): # make sure widget gets keyboard events #print 'enter', event.widget if widgetsOnBackWindowsCanGrabFocus is False: lActiveWindow = event.widget.focus_get() if lActiveWindow is not None \ and ( lActiveWindow.winfo_toplevel() != event.widget.winfo_toplevel() ): return if self.lastFocus is None: #print 'setting focus' self.lastFocus = self.focus_lastfor() event.widget.focus_set() event.widget.config(cursor='xterm') def return_cb(self, event): # return should destroy the topEntry #print "return_cb" if self.typedValueTK is not None: self.typedValueTK.destroy() if self.topEntry is not None: self.topEntry.destroy() self.topEntry = None if len(self.typedValue): #print 'setting to', self.type(self.typedValue) self.callSet(self.typedValue) self.typedValue = '' ## TO BE SUBCLASSED def handleKeyStroke(self, event): # by default we handle delete character keys key = event.keysym if key == 'BackSpace' or key == 'Delete': self.typedValue = self.typedValue[:-1] self.typedValueTK.configure(text=self.typedValue)
class Interfaz_Ventana(object): """ Interfaz grafica del juego. """ def __init__(self): pygame.init() self.tk_window = Tk() self.label_imagen = Label() self.surface_cartas = {} def obtener_entero(self, mensaje, titulo="", intervalo=[]): """ Pide al usuario que ingrese un numero entero, mostrando el mensaje pasado por parametro. Si se recibe un intervalo, el numero debe pertenecer al mismo. :param mensaje: Mensaje a mostrar en la ventana al pedir el numero. :param titulo: Titulo de la ventana. :param intervalo: Lista de dos numeros, de la forma [min, max]. Si se recibe, el numero que se pida debe ser mayor o igual a min y menor o igual a max. Se seguira pidiendo al usuario que ingrese un numero hasta que se cumplan las condiciones. :return: Numero entero ingresado por el usuario. """ if not intervalo: return tkSimpleDialog.askinteger(titulo, mensaje, parent=self.tk_window) return tkSimpleDialog.askinteger(titulo, mensaje, parent=self.tk_window, minvalue=intervalo[0], maxvalue=intervalo[1]) def mostrar_informacion(self, mensaje, titulo=""): """ Muestra una ventana con el mensaje pasado por parametro. :param mensaje: Mensaje que se mostrara en la ventana. :param titulo: Titulo de la ventana. :return: No tiene valor de retorno. """ tkMessageBox.askquestion(titulo, mensaje, type=tkMessageBox.OK, icon="info") def preguntar_si_no(self, mensaje, titulo=""): """ Muestra el mensaje recibido por parametro y pide que se conteste si o no. Devuelve True si se contesto si, False si se contesto no. :param mensaje: Mensaje a mostrar en la ventana. :param titulo: Titulo de la ventana. :return: Booleano que indica si se contesto si. """ resultado = tkMessageBox.askquestion(titulo, mensaje, type=tkMessageBox.YESNO) return resultado == "yes" def mostrar_carta(self, carta, titulo=""): """ Muestra una ventana con la imagen que corresponde a la carta pasada por parametro. :param carta: Carta que se quiere mostrar su imagen correspondiente. :param titulo: Titulo de la ventana. :return: No tiene valor de retorno. """ self.label_imagen.destroy() c = self.__obtener_surface_carta(carta) from PIL import Image, ImageTk imagen = Image.fromstring('RGBA', c.get_rect()[2:], pygame.image.tostring(c, "RGBA")) foto = ImageTk.PhotoImage(imagen) self.label_imagen = Label(image=foto) self.label_imagen.image = foto # keep a reference! self.label_imagen.pack() self.tk_window.title(titulo) self.tk_window.update() sleep(2) def __obtener_surface_carta(self, carta): """ Devuelve la imagen correspondiente a la carta pasada por parametro. Si la imagen no esta guardada, se genera y se guarda. :param carta: Carta que se quiere mostrar su imagen. :return: Surface con la imagen correspondiente a la carta. """ str_carta = str(carta) if not self.surface_cartas.has_key(str_carta): self.surface_cartas[str_carta] = creador_cartas.generar_imagen_carta(carta) return self.surface_cartas[str_carta] def __dibujar_cartas_personaje(self, background, zona_campo, posicion, rotacion): for carta in zona_campo: fuente = pygame.font.Font("resources/agfarotissemiserif.ttf", 30) if carta: surface_carta = self.__obtener_surface_carta(carta) surface_carta = pygame.transform.scale(surface_carta, (ANCHO_CARTA_TABLERO, ALTO_CARTA_TABLERO)) label_poder = fuente.render(str(carta.obtener_poder()), 1, (0, 0, 0)) surface_carta.blit(label_poder, (POSICION_ANCHO_LABEL_PODER, POSICION_ALTO_LABEL_PODER)) surface_carta = pygame.transform.rotate(surface_carta, rotacion) background.blit(surface_carta, posicion) posicion[1] += LADO_AREA_CARTA def __dibujar_campo_frontal(self, background, posicion_frontal_izquierda, rotacion, campo_frontal): posicion = [posicion_frontal_izquierda + LADO_AREA_CARTA / 12, LADO_AREA_CARTA + (5 * LADO_AREA_CARTA) / 24] self.__dibujar_cartas_personaje(background, campo_frontal, posicion, rotacion) def __dibujar_retaguardia(self, background, posicion_frontal_izquierda, rotacion, retaguardia): posicion = [posicion_frontal_izquierda + LADO_AREA_CARTA / 12, (3 * LADO_AREA_CARTA) / 2 + (5 * LADO_AREA_CARTA) / 24] self.__dibujar_cartas_personaje(background, retaguardia, posicion, rotacion) def __dibujar_climax(self, background, posicion_frontal_izquierda, rotacion, carta_climax): posicion = [posicion_frontal_izquierda + (5 * LADO_AREA_CARTA) / 24, 2 * LADO_AREA_CARTA + LADO_AREA_CARTA / 12] if not carta_climax: return self.__dibujar_carta_individual(background, carta_climax, posicion, rotacion) def __dibujar_carta_individual(self, background, discard_top, posicion, rotacion): surface_carta = self.__obtener_surface_carta(discard_top) surface_carta = pygame.transform.scale(surface_carta, (ANCHO_CARTA_TABLERO, ALTO_CARTA_TABLERO)) surface_carta = pygame.transform.rotate(surface_carta, rotacion) background.blit(surface_carta, posicion) def __dibujar_descarte_weiss(self, background, posicion_frontal_izquierda, rotacion, discard_top): posicion = [posicion_frontal_izquierda + LADO_AREA_CARTA / 12, 4 * LADO_AREA_CARTA + (5 * LADO_AREA_CARTA) / 24] if not discard_top: return self.__dibujar_carta_individual(background, discard_top, posicion, rotacion) def __dibujar_descarte_schwarz(self, background, posicion_frontal_izquierda, rotacion, discard_top): posicion = [posicion_frontal_izquierda + LADO_AREA_CARTA / 12, (5 * LADO_AREA_CARTA) / 24] if not discard_top: return self.__dibujar_carta_individual(background, discard_top, posicion, rotacion) def __dibujar_clock_weiss(self, background, posicion_frontal_izquierda, rotacion, clock): posicion = [posicion_frontal_izquierda + LADO_AREA_CARTA / 12, LADO_AREA_CARTA + (3 * LADO_AREA_CARTA) / 24] for carta in clock: if carta: self.__dibujar_carta_individual(background, carta, posicion, rotacion) posicion[1] += (3 * ANCHO_CARTA_TABLERO) / 4 def __dibujar_clock_schwarz(self, background, posicion_frontal_izquierda, rotacion, clock): posicion = [posicion_frontal_izquierda + LADO_AREA_CARTA / 12, 4 * LADO_AREA_CARTA - (3 * LADO_AREA_CARTA) / 24 - ANCHO_CARTA_TABLERO] for carta in clock: if carta: self.__dibujar_carta_individual(background, carta, posicion, rotacion) posicion[1] -= (3 * ANCHO_CARTA_TABLERO) / 4 def __dibujar_nivel_weiss(self, background, posicion_frontal_izquierda, rotacion, nivel): posicion = [posicion_frontal_izquierda + LADO_AREA_CARTA / 12, LADO_AREA_CARTA / 12] for carta in nivel: if carta: self.__dibujar_carta_individual(background, carta, posicion, rotacion) posicion[0] += ANCHO_CARTA_TABLERO / 3 def __dibujar_nivel_schwarz(self, background, posicion_frontal_izquierda, rotacion, nivel): posicion = [posicion_frontal_izquierda + LADO_AREA_CARTA / 3, 4 * LADO_AREA_CARTA + LADO_AREA_CARTA / 12] for carta in nivel: if carta: self.__dibujar_carta_individual(background, carta, posicion, rotacion) posicion[0] -= ANCHO_CARTA_TABLERO / 3 def __dibujar_recursos_weiss(self, background, posicion_frontal_izquierda, rotacion, recursos): posicion = [posicion_frontal_izquierda + LADO_AREA_CARTA / 4, LADO_AREA_CARTA / 12] for carta in recursos: if carta: self.__dibujar_carta_individual(background, carta, posicion, rotacion) posicion[0] -= ANCHO_CARTA_TABLERO / 3 def __dibujar_recursos_schwarz(self, background, posicion_frontal_izquierda, rotacion, recursos): posicion = [posicion_frontal_izquierda + LADO_AREA_CARTA / 5, 4 * LADO_AREA_CARTA + LADO_AREA_CARTA / 12] for carta in recursos: if carta: self.__dibujar_carta_individual(background, carta, posicion, rotacion) posicion[0] += ANCHO_CARTA_TABLERO / 3 def __generar_tablero(self, tablero): background = pygame.image.load("resources/background.png") background = pygame.transform.scale(background, (ANCHO_BACKGROUND, ALTO_BACKGROUND)) campo_frontal = tablero.obtener_todas_campo_frontal() posicion_frontal_izquierda = 0 self.__dibujar_clock_weiss(background, posicion_frontal_izquierda, -90, tablero.obtener_cartas_clock(WEISS)) self.__dibujar_nivel_weiss(background, posicion_frontal_izquierda, 0, tablero.obtener_cartas_nivel(WEISS)) posicion_frontal_izquierda += LADO_AREA_CARTA self.__dibujar_climax(background, posicion_frontal_izquierda, 0, tablero.obtener_climax(WEISS)) self.__dibujar_descarte_weiss(background, posicion_frontal_izquierda, -90, tablero.obtener_tope_espera(WEISS)) posicion_frontal_izquierda += LADO_AREA_CARTA self.__dibujar_retaguardia(background, posicion_frontal_izquierda, -90, tablero.obtener_cartas_retaguardia(WEISS)) posicion_frontal_izquierda += LADO_AREA_CARTA self.__dibujar_recursos_weiss(background, posicion_frontal_izquierda, 0, tablero.obtener_cartas_recursos(WEISS)) self.__dibujar_campo_frontal(background, posicion_frontal_izquierda, -90, tablero.obtener_cartas_campo_frontal(WEISS)) posicion_frontal_izquierda += LADO_AREA_CARTA self.__dibujar_campo_frontal(background, posicion_frontal_izquierda, 90, tablero.obtener_cartas_campo_frontal(SCHWARZ)[::-1]) self.__dibujar_recursos_schwarz(background, posicion_frontal_izquierda, 180, tablero.obtener_cartas_recursos(SCHWARZ)) posicion_frontal_izquierda += LADO_AREA_CARTA self.__dibujar_retaguardia(background, posicion_frontal_izquierda, 90, tablero.obtener_cartas_retaguardia(SCHWARZ)[::-1]) posicion_frontal_izquierda += LADO_AREA_CARTA self.__dibujar_descarte_schwarz(background, posicion_frontal_izquierda, 90, tablero.obtener_tope_espera(SCHWARZ)) self.__dibujar_climax(background, posicion_frontal_izquierda, 180, tablero.obtener_climax(SCHWARZ)) posicion_frontal_izquierda += LADO_AREA_CARTA self.__dibujar_clock_schwarz(background, posicion_frontal_izquierda, 90, tablero.obtener_cartas_clock(SCHWARZ)) self.__dibujar_nivel_schwarz(background, posicion_frontal_izquierda, 180, tablero.obtener_cartas_nivel(SCHWARZ)) return pygame.transform.scale(background, RESOLUCION) def actualizar_tablero(self, tablero): """ Actualiza y muestra el tablero de juego. :param tablero: TableroJuego del que se quiere mostrar el estado. :return: No tiene valor de retorno. """ surface_tablero = self.__generar_tablero(tablero) pantalla = pygame.display.set_mode(surface_tablero.get_size()) pantalla.blit(surface_tablero, (0, 0)) pygame.display.set_caption("Tablero") pygame.display.flip() def lanzar_dado(self): """ Simula el lanzamiento de un dado de 6 caras y muestra en una ventana informativa el resultado obtenido. :return: Entero de 1 a 6, que es el resultado de la tirada de dado. """ resultado = random.randrange(1, 6) self.mostrar_informacion("Salio: " + str(resultado), "Dado lanzado") return resultado def lanzar_moneda(self): """ Simula el lanzamiento de una moneda y muestra el resultado en una ventana informativa. :return: String con las contantes CARA o CRUZ, que es el resultado del lanzamiento de la moneda. """ resultado = random.choice([CARA, CRUZ]) self.mostrar_informacion("Salio: " + resultado, "Moneda lanzada") return resultado
class Example(Frame): def __init__(self, parent, queue, musicplayer): Frame.__init__(self, parent) self.parent = parent self.weight = 500 self.height = 400 self.queue = queue self.musicplayer = musicplayer self.pictures = ["hd_1.jpg", "hd_2.jpg", "hd_3.jpg", "hd_4.jpg", "hd_5.jpg"]; self.centerWindow() self.initUI() ''' self.showPic = 1 self.playSlides() ''' def initUI(self): self.parent.title("Example") self.pack(fill=BOTH, expand = 1) self.style = Style() self.style.theme_use("default") frame = Frame(self, relief=Tkinter.RAISED, borderwidth=1) frame.pack(fill=BOTH, expand=1) okButton = Button(self, text = "OK") okButton.place(x = self.width - 200, y = self.height - 100) quitButton = Button(self.parent, text = "QUIT") quitButton.place(x = self.width - 100, y = self.height - 100) scale = 0.75 self.wow_pic = Image.open("hd_1.jpg") self.wow_pic = self.wow_pic.resize((int(self.width*scale), int(self.height*scale))) self.wow_pic_tk = ImageTk.PhotoImage(self.wow_pic) self.label_wow_pic = Label(self, image = self.wow_pic_tk) self.label_wow_pic.image = self.wow_pic_tk self.label_wow_pic.place(x = 10, y = 10) info_x = int(self.width*scale) + 20 label_text_area = Tkinter.Label(self, text = "Message received:") label_text_area.place(x = info_x, y = 10) self.text_area = Tkinter.Text(self, height = 10, width = 40) self.text_area.place(x = info_x, y = 30) def centerWindow(self): self.width = self.parent.winfo_screenwidth() self.height = self.parent.winfo_screenheight() self.queue.put("Width: " + str(self.width) + " Height: " + str(self.height)) self.parent.geometry('%dx%d+%d+%d' % (self.width, self.height, 0, 0)) def insertText(self, str): self.text_area.insert(Tkinter.INSERT, "\n" + str) def showPicture(self, img_name): self.label_wow_pic.destroy() scale = 0.75 self.wow_pic = Image.open(img_name) self.wow_pic = self.wow_pic.resize((int(self.width*scale), int(self.height*scale))) self.wow_pic_tk = ImageTk.PhotoImage(self.wow_pic) self.label_wow_pic = Label(self, image = self.wow_pic_tk) self.label_wow_pic.image = self.wow_pic_tk self.label_wow_pic.place(x = 10, y = 10) def playMusic(self): pygame.mixer.init() pygame.mixer.music.load("1.mp3") pygame.mixer.music.play() def pauseMusic(self): self.musicthread = threading.Thread(target = self.musicplayer.play) self.musicthread.start() def playSlides(self): self.showPic = 1 self.currentSlideNo = 0; self.showSlidesThread = threading.Thread(target = self.playSlidesClock) self.showSlidesThread.start() def playSlidesClock(self): #self.queue.put("next_picture"); while True: if(self.showPic == 0): break; self.queue.put("next_picture"); time.sleep(5); def nextSlide(self): self.currentSlideNo = (self.currentSlideNo + 1) % len(self.pictures) self.showPicture(self.pictures[self.currentSlideNo]) def processIncoming(self): while self.queue.qsize(): try: msg = self.queue.get(0) print "From queue, get msg:", msg if(msg == "show_text"): self.insertText("I need to show a text") elif(msg == "show_picture"): self.showPic = 1 self.playSlides() elif(msg == "play_music"): self.playMusic() elif(msg == "pause_music"): self.pauseMusic() elif(msg == "next_picture"): self.nextSlide() else: self.insertText(msg) except: pass
def destroy(self): self.greenlet.kill() Label.destroy(self)