Ejemplo n.º 1
0
def expired(cur_dir, amount):
    """
    Displays a "deadline expired" picture
    """
    root = Tk()
    root.focus_set()
    # Get the size of the screen and place the splash screen in the center
    img = Image.open(str(cur_dir) + '/Images/Expired.gif')
    width = img.size[0]
    height = img.size[1]
    flog = root.winfo_screenwidth()/2-width/2
    blog = root.winfo_screenheight()/2-height/2
    root.overrideredirect(True)
    root.geometry('%dx%d+%d+%d' % (width*1, height + 44, flog, blog))
    # Pack a canvas into the top level window.
    # This will be used to place the image
    expired_canvas = Canvas(root)
    expired_canvas.pack(fill="both", expand=True)
    # Open the image
    imgtk = PhotoImage(img)
    # Get the top level window size
    # Need a call to update first, or else size is wrong
    root.update()
    cwidth = root.winfo_width()
    cheight =  root.winfo_height()
    # create the image on the canvas
    expired_canvas.create_image(cwidth/2, cheight/2.1, image=imgtk)
    Button(root, text='Deadline Expired by ' + str(amount
          ) + '. Assignment Submitted, time '\
          'noted', width=80, height=2, command=root.destroy).pack()
    root.after(5000, root.destroy)
    root.mainloop()
Ejemplo n.º 2
0
def success(cur_dir):
    """
    Displays a "successful submission" picture
    """
    root = Tk()
    root.focus_set()
    # Get the size of the screen and place the splash screen in the center
    img = Image.open(str(cur_dir) + '/Images/Success.gif')
    width = img.size[0]
    height = img.size[1]
    flog = (root.winfo_screenwidth()/2-width/2)
    blog = (root.winfo_screenheight()/2-height/2)
    root.overrideredirect(1)
    root.geometry('%dx%d+%d+%d' % (width, height, flog, blog))
    # Pack a canvas into the top level window.
    # This will be used to place the image
    success_canvas = Canvas(root)
    success_canvas.pack(fill = "both", expand = True)
    # Open the image
    imgtk = PhotoImage(img)
    # Get the top level window size
    # Need a call to update first, or else size is wrong
    root.update()
    cwidth = root.winfo_width()
    cheight =  root.winfo_height()
    # create the image on the canvas
    success_canvas.create_image(cwidth/2, cheight/2, image = imgtk)
    root.after(4000, root.destroy)
    root.mainloop()
Ejemplo n.º 3
0
    def _setupDisplay(self, root, config):
        """Set screen size and add background image
        
        root -- the Tk instance of the application
        config -- ConfigParser containing application settings

        """
        fullscreen = config.getboolean(ini.general, ini.fullscreen)
        bgimage = ini.getPath(config.get(ini.general, ini.bgimage))
        
        image = Image.open(bgimage)
        backgroundIm = ImageTk.PhotoImage(image)        
        
        if(fullscreen):
            screenwidth = root.winfo_screenwidth()
            screenheight = root.winfo_screenheight()
            (w, h) = image.size
            self._scalefactor = (screenwidth / float(w), screenheight / float(h))
            image = image.resize((screenwidth, screenheight))
        else:
            (screenwidth, screenheight) = image.size
            self._scalefactor = (1, 1)
            
        geom = "{}x{}+{}+{}".format(screenwidth, screenheight, 0, 0)
        root.geometry(geom)
        root.overrideredirect(1)
        
        background = Canvas(root, width = screenwidth, height = screenheight)
        self._canvas = background
        background.pack()
        backgroundIm = ImageTk.PhotoImage(image)
        self._backgroundIm = backgroundIm
        background.create_image(0,0, image = backgroundIm, anchor = NW)
Ejemplo n.º 4
0
    def __init_window(self, height, width):
        self.master.title = "Ray Py"
        canvas = Canvas(self.master, width=width, height=height)
        canvas.pack(side=TOP)
        self.img = PhotoImage(width=width, height=height)
        canvas.create_image((width / 2, height / 2),
                            image=self.img,
                            state="normal")
        self.startButton = Button(self.master,
                                  text="Render",
                                  command=lambda: self.__onStartPressed())
        self.startButton.pack(side=RIGHT)
        self.resetButton = Button(self.master,
                                  text="Reset",
                                  command=lambda: self.__onResetPressed())
        self.resetButton.config(state="disabled")
        self.resetButton.pack(side=RIGHT)

        self.listbox = Listbox(self.master, height=5)
        self.listbox.bind('<<ListboxSelect>>', self.__selectTracer)
        self.listbox.insert(END, "Simple", "Shadow", "ShadingShadow",
                            "Recursive", "PathTracer")
        self.listbox.pack(side=LEFT)

        self.listbox.selection_set(0)
        self.listbox.activate(0)
        self.listbox.focus_set()
Ejemplo n.º 5
0
class ImageView(BaseView):
    def __init__(self, manager):
        self.viewname = 'imageview'
        BaseView.__init__(self, manager)

    def pack_view(self, *args, **kwargs):
        layout = kwargs.get('layout', 2)
        image_object = kwargs['image_object']
        image_no = kwargs.get('image_no', None)

        left_frame = self.display_left(flexible=True)

        _display_idx = self.manager.get_display_index()
        _display_size = (self.config.DISPLAY_SIZE[_display_idx][0], self.config.DISPLAY_SIZE[_display_idx][1])
        self.manager.log('display size', _display_size)
        self._imgtk = ImageTk.PhotoImage(image_object.resize(_display_size))

        # # self.frame = Frame(self.master)
        # self.frame = Frame(self.master, bg='white', width=_display_size[0], height=_display_size[1])
        # self.frame.grid_propagate(0)
        left_frame.config(bg='white', width=_display_size[0], height=_display_size[1])

        self.canvas = Canvas(left_frame, width=_display_size[0], height=_display_size[1], bg='red')
        # self.canvas.grid_propagate(0)
        self.canvas.place(relx=0.5, rely=0.5, anchor=CENTER)
        self.canvas.create_image(2, 2, image=self._imgtk, anchor='nw')
        if image_no is not None:
            self.canvas.create_text(self._imgtk.width() * 0.9, self._imgtk.height() * 0.9, text="Image No: " + str(image_no),
                                fill="white")
        if layout == 2:
            bottom_frame = self.display_bottom(True)

        self.add_next_action_btn(lambda: self.done())
        self.display()
class MapRenderer:
    def __init__(self, config=config, **kwargs):
        self.config = config
        self.__dict__.update(kwargs)
        self.map = Map(**kwargs)

    @property
    def canvas_width(self):
        return self.map.width * self.map.block_width

    @property
    def canvas_height(self):
        return self.map.height * self.map.block_height

    def init_canvas(self, parent=None):
        if parent == None:
            parent = self.parent
        if hasattr(self, 'canvas'):
            pass
        else:
            self.canvas = Canvas(parent)
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

    def kill_canvas(self):
        if hasattr(self, 'canvas'):
            self.canvas.destroy()

    def draw(self):
        self.canvas.configure(width=self.canvas_width, height=self.canvas_height)
        for i in xrange(len(self.map.blockdata)):
            block_x = i % self.map.width
            block_y = i / self.map.width
            self.draw_block(block_x, block_y)

    def draw_block(self, block_x, block_y):
        # the canvas starts at 4, 4 for some reason
        # probably something to do with a border
        index, indey = 4, 4

        # Draw one block (4x4 tiles)
        block = self.map.blockdata[block_y * self.map.width + block_x]

        # Ignore nonexistent blocks.
        if block >= len(self.map.tileset.blocks): return

        for j, tile in enumerate(self.map.tileset.blocks[block]):
            try:
                # Tile gfx are split in half to make vram mapping easier
                if tile >= 0x80:
                    tile -= 0x20
                tile_x = block_x * self.map.block_width + (j % 4) * 8
                tile_y = block_y * self.map.block_height + (j / 4) * 8
                self.canvas.create_image(index + tile_x, indey + tile_y, image=self.map.tileset.tiles[tile])
            except:
                pass

    def crop(self, *args, **kwargs):
        self.map.crop(*args, **kwargs)
        self.draw()
Ejemplo n.º 7
0
class MarcaFoto(Frame):

    def __init__(self, root):
        Frame.__init__(self, root)
        self.grid(column=0, row=0)
        self.canvas = Canvas(self, width=604, height=480)
        self.canvas.grid(column=0, row=0, columnspan=2)
        self.coords = Label(self)
        self.coords.grid(column=0, row=1)
        nome_arq_foto = 'turma1-640x480.gif'
        self.foto = PhotoImage(file=nome_arq_foto)
        self.canvas.create_image(0, 0, image=self.foto, anchor=NW)
        self.canvas.bind('<Motion>', self.moveu)
        self.canvas.bind('<ButtonPress>', self.marcar)
        self.marca_ativa = None
        
    def moveu(self, evento):
        if self.marca_ativa is not None:
            bbox = self.canvas.coords(self.marca_ativa)
            bbox[2:4] = [evento.x, evento.y]
            self.canvas.coords(self.marca_ativa, *bbox)
        
    def marcar(self, evento):
        if self.marca_ativa is None:
            self.marca_ativa = self.canvas.create_oval(evento.x, evento.y, evento.x, evento.y,
                outline='green', width=5)
        else:
            coords = [int(i) for i in self.canvas.coords(self.marca_ativa)]
            self.coords['text'] = coords
            print coords
            self.marca_ativa = None
Ejemplo n.º 8
0
def main():
    master = Tk()
    w = Canvas(master, width=WIDTH, height=HEIGHT)
    w.pack()

    img = PhotoImage(width=WIDTH, height=HEIGHT, master=master)
    w.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal")

    cam = Camera()
    cam.look_at(np.array([0, 10, -8]),
                np.array([0, 0, 3.0]),
                np.array([0, 1.0, 0]))

    init_world(world_objects)
    init_light(light_objects)
    # Generate rays for each pixel and determine color
    progress_interval = HEIGHT*WIDTH / 10
    progress_tick = 0
    print 'Progress (10 ticks): [ -',
    sys.stdout.flush()
    for y in xrange(HEIGHT):
        for x in xrange(WIDTH):
            progress_tick += 1
            if progress_tick > progress_interval:
                progress_tick = 0
                print ' -',
                sys.stdout.flush()
            ray = compute_camera_ray(WIDTH, HEIGHT, cam, 3, x, y)
            color = trace_ray(world_objects, light_objects, ray)
            # TKinter requires a hex string as color input for photo image
            img.put('#%02X%02X%02X' % tuple(color), (x, y))
    print ' ]'
    mainloop()
Ejemplo n.º 9
0
class MapRenderer:
    def __init__(self, config=config, **kwargs):
        self.config = config
        self.__dict__.update(kwargs)
        self.map = Map(**kwargs)

    @property
    def canvas_width(self):
        return self.map.width * self.map.block_width

    @property
    def canvas_height(self):
        return self.map.height * self.map.block_height

    def init_canvas(self, parent=None):
        if parent == None:
            parent = self.parent
        if hasattr(self, 'canvas'):
            pass
        else:
            self.canvas = Canvas(parent)
        self.canvas.xview_moveto(0)
        self.canvas.yview_moveto(0)

    def kill_canvas(self):
        if hasattr(self, 'canvas'):
            self.canvas.destroy()

    def draw(self):
        self.canvas.configure(width=self.canvas_width, height=self.canvas_height)
        for i in xrange(len(self.map.blockdata)):
            block_x = i % self.map.width
            block_y = i / self.map.width
            self.draw_block(block_x, block_y)

    def draw_block(self, block_x, block_y):
        # the canvas starts at 4, 4 for some reason
        # probably something to do with a border
        index, indey = 4, 4

        # Draw one block (4x4 tiles)
        block = self.map.blockdata[block_y * self.map.width + block_x]

        # Ignore nonexistent blocks.
        if block >= len(self.map.tileset.blocks): return

        for j, tile in enumerate(self.map.tileset.blocks[block]):
            try:
                # Tile gfx are split in half to make vram mapping easier
                if tile >= 0x80:
                    tile -= 0x20
                tile_x = block_x * self.map.block_width + (j % 4) * 8
                tile_y = block_y * self.map.block_height + (j / 4) * 8
                self.canvas.create_image(index + tile_x, indey + tile_y, image=self.map.tileset.tiles[tile])
            except:
                pass

    def crop(self, *args, **kwargs):
        self.map.crop(*args, **kwargs)
        self.draw()
Ejemplo n.º 10
0
class Track:
    """ operates with list of satellites
    
    it can read data about satellites from file, from url, display satellites

    """
    def __init__(self):
        # loading images:
        img = Image.open('map.jpg')
        self.map_img = ImageTk.PhotoImage(img)
        img = Image.open('sat.png').convert("RGBA")
        self.sat_img = ImageTk.PhotoImage(img)
        
        self.anim = Canvas(width = 1024, height = 513)
        self.anim.create_image((0,0), anchor = NW, image = self.map_img)
        
        self.satellites = []    # list of satelites loaded from TLE
        self.draw_sats = []     # indices of desired satellites, and their
                                # canvas ID, for animation
    def load_local(self, file_name):
        fp = open(file_name, 'r')
        line = fp.readline()
        print "load"
        while line > '':
            title = line
            l1 = fp.readline()
            l2 = fp.readline()
            tle_data = TLE(title, l1, l2)
            sat = Satellite(tle_data, datetime.today())
            self.satellites.append(sat)
            line = fp.readline()

    def load_url(self, url, file_name):
        # will be improved later,,, now just downloading txt
        # and writes it to file
        buff = urllib2.urlopen(url)
        fp = open(file_name, 'rw')
        fp.write(buff.read())
    
    def update_satellites(self, dt):
        """ recalculate data about satellites """
        for (index, _id) in self.draw_sats:
            self.satellites[index].update(dt)
#        for sat in self.satellites:
#            sat.update(15)
    
    def add_satellite(self, index):
        # index will be taken from GUI,,,aditional images can be added
        _id = self.anim.create_image(self.satellites[index].map_coords, 
                                     image = self.sat_img)
        self.draw_sats.append((index, _id)) # better use dictionaries
        # testing:
        self.satellites[index].get_coords()
        self.anim.create_line(self.satellites[index].trajectory)
    def draw(self):
        """updates position of the satellites on the canvas"""
        for (index, _id) in self.draw_sats:
            self.anim.coords(_id, self.satellites[index].map_coords)
Ejemplo n.º 11
0
def display_obj(root, obj):
    # label = Label(root,image=obj)
    # label.image = obj
    # label.pack()
    canvas = Canvas(root, width=800, height=500)
    canvas.create_image(100, 100, image=obj)

    canvas.pack()

    root.mainloop()
Ejemplo n.º 12
0
    def initUI(self):
        self.parent.title("High Tatras")
        self.pack(fill=BOTH, expand=1)

        self.img = Image.open("./img/tatras.jpg")
        self.tatras = ImageTk.PhotoImage(self.img)

        canvas = Canvas(self, width=self.img.size[0]+20, height=self.img.size[1]+20)
        canvas.create_image(10, 10, anchor=NW, image=self.tatras)
        canvas.pack(fill=BOTH, expand=1)
Ejemplo n.º 13
0
    def __init__(self):
        self.root = Tk()
        self.root.title("Ray Tracer")
        canvas = Canvas(self.root, width=WIN_SIZE , height=WIN_SIZE )
        self.image = PhotoImage(master=self.root, width=WIN_SIZE, height=WIN_SIZE)
        imageCentre = (WIN_SIZE / 2 + 2, WIN_SIZE / 2 + 2)
        canvas.create_image(imageCentre, image = self.image)
        canvas.pack()

        # Enqueue a callback to the ray tracer to start it going
        self.root.after(0, lambda : self.trace() )
        return
Ejemplo n.º 14
0
    def initUI(self):
        self.parent.title("High Tatras")
        self.pack(fill=BOTH, expand=1)

        self.img = Image.open("./img/tatras.jpg")
        self.tatras = ImageTk.PhotoImage(self.img)

        canvas = Canvas(self,
                        width=self.img.size[0] + 20,
                        height=self.img.size[1] + 20)
        canvas.create_image(10, 10, anchor=NW, image=self.tatras)
        canvas.pack(fill=BOTH, expand=1)
Ejemplo n.º 15
0
def baseline():
    root=Tkinter.Toplevel()
    #root.geometry("730x450")
    root.title("Testing")
    img2 = ImageTk.PhotoImage(Image.open("efg.jpg"))
    w, h = img2.width(), img2.height() 
    canvas = Canvas(root, width=w , height=h)
    canvas.pack(fill = "both")
    canvas.create_image(0, 0, anchor=Tkinter.NW, image=img2)
    canvas.image = img2
    Tkinter.Button(root,text= "BASELINE RECORDING", width= 30, bg= "blue", fg= "white", command= testing).place(x=100, y=50)
    Tkinter.Button(root,text= "START TRAINING", width= 30, bg= "blue", fg= "white", command= EEG).place(x=100, y=100)
    Tkinter.Button(root, text= "GO BACK", width= 30, bg= "blue", fg= "white", command= nothing1).place(x=100, y= 150)
Ejemplo n.º 16
0
    def initUI(self):
      
        self.parent.title("Test Canvas")        
        self.pack(fill=BOTH, expand=1)
        
        self.img = Image.open("../img/blackp.gif")
        self.photo = ImageTk.PhotoImage(self.img)

        #kaleko
        canvas = Canvas(self,width=self.img.size[0]+20,
            height=self.img.size[1]+20)
        canvas.create_image(10, 10, anchor=NW, image=self.photo)
        canvas.pack(fill=BOTH, expand=1)
Ejemplo n.º 17
0
def filter_pic(fname):
    # init image object
    img = IMG(fname)

    # transformations ##################
    img.colorShiftA()
    # img.cosNoise(200,30)
    img.sinePixelShift(5,
                       .5,
                       amp_stagger={
                           'b': 0,
                           'g': 10,
                           'r': 10
                       },
                       freq_stagger={
                           'b': 2,
                           'r': 2,
                           'g': 2
                       })
    img.rotate(180)
    img.sinePixelShift(5,
                       .5,
                       amp_stagger={
                           'b': 20,
                           'g': 10,
                           'r': 0
                       },
                       freq_stagger={
                           'b': 2,
                           'r': 2,
                           'g': 20
                       })
    img.rotate(180)
    # img.filterColor('r')
    #####################################

    # save image
    f = img.save_obj()
    #
    # #Create a canvas
    root = Tk()
    im = Image.open(f)
    canvas = Canvas(root, width=im.width, height=im.height)
    canvas.pack()
    # Put the image into a canvas compatible class, and stick in an
    # arbitrary variable to the garbage collector doesn't destroy it
    canvas.image = ImageTk.PhotoImage(im)
    # Add the image to the canvas, and set the anchor to the top left / north west corner
    canvas.create_image(0, 0, image=canvas.image, anchor='nw')
    raw_input('done')
Ejemplo n.º 18
0
 def __init__(self, update, fps=8):
     self.t = 0
     self.period = 1000/fps        
     self.update = update
     self.master = Tk()
     
     m = self.update(self.t)
     self.W, self.H = m3d.shape(m)
     self.img = PhotoImage(width=self.W, height=self.H)
     
     canvas = Canvas(self.master, width=self.W, height=self.H)
     canvas.pack()
     canvas.create_image((self.W/2, self.H/2), image=self.img, state="normal")
     self._on_tick()
Ejemplo n.º 19
0
def draw(force = False):
    global _DIGITWIDTH, _DIGITHEIGHT, _SEGMENTWIDTH, _DIGITSPACING
    global last_draw_parameters, endTime

    w = c.winfo_width()
    h = c.winfo_height()
    _DIGITWIDTH = w / 4.3
    _DIGITHEIGHT = _DIGITWIDTH * 2
    _SEGMENTWIDTH = _DIGITWIDTH / 6.0
    _DIGITSPACING = _SEGMENTWIDTH
    x = _DIGITSPACING
    y = 0.5 * (h - _DIGITHEIGHT)

    remainingTime = endTime - time.time()
    if pausedAt != None:
        remainingTime = pausedAt
    remainingSeconds = int(math.ceil(remainingTime))

    warn = False
    if remainingSeconds <= warnInterval:
        #if int(remainingTime * 2) % 2 != 0:
        warn = True

    #seconds = max(0, math.ceil(remainingSeconds/10.0)*10)
    seconds = remainingSeconds
    colon = (remainingSeconds % 2 == 0) or (pausedAt != None)
    bgcolor = _BG
    if remainingSeconds <= 0 and remainingSeconds % 2 == 0:
        bgcolor = _BGOUT

    if remainingSeconds == 0:
        from PIL import ImageTk,Image  
        from Tkinter import Canvas, NW, Toplevel, YES, BOTH
        novi = Toplevel()
        canvas = Canvas(novi, width = 650, height = 1000)
        canvas.pack(expand = YES, fill = BOTH)
        img = ImageTk.PhotoImage(Image.open(draw_card()))  
        canvas.create_image(0,0, anchor=NW, image=img)   
        #assigned the gif1 to the canvas object
        canvas.img = img

        #restart new round
        endTime = time.time() + defaultInterval

    draw_parameters = (x, y, seconds, colon, warn, bgcolor)
    if draw_parameters != last_draw_parameters or force:
        c.delete(Tkinter.ALL)
        c.config(bg = bgcolor)
        draw_time(c, x, y, seconds=seconds, drawColon=colon, warn=warn)
        last_draw_parameters = draw_parameters
Ejemplo n.º 20
0
    def initUI(self):

        self.parent.title("Test Canvas")
        self.pack(fill=BOTH, expand=1)

        self.img = Image.open("../img/blackp.gif")
        self.photo = ImageTk.PhotoImage(self.img)

        #kaleko
        canvas = Canvas(self,
                        width=self.img.size[0] + 20,
                        height=self.img.size[1] + 20)
        canvas.create_image(10, 10, anchor=NW, image=self.photo)
        canvas.pack(fill=BOTH, expand=1)
Ejemplo n.º 21
0
    def __init__(self):
        self.root = Tk()
        self.root.title("Ray Tracer")
        canvas = Canvas(self.root, width=WIN_SIZE, height=WIN_SIZE)
        self.image = PhotoImage(master=self.root,
                                width=WIN_SIZE,
                                height=WIN_SIZE)
        imageCentre = (WIN_SIZE / 2 + 2, WIN_SIZE / 2 + 2)
        canvas.create_image(imageCentre, image=self.image)
        canvas.pack()

        # Enqueue a callback to the ray tracer to start it going
        self.root.after(0, lambda: self.trace())
        return
Ejemplo n.º 22
0
    def __init__(self, width, height):
        if type(width) != int:
            raise TypeError("Width must be an integer, recieved: %s"%width)
        if type(height) != int:
            raise TypeError("Height must be an integer, recieved: %s"%height)
        window = Tk()
        canvas = Canvas(window, width=width, height=height, bg="#000000")
        canvas.pack()
        image = PhotoImage(width=width, height=height)
        canvas.create_image((width//2, height//2), image=image, state="normal")

        self.width = width
        self.height = height
        self.canvas = canvas
        self.image = image
Ejemplo n.º 23
0
def main():
    global pd, image, photo, canvas, image_on_canvas, master, args

    logging.info("Loading petri dish...")
    pd = load(args.file)

    # Start the petri dish execution thread
    t = Thread(target=updateModel, args=())
    t.start()

    if (args.nogui == True):

        signal.signal(signal.SIGINT, signalHandler)
        signal.pause()

    else:

        image = petriDishToImage(
            pd,
            config.IMAGE_RESIZE)  # Generate the first image to get the size

        master = Tk()
        canvas = Canvas(master, width=image.width, height=image.height)
        canvas.pack()

        photo = ImageTk.PhotoImage(image)
        image_on_canvas = canvas.create_image(0, 0, image=photo, anchor=tk.NW)

        updateView()

        master.protocol("WM_DELETE_WINDOW", onDeleteWindow)
        master.mainloop()
Ejemplo n.º 24
0
def display():
    window = Tk()
    canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000")
    canvas.pack()
    img = PhotoImage(width=WIDTH, height=HEIGHT)
    canvas.create_image((WIDTH/2, HEIGHT/2), image=img, state="normal")

    data = ""
    for i in range(HEIGHT):
        data += '{' + ' '.join(map(
            convert_color,
            memory_dump(i*WIDTH, i*WIDTH + WIDTH)
        )) + '} '
    img.put(data[:-1])

    mainloop()
Ejemplo n.º 25
0
class FrameTk(object):

    def __init__(self, height, width, box_size, title = "Tk", bg = None):
        self.BOX_SIZE = box_size

        self.main = Tk()
        self.main.wm_title(title)
        self.canvas = Canvas(self.main, height = height, width = width, bg = bg)
        self.canvas.pack()

    def run(self):
        self.main.mainloop()

    def repeat(self, end, timeMillis, callback):
        def _repeat(end, time, func):
            if self.sma.stop:
                return

            if end > 0:
                end -= 1
                self.repeat(end, time, func)
                func()
                self._draw()

        self.canvas.after(timeMillis, _repeat, end, timeMillis, callback)

    def after(self, timeMillis, callback):
        def _callback(time, func):
            if self.sma.stop:
                return

            self.after(time, func)
            func()
            self._draw()

        self.canvas.after(timeMillis, _callback, timeMillis, callback)

    def _draw(self):
        pass

    def drawTkImage(self, x, y, tkimage):
        self.canvas.create_image(x, y, anchor = NW, image = tkimage)

    def drawText(self, x, y, text, color = 'black', size = 8):
        self.canvas.create_text(x, y, anchor = NW, text = text, font = ('Arial', size), width = self.BOX_SIZE, fill = color)
Ejemplo n.º 26
0
class SplashScreen(Toplevel):
    def __init__(self, master, image=None, timeout=1000):
        """(master, image, timeout=1000) -> create a splash screen
        from specified image file.  Keep splashscreen up for timeout
        milliseconds"""
        
        Toplevel.__init__(self, master, relief=FLAT, borderwidth=0)
        if master == None: master = Tk()
        self.main = master
        if self.main.master != None: # Why ?
            self.main.master.withdraw()
        self.main.withdraw()
        self.overrideredirect(1)
        self.image = PhotoImage(file=image)
        self.after_idle(self.centerOnScreen)

        self.update()
        if (timeout != 0): self.after(timeout, self.destroy)

    def centerOnScreen(self):
        self.update_idletasks()
        width, height = self.width, self.height = \
                        self.image.width(), self.image.height()

        xmax = self.winfo_screenwidth()
        ymax = self.winfo_screenheight()

        x0 = self.x0 = xmax/2 - width/2
        y0 = self.y0 = ymax/2 - height/2
        
        self.geometry("%dx%d+%d+%d" % (width, height, x0, y0))
        self.createWidgets()

    def createWidgets(self):
        self.canvas = Canvas(self, width=self.width, height=self.height)
        self.canvas.create_image(0,0, anchor=NW, image=self.image)
        self.canvas.pack()

    def destroy(self):
        # self.main.update()
        # self.main.deiconify()
        self.main.withdraw()
        self.withdraw()
Ejemplo n.º 27
0
def StartUI():
    def close_window():
        # print(entry.get())
        name = entry.get()
        data = {"Name": name}
        pickle.dump
        file = open("Name.txt", 'wb')
        pickle.dump(data, file)
        root.destroy()
        # quit()

    root = Tk()
    # quit()
    entry_pady = 9
    height_text = 5
    photoimage2 = ImageTk.PhotoImage(file='pops.png')
    root.title('Harp')
    canvas = Canvas(root,
                    width=600,
                    height=500,
                    bg="Green",
                    bd="0",
                    highlightthickness=0,
                    relief='ridge')
    canvas.create_image((0, 0), image=photoimage2, anchor="nw")
    canvas.pack()
    root.geometry("+250+250")
    root.overrideredirect(True)
    root.wm_attributes("-transparentcolor", "Green")
    root.lift()
    entry = Entry(canvas, background="white")
    button = Button(canvas,
                    background="white",
                    text="Submit",
                    command=close_window)
    canvas.create_window((125, 40 + height_text + entry_pady + 90),
                         window=entry,
                         anchor="nw")
    canvas.create_window((265, 40 + height_text + entry_pady + 85),
                         window=button,
                         anchor="nw")
    root.mainloop()
Ejemplo n.º 28
0
	def _init_ui(self):
		# Load an image
		self.img = ImageTk.PhotoImage(Image.open(r"images\dna5.png"))
		# Define a canvas in a frame
		frame = Frame(self)
		c = Canvas(frame, bg="white", height=475, width=475)
		# Display the image in the canvas
		c.create_image(0, 0, image=self.img, anchor=NW)
		# Y-scrollbar
		yscrollbar = Scrollbar(frame, command=c.yview)
		c.configure(yscrollcommand=yscrollbar.set)
		# X-scrollbar
		xscrollbar = Scrollbar(frame, orient=HORIZONTAL, command=c.xview)
		c.configure(xscrollcommand=xscrollbar.set)
		# Display widgets using grid layout.
		frame.grid(row=0, column=0)
		yscrollbar.grid(row=0, column=2, sticky=S + N)
		xscrollbar.grid(row=2, column=0, sticky=W + E)
		c.grid(row=0, column=0)
		self.pack(fill=BOTH, expand=1)
Ejemplo n.º 29
0
def display(image_file):

    root = Tk()
    root.title("Dataflow Graph")
    screen_width = root.winfo_screenwidth() * 1.0
    screen_height = root.winfo_screenheight() * 0.875

    image1 = Image.open(image_file)
    width, height = image1.size
    if width > screen_width or height > screen_height:
        factor = max(width / screen_width, height / screen_height)
        image1 = image1.resize((int(width / factor), int(height / factor)),
                               Image.ANTIALIAS)

    frame = Frame(root, width=image1.size[0], height=image1.size[1])
    frame.grid(row=0, column=0)
    canvas = Canvas(frame,
                    bg='#FFFFFF',
                    width=image1.size[0],
                    height=image1.size[1],
                    scrollregion=(0, 0, image1.size[0], image1.size[1]))
    img = ImageTk.PhotoImage(image1)
    canvas.create_image(0, 0, image=img, anchor="nw")

    hbar = Scrollbar(frame, orient=HORIZONTAL)
    hbar.pack(side=BOTTOM, fill=Tkinter.X)
    hbar.config(command=canvas.xview)
    vbar = Scrollbar(frame, orient=VERTICAL)
    vbar.pack(side=RIGHT, fill=Tkinter.Y)
    vbar.config(command=canvas.yview)
    canvas.config(width=image1.size[0], height=image1.size[1])
    canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
    canvas.pack(side=LEFT, expand=True, fill=BOTH)

    frame.pack()
    # added so that the windows pops up (and is not minimized)
    # --> see http://stackoverflow.com/questions/9083687/python-tkinter-gui-always-loads-minimized
    root.attributes('-topmost', 1)
    root.update()
    root.attributes('-topmost', 0)
    mainloop()
Ejemplo n.º 30
0
def debug_show_images(imagelist):
    from Tkinter import Tk, Canvas, LEFT, BOTH, NW
    from PIL import ImageTk
    root = Tk()
    items = []
    for im in imagelist:
        canvas = Canvas(root, height=im.size[1], width=im.size[0])
        canvas.pack(side='left')
        photo = ImageTk.PhotoImage(im)
        items.append(photo)
        item = canvas.create_image(0,0,anchor='nw',image=photo)
    mainloop()
Ejemplo n.º 31
0
class intro(object):
    def __init__(self):

        self.master=Tk()

        self.x = (self.master.winfo_screenwidth()/3) - (self.master.winfo_width())
        self.y = (self.master.winfo_screenheight()/3) - (self.master.winfo_height())
        self.master.geometry("+%d+%d" % (self.x, self.y))
        self.master.overrideredirect(True)
        self.master.resizable(False,False)
        self.logointroimg=Image.open(r'img/Logo-introscreenmin.jpg')
        self.Tkimage3= ImageTk.PhotoImage(self.logointroimg)

        self.canvas = Canvas(self.master, height=378,width=672 )
        self.canvas.create_image(336,186, image=self.Tkimage3)
        self.canvas.pack()


        self.master.after(1250,self.master.destroy)

        self.master.mainloop()
Ejemplo n.º 32
0
class Painter:
	def __init__(self, window):
		self.population = Population()
		self.initWidgets(window)
		
	def initWidgets(self, window):
		self.targetPhoto = ImageTk.PhotoImage(targetImage)
		self.targetCanvas = Canvas(window, width=config.PIC_W, height=config.PIC_W)
		self.targetCanvas.create_image(config.PIC_W/2, config.PIC_H/2, image=self.targetPhoto)
		self.targetCanvas.pack(side='left')
		self.bestCanvas = Canvas(window, width=config.PIC_W, height=config.PIC_H)
		self.bestCanvas.pack(side='left')
		self.currentCanvas = Canvas(window, width=config.PIC_W, height=config.PIC_H)
		self.currentCanvas.pack(side='left')
	
	def update(self):
		if self.population.evolve():
			self.bestImage = ImageTk.PhotoImage(self.population.bestArtist().image)
			self.bestCanvas.create_image(config.PIC_W/2, config.PIC_H/2, image=self.bestImage)
			self.bestCanvas.update_idletasks()
		else:
			self.currentImage = ImageTk.PhotoImage(self.population.artist.image)
			self.currentCanvas.create_image(config.PIC_W/2, config.PIC_H/2, image=self.currentImage)
			self.currentCanvas.update_idletasks()
			self.population.unevolve()

		root.after(0, self.update)
Ejemplo n.º 33
0
class MemoCaras(Frame):

    def __init__(self, root):
        Frame.__init__(self, root)
        self.grid(column=0, row=0)
        self.canvas = Canvas(self, width=604, height=480)
        self.canvas.grid(column=0, row=0, columnspan=2)
        self.bt_prox = Button(self, text='Próximo', command=self.proximo)
        self.bt_prox.grid(column=0, row=1, sticky=W)
        self.nome = Label(self, text='(passe aqui para ver o nome)')
        self.nome.bind('<Enter>', self.mostra_nome)
        self.nome.bind('<Leave>', self.esconde_nome)
        self.nome.grid(column=1, row=1, sticky=EW)
        self.foto = PhotoImage(file=NOME_ARQ_FOTO)
        self.canvas.create_image(0, 0, image=self.foto, anchor=NW)
        self.caras = {}
        for nome, bbox in pessoas:
            marca = self.canvas.create_oval(*bbox, outline='green', width=5,
                                    state=HIDDEN)
            self.caras[nome] = marca
        self.sequencia = []
        self.cara_ativa = None

    def proximo(self):
        if self.cara_ativa is not None:
            marca = self.caras[self.cara_ativa]
            self.canvas.itemconfigure(marca, state=HIDDEN)
        if len(self.sequencia) == 0:
            self.sequencia = self.caras.keys()
            shuffle(self.sequencia)
        self.cara_ativa = self.sequencia.pop()
        marca = self.caras[self.cara_ativa]
        self.canvas.itemconfigure(marca, state=NORMAL)

    def mostra_nome(self, evento):
        self.texto_nome = self.nome['text']
        self.nome['text'] = self.cara_ativa

    def esconde_nome(self, evento):
        self.nome['text'] = self.texto_nome
Ejemplo n.º 34
0
class Painter:
	def __init__(self, window):
		self.population = Population(Settings.populationSize, Settings.polyCount, Settings.vertexCount, targetImage)
		self.targetPhoto = ImageTk.PhotoImage(targetImage)
		self.initWidgets(window)
		
	def initWidgets(self, window):
		self.targetCanvas = Canvas(window, width=SIZE, height=SIZE)
		self.targetCanvas.create_image(SIZE/2, SIZE/2, image=self.targetPhoto)
		self.targetCanvas.pack(side='left')
		self.bestCanvas = Canvas(window, width=SIZE, height=SIZE)
		self.bestCanvas.pack(side='left')
	
	def update(self):
		if self.population.evolve():
			print "Cycles", self.population.cycles
			print "Improvements", self.population.improvements
			image = ImageTools.imageFromDna(self.population.artists[0])
			self.bestImage = ImageTk.PhotoImage(ImageTools.imageFromDna(self.population.artists[0]))
			self.bestCanvas.create_image(SIZE/2, SIZE/2, image=self.bestImage)
			self.bestCanvas.update_idletasks()
		root.after(0, self.update)
Ejemplo n.º 35
0
 def showplot(p=i, q=j):
     """when plot clicked, open a new window with original size"""
     newwin = Toplevel()
     topscrollbar = Scrollbar(newwin)
     topscrollbar.pack(side=RIGHT, fill=Y)
     topcanvas = Canvas(newwin,
                        width=900,
                        height=900,
                        yscrollcommand=topscrollbar.set,
                        scrollregion=(0, 0, 0, 900))
     topcanvas.pack()
     bigplot = topcanvas.create_image(
         451, 451, image=listphotosbig[p + q * 4])
     topscrollbar.config(command=topcanvas.yview)
Ejemplo n.º 36
0
def display(image_file):
    
    root = Tk()
    root.title("Dataflow Graph")
    screen_width=root.winfo_screenwidth()*1.0
    screen_height=root.winfo_screenheight()*0.875
    
    image1 = Image.open(image_file)
    width,height=image1.size
    if width>screen_width or height>screen_height:
        factor=max(width/screen_width,height/screen_height)
        image1=image1.resize((int(width/factor),int(height/factor)), Image.ANTIALIAS)

    
    frame = Frame(root, width=image1.size[0],height=image1.size[1])
    frame.grid(row=0,column=0)
    canvas=Canvas(frame,bg='#FFFFFF',width=image1.size[0],height=image1.size[1],scrollregion=(0,0,image1.size[0],image1.size[1]))
    img = ImageTk.PhotoImage(image1)
    canvas.create_image(0,0,image=img, anchor="nw")

    hbar=Scrollbar(frame,orient=HORIZONTAL)
    hbar.pack(side=BOTTOM,fill=Tkinter.X)
    hbar.config(command=canvas.xview)
    vbar=Scrollbar(frame,orient=VERTICAL)
    vbar.pack(side=RIGHT,fill=Tkinter.Y)
    vbar.config(command=canvas.yview)
    canvas.config(width=image1.size[0],height=image1.size[1])
    canvas.config(xscrollcommand=hbar.set, yscrollcommand=vbar.set)
    canvas.pack(side=LEFT,expand=True,fill=BOTH)

    frame.pack()
    # added so that the windows pops up (and is not minimized) 
    # --> see http://stackoverflow.com/questions/9083687/python-tkinter-gui-always-loads-minimized
    root.attributes('-topmost', 1)
    root.update()
    root.attributes('-topmost', 0)    
    mainloop()
Ejemplo n.º 37
0
    def initUI(self):
      
        self.parent.title("High Tatras")        
        self.pack(fill=BOTH, expand=1)
        
        self.img = Image.open("tatras.jpg")
        self.tatras = ImageTk.PhotoImage(self.img)
        #Tkinter does not support JPG images internally. 
        #As a workaround, we use the Image and ImageTk modules.

        canvas = Canvas(self, width=self.img.size[0]+20, 
           height=self.img.size[1]+20)
        #We create the Canvas widget. 
        #It takes the size of the image into account. 
        #It is 20 px wider and 20 px higher than the actual image size.


        canvas.create_image(10, 10, anchor=NW, image=self.tatras)
        #We use the create_image() method to create an image item on the canvas. 
        #To show the whole image, it is anchored to the north and to the west. 
        #The image parameter provides the photo image to display.


        canvas.pack(fill=BOTH, expand=1)
Ejemplo n.º 38
0
class Painter:
    def __init__(self, window):
        self.population = Population()
        self.initWidgets(window)

    def initWidgets(self, window):
        self.targetPhoto = ImageTk.PhotoImage(targetImage)
        self.targetCanvas = Canvas(window,
                                   width=config.PIC_W,
                                   height=config.PIC_W)
        self.targetCanvas.create_image(config.PIC_W / 2,
                                       config.PIC_H / 2,
                                       image=self.targetPhoto)
        self.targetCanvas.pack(side='left')
        self.bestCanvas = Canvas(window,
                                 width=config.PIC_W,
                                 height=config.PIC_H)
        self.bestCanvas.pack(side='left')
        self.currentCanvas = Canvas(window,
                                    width=config.PIC_W,
                                    height=config.PIC_H)
        self.currentCanvas.pack(side='left')

    def update(self):
        if self.population.evolve():
            self.bestImage = ImageTk.PhotoImage(
                self.population.bestArtist().image)
            self.bestCanvas.create_image(config.PIC_W / 2,
                                         config.PIC_H / 2,
                                         image=self.bestImage)
            self.bestCanvas.update_idletasks()
        else:
            self.currentImage = ImageTk.PhotoImage(
                self.population.artist.image)
            self.currentCanvas.create_image(config.PIC_W / 2,
                                            config.PIC_H / 2,
                                            image=self.currentImage)
            self.currentCanvas.update_idletasks()
            self.population.unevolve()

        root.after(0, self.update)
Ejemplo n.º 39
0
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()

        '''
Ejemplo n.º 40
0
class EPD(object):
    """EPD E-Ink interface

to use:
  from EPD import EPD

  epd = EPD([path='/path/to/epd'], [auto=boolean])

  image = Image.new('1', epd.size, 0)
  # draw on image
  epd.clear()         # clear the panel
  epd.display(image)  # tranfer image data
  epd.update()        # refresh the panel image - not deeed if auto=true
"""
    def __init__(self, *args, **kwargs):
        self._width = 264
        self._height = 176
        self._panel = 'EPD 2.7'
        self._cog = 0
        self._film = 0
        self._auto = False

        self._version = '4'

        if ('auto' in kwargs) and kwargs['auto']:
            self._auto = True

        self.root = Tk()
        self.canvas = Canvas(self.root, width=self._width, height=self._height)
        self.canvas.pack()

    @property
    def size(self):
        return (self._width, self._height)

    @property
    def width(self):
        return self._width

    @property
    def height(self):
        return self._height

    @property
    def panel(self):
        return self._panel

    @property
    def version(self):
        return self._version

    @property
    def cog(self):
        return self._cog

    @property
    def film(self):
        return self._film

    @property
    def auto(self):
        return self._auto

    @auto.setter
    def auto(self, flag):
        if flag:
            self._auto = True
        else:
            self._auto = False

    def display(self, image):

        # attempt grayscale conversion, and then to single bit.
        # better to do this before calling this if the image is to
        # be displayed several times
        if image.mode != "1":
            image = ImageOps.grayscale(image).convert(
                "1", dither=Image.FLOYDSTEINBERG)

        if image.mode != "1":
            raise EPDError('only single bit images are supported')

        if image.size != self.size:
            raise EPDError('image size mismatch')
        image = image.convert('L')
        image = ImageOps.invert(image)
        image = image.convert('1')
        try:
            self.oldimage = self.image
        except Exception:
            self.oldimage = image
        self.image = image

        if self.auto:
            self.update()

    def _invert(self, image):
        image = image.convert('L')
        image = ImageOps.invert(image)
        image = image.convert('1')
        self.timage = ImageTk.BitmapImage(image)
        self.imagesprite = self.canvas.create_image(0,
                                                    0,
                                                    anchor=NW,
                                                    image=self.timage)
        self.root.update()
        time.sleep(0.250)

    def _fill(self, color):
        self.timage = ImageTk.BitmapImage(
            Image.new("1", (self._width, self._height), color))
        self.imagesprite = self.canvas.create_image(0,
                                                    0,
                                                    anchor=NW,
                                                    image=self.timage)
        self.root.update()
        time.sleep(0.250)

    def _paint(self):
        self.timage = ImageTk.BitmapImage(self.image)
        self.imagesprite = self.canvas.create_image(0,
                                                    0,
                                                    anchor=NW,
                                                    image=self.timage)
        self.root.update()

    def update(self):
        self._invert(self.oldimage)
        self._fill(1)
        self._fill(0)
        self._invert(self.image)
        self._paint()

    def partial_update(self):
        self._paint()

    def blink(self):
        self._invert(self.image)
        self._paint()

    def clear(self):
        self._fill(0)
Ejemplo n.º 41
0
class PlayerApp(Frame):
    def __init__(self, root, player):
        Frame.__init__(self, root)
        self.root = root
        self.config(bd=0, bg='black', highlightbackground='black')
        self.pack()
        self._canvas = Canvas(root,
                              width=(WIN_WIDTH),
                              height=WIN_HEIGHT,
                              bd=0,
                              bg='black',
                              highlightbackground='black')
        self._canvas.pack()

        self.player = player

        self._img_mode = 4
        self._img_mode_count = 6

        # Scale the size to with the entire width of our window.
        # TODO(igorc): Avoid scaling? Or auto-rescale when window resizes.
        frame1_size = self.player.get_frame_size()
        img1_aspect = frame1_size[0] / 2 / frame1_size[1]
        img1_width = int(WIN_WIDTH * 0.95)
        self._img1_size = (img1_width, int(img1_width / img1_aspect))

        if self.player.is_fin_enabled() or self.player.is_kinect_enabled():
            text_y = 0.07
            img1_y = 0.28
            img2_y = 0.56
        else:
            text_y = 0.04
            img1_y = 0.23
            img2_y = 0.54

        # Undo gamma correction in LED preview, otherwise it is too dark.
        # Keep a fixed value to have better feedback on LED gamma changes.
        left_x = int(WIN_WIDTH * 0.025)
        self._img1 = ImageTk.PhotoImage('RGBA', self._img1_size, gamma=2.2)
        self._img2 = ImageTk.PhotoImage('RGBA', self._img1_size)
        self._canvas.create_image(left_x,
                                  int(WIN_HEIGHT * img1_y),
                                  anchor='nw',
                                  image=self._img1)
        self._canvas.create_image(left_x,
                                  int(WIN_HEIGHT * img2_y),
                                  anchor='nw',
                                  image=self._img2)

        if self.player.is_fin_enabled():
            img3_width = int(WIN_WIDTH * 0.15)
            # The fin dimensions are 150x240 inches.
            self._img3_size = (img3_width, int(img3_width * 1.1))
            self._img3 = ImageTk.PhotoImage('RGBA', self._img3_size, gamma=2.2)
            left_scale = 0.60 if self.player.is_kinect_enabled() else 0.65
            self._canvas.create_image(int(WIN_WIDTH * left_scale),
                                      int(WIN_HEIGHT * 0.05),
                                      anchor='nw',
                                      image=self._img3)

        if self.player.is_kinect_enabled():
            img4_width = int(WIN_WIDTH * 0.15)
            self._img4_size = (img4_width, int(img4_width * 0.7))
            self._img4 = ImageTk.PhotoImage('RGB', self._img4_size, gamma=2.2)
            self._canvas.create_image(int(WIN_WIDTH * 0.8),
                                      int(WIN_HEIGHT * 0.08),
                                      anchor='nw',
                                      image=self._img4)

        self._main_label = self._canvas.create_text(
            (left_x, WIN_HEIGHT * text_y),
            fill='#fff',
            anchor='nw',
            justify='left',
            font=("Sans Serif", 16))
        self._canvas.itemconfig(self._main_label, text="this is the text")

        self.root.bind('q', lambda e: player.volume_up())
        self.root.bind('a', lambda e: player.volume_down())
        self.root.bind('m', lambda e: self.switch_mask())
        self.root.bind('g', lambda e: player.gamma_up())
        self.root.bind('b', lambda e: player.gamma_down())
        self.root.bind('h', lambda e: player.visualization_volume_up())
        self.root.bind('n', lambda e: player.visualization_volume_down())
        self.root.bind('v', lambda e: player.toggle_visualization())
        self.root.bind('t', lambda e: self.toggle_visualizer_render())
        self.root.bind('d', lambda e: player.toggle_hdr_mode())
        self.root.bind('o', lambda e: player.select_next_preset(False))
        self.root.bind('p', lambda e: player.select_next_preset(True))
        self.root.bind('l', lambda e: player.lock_screen())
        self.root.bind('0', lambda e: player.stop_effect())
        self.root.bind('1', lambda e: player.play_effect('slowblink'))
        self.root.bind('2', lambda e: player.play_effect('radiaterainbow'))
        self.root.bind('3', lambda e: player.play_effect('threesine'))
        self.root.bind('4', lambda e: player.play_effect('plasma'))
        self.root.bind('5', lambda e: player.play_effect('rider'))
        self.root.bind('6', lambda e: player.play_effect('flame'))
        self.root.bind('7', lambda e: player.play_effect('glitter'))
        self.root.bind('8', lambda e: player.play_effect('slantbars'))
        self.root.bind('9', lambda e: player.play_effect('textticker'))
        self.root.bind('!', lambda e: player.play_effect('solidcolor'))
        self.root.bind('@', lambda e: player.play_effect('randompixels'))
        self.root.bind('#', lambda e: player.play_effect('teststripes'))
        self.root.bind('$', lambda e: player.play_effect('blink'))
        self.root.bind('%', lambda e: player.play_effect('chameleon'))
        self.root.bind('^', lambda e: player.play_effect('indicator'))
        self.root.bind('&', lambda e: player.play_effect('flick'))
        self.root.bind('*', lambda e: player.play_effect('textstay'))
        self.root.bind('<space>', lambda e: player.toggle())
        self.root.bind('<Up>', lambda e: player.prev())
        self.root.bind('<Down>', lambda e: player.next())
        self.root.bind('<Left>', lambda e: player.skip_backward())
        self.root.bind('<Right>', lambda e: player.skip_forward())
        self.root.protocol('WM_DELETE_WINDOW', lambda: self.quit())
        self.root.after(1000 / FPS / 4, lambda: self.update())
        self.running = True

    def run_effect(self, effect):
        self.player.effect = effect

    def switch_mask(self):
        self._img_mode += 1
        self._img_mode = self._img_mode % self._img_mode_count

    def toggle_visualizer_render(self):
        if (self._img_mode % 3) == 0:
            self._img_mode += 1
        elif (self._img_mode % 3) == 2:
            self._img_mode += 2
        else:
            self._img_mode += 2
        self._img_mode = self._img_mode % self._img_mode_count

    def quit(self):
        self.running = False

    def _paste_images(self, images, mode):
        # Always use LED image as the first image.
        frame1 = images[2].copy() if images[2] else None
        frame3 = images[3].copy() if images[3] else None
        frame4 = images[4].copy() if images[4] else None

        crop_rect = None
        frame_size = self.player.get_frame_size()
        if mode < 3:
            crop_rect = (0, 0, frame_size[0] / 2, frame_size[1])
        else:
            crop_rect = (frame_size[0] / 2, 0, frame_size[0], frame_size[1])
        if frame1:
            frame1 = frame1.crop(crop_rect)

        if (mode % 3) == 0:
            # Second is intermediate image by default.
            frame2 = images[1].copy() if images[1] else None
            if frame2:
                frame2 = frame2.crop(crop_rect)
        elif (mode % 3) == 1:
            # Otherwise show original image.
            frame2 = images[0].copy() if images[0] else None
            if frame2 and mode >= 3:
                frame2 = frame2.transpose(Image.FLIP_LEFT_RIGHT)
        else:
            # Show black if disabled.
            frame2 = Image.new('RGBA', self._img1_size, (0, 0, 0, 0))

        if frame1:
            self._img1.paste(frame1.resize(self._img1_size))
        if frame2:
            self._img2.paste(frame2.resize(self._img1_size))
        if frame3:
            # Dorsal fin
            self._img3.paste(frame3.resize(self._img3_size))
        if frame4:
            # Kinect
            self._img4.paste(frame4.resize(self._img4_size))

    def update(self):
        try:
            mode = self._img_mode
            if (mode % 3) == 1 and self.player.is_playing_effect():
                mode -= 1
            need_original = (mode % 3) == 1
            need_intermediate = (mode % 3) == 0
            images = self.player.get_frame_images(need_original,
                                                  need_intermediate)
            if images:
                self._paste_images(images, mode)
            status_lines = self.player.get_status_lines()
            self._canvas.itemconfig(self._main_label,
                                    text='\n'.join(status_lines))
            # TODO(igorc): Reschedule after errors.
            self.root.after(1000 / FPS / 4, lambda: self.update())
        except KeyboardInterrupt:
            self.quit()
Ejemplo n.º 42
0
class World(Tk):
    #    def __init__(self,filename=None,block=50,debug=True,delay=0.25,image=False,width=10,height=10):
    def __init__(self,
                 filename=None,
                 block=50,
                 debug=True,
                 delay=0.25,
                 image=True,
                 width=10,
                 height=10):
        Tk.__init__(self)
        self.title("")
        arg, self.width, self.height = block, width, height
        self.photos = [
            PhotoImage(file=(k + ".gif"))
            for k in ["east", "north", "west", "south"]
        ]
        self.beepers, self.ovals, self.numbers, self.robots, self.walls = {},{},{},{},{}
        self.m, self.n, self.t, self.delay = arg * (width + 3), arg * (
            height + 3), arg, delay
        self.debug, self.useImage = debug, image
        a, b, c = self.t + self.t / 2, self.m - self.t - self.t / 2, self.n - self.t - self.t / 2
        self.canvas = Canvas(self, bg="white", width=self.m, height=self.n)
        self.canvas.pack()
        count = 1
        for k in range(2 * self.t, max(self.m, self.n) - self.t, self.t):
            if k < b:
                self.canvas.create_line(k, c, k, a, fill="red")
                self.canvas.create_text(k,
                                        c + self.t / 2,
                                        text=str(count),
                                        font=("Times",
                                              max(-self.t * 2 / 3, -15), ""))
            if k < c:
                self.canvas.create_line(b, k, a, k, fill="red")
                self.canvas.create_text(a - self.t / 2,
                                        self.n - k,
                                        text=str(count),
                                        font=("Times",
                                              max(-self.t * 2 / 3, -15), ""))
            count += 1
        self.canvas.create_line(a, c, b, c, fill="black", width=3)
        self.canvas.create_line(a, a, a, c, fill="black", width=3)
        if filename is not None:
            self.readWorld(filename)
        self.refresh()

    def readWorld(self, filename):
        try:
            infile = open("worlds\\%s.wld" % filename, "r")
        except IOError:
            try:
                infile = open("worlds/%s.wld" % filename, "r")
            except IOError:
                infile = open(filename, "r")
        text = infile.read().split("\n")
        infile.close()
        for t in text:
            if t.startswith("eastwestwalls"):
                s = t.split(" ")
                y, x = int(s[1]), int(s[2])
                self.addWall(x, y, -1, y)
            if t.startswith("northsouthwalls"):
                s = t.split(" ")
                x, y = int(s[1]), int(s[2])
                self.addWall(x, y, x, -1)
            if t.startswith("beepers"):
                s = t.split(" ")
                y, x, n = int(s[1]), int(s[2]), int(s[3])
                if n is infinity:
                    self.addInfiniteBeepers(x, y)
                else:
                    for k in range(n):
                        self.addBeeper(x, y)

    def pause(self):
        sleep(self.delay)

    def isBeeper(self, x, y):
        return (x, y) in self.beepers.keys() and not self.beepers[(x, y)] == 0

    def countRobots(self, x, y):
        if (x, y) not in self.robots.keys():
            return 0
        return len(self.robots[(x, y)])

    def crash(self, x1, y1, x2, y2):
        if 0 in (x1, y1, x2, y2):
            return True
        if (x2, y2) in self.walls.keys() and (x1, y1) in self.walls[(x2, y2)]:
            return True
        if (x1, y1) in self.walls.keys() and (x2, y2) in self.walls[(x1, y1)]:
            return True
        return False

    def addInfiniteBeepers(self, x, y):
        flag = (x, y) not in self.beepers.keys() or self.beepers[(x, y)] is 0
        self.beepers[(x, y)] = infinity
        text = "oo"
        a, b = self.t + x * self.t, self.n - (self.t + y * self.t)
        t = self.t / 3
        if flag:
            self.ovals[(x, y)] = self.canvas.create_oval(a - t,
                                                         b - t,
                                                         a + t,
                                                         b + t,
                                                         fill="black")
            self.numbers[(x, y)] = self.canvas.create_text(
                a,
                b,
                text=text,
                fill="white",
                font=("Times", max(-self.t / 2, -20), ""))
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in self.robots.keys():
            for robot in self.robots[(x, y)]:
                robot.lift()

    def addBeeper(self, x, y):
        if (x, y) in self.beepers.keys() and self.beepers[(x, y)] is infinity:
            return
        flag = (x, y) not in self.beepers.keys() or self.beepers[(x, y)] is 0
        if flag:
            self.beepers[(x, y)] = 1
        else:
            self.beepers[(x, y)] += 1
        text = str(self.beepers[(x, y)])
        a, b = self.t + x * self.t, self.n - (self.t + y * self.t)
        t = self.t / 3
        if flag:
            self.ovals[(x, y)] = self.canvas.create_oval(a - t,
                                                         b - t,
                                                         a + t,
                                                         b + t,
                                                         fill="black")
            self.numbers[(x, y)] = self.canvas.create_text(
                a,
                b,
                text=text,
                fill="white",
                font=("Times", max(-self.t / 2, -20), ""))
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in self.robots.keys():
            for robot in self.robots[(x, y)]:
                robot.lift()

    def removeBeeper(self, x, y):
        if self.beepers[(x, y)] is infinity:
            return
        self.beepers[(x, y)] -= 1
        flag = self.beepers[(x, y)] is 0
        text = str(self.beepers[(x, y)])
        if flag:
            self.canvas.delete(self.ovals[(x, y)])
            self.canvas.delete(self.numbers[(x, y)])
        else:
            self.canvas.itemconfig(self.numbers[(x, y)], text=text)
        if (x, y) in self.robots.keys():
            for robot in self.robots[(x, y)]:
                robot.lift()

    def addWall(self, x1, y1, x2, y2):
        if not x1 == x2 and not y1 == y2:
            return
        if x1 == x2:
            y1, y2 = min(y1, y2), max(y1, y2)
            if y1 == -1:
                y1 = y2
            for k in range(y1, y2 + 1):
                self.walls.setdefault((x1, k), []).append((x1 + 1, k))
                a, b = self.t + x1 * self.t + self.t / 2, self.n - (
                    self.t + k * self.t) + self.t / 2
                c, d = self.t + x1 * self.t + self.t / 2, self.n - (
                    self.t + k * self.t) - self.t / 2
                self.canvas.create_line(a,
                                        b + 1,
                                        c,
                                        d - 1,
                                        fill="black",
                                        width=3)
        else:
            x1, x2 = min(x1, x2), max(x1, x2)
            if x1 == -1:
                x1 = x2
            for k in range(x1, x2 + 1):
                self.walls.setdefault((k, y1), []).append((k, y1 + 1))
                a, b = self.t + k * self.t - self.t / 2, self.n - (
                    self.t + y1 * self.t) - self.t / 2
                c, d = self.t + k * self.t + self.t / 2, self.n - (
                    self.t + y1 * self.t) - self.t / 2
                self.canvas.create_line(a - 1,
                                        b,
                                        c + 1,
                                        d,
                                        fill="black",
                                        width=3)

    def draw(self, x, y, d, img):
        if self.useImage:
            if img is not None:
                self.canvas.delete(img)
            x, y = self.t + x * self.t, self.n - (self.t + y * self.t)
            photo = self.photos[d / 90]
            img = self.canvas.create_image(x, y, image=photo)
            return img
        else:
            t, angle = self.t / 2, 120
            x, y = self.t + x * self.t, self.n - (self.t + y * self.t)
            x1, y1 = x + 3**0.5 * t / 2 * cos(
                radians(d)), y - 3**0.5 * t / 2 * sin(radians(d))
            x2, y2 = x + t * cos(radians(d + angle)), y - t * sin(
                radians(d + angle))
            x3, y3 = x + t / 4 * cos(radians(d + 180)), y - t / 4 * sin(
                radians(d + 180))
            x4, y4 = x + t * cos(radians(d - angle)), y - t * sin(
                radians(d - angle))
            if img is not None:
                self.canvas.delete(img)
            img = self.canvas.create_polygon(x1,
                                             y1,
                                             x2,
                                             y2,
                                             x3,
                                             y3,
                                             x4,
                                             y4,
                                             fill="blue")
            return img

    def erase(self, img):
        self.canvas.delete(img)

    def recordMove(self, count, x1, y1, x2, y2):
        for robot in self.robots[(x1, y1)]:
            if robot.count == count:
                self.robots[(x1, y1)].remove(robot)
                self.robots.setdefault((x2, y2), []).append(robot)
                break

    def lift(self, img):
        self.canvas.lift(img)

    def refresh(self):
        self.canvas.update()
        self.pause()

    def register(self, x, y, robot):
        self.robots.setdefault((x, y), []).append(robot)

    def remove(self, x, y, robot):
        self.robots[(x, y)].remove(robot)
else:
    cciX = 243
    cciY = 113
    photo = PhotoImage(file="atomic.gif")

root.update() #update our root with new dimensions

lines = [] # for appending to lineNumber
lineNumber = []  # keeps track of line item numbers to delete later
toSum = [] # (oldpoint.x, oldpoint.y), (newpoint.x, newpoint.y), dist(previous tuples listed))

frame = Frame(root, width = fcW, height = fcH) #create a frame in root
frame.pack() #put it in the window

canvas = Canvas(frame, width = fcW, height = fcH) #create a canvas
canvas.create_image(cciX, cciY, image = photo) #put a image in the canvas
canvas.pack() #put it in the frame

result = Entry(root, font = ("Times", 14)) #create a results box
result.pack() #put it in the window

def dist(oldCoord, newCoord):
    return math.sqrt(math.pow((newCoord[0]-oldCoord[0]), 2)+math.pow((newCoord[1]-oldCoord[1]), 2))

def getReturn(toSum):
    length = 0
    for i in range(len(toSum)):
        length += toSum[i][2]
    return length

def callback(event, reset): #note, when sending to database, add 400 to x and 300 to y
Ejemplo n.º 44
0
import Tkinter
import Image
from Tkinter import Tk, BOTH
from ttk import Frame, Button, Style
import cv2
import os
import time
import itertools
from Tkinter import Tk, Frame, BOTH, Button, RIGHT, RAISED
from Tkinter import BooleanVar, Checkbutton, PhotoImage, Canvas
from Tkinter import Scale, StringVar, END, Listbox, Label, Menu
from PIL import Image
import ttk
import thread
import pylab

root = Tk()
cwgt = Canvas(root)
cwgt.pack(expand=True, fill=BOTH)
image1 = PhotoImage(file="1.png")
# keep a link to the image to stop the image being garbage collected
cwgt.img = image1
cwgt.create_image(0, 0, image=image1)
b1 = Button(cwgt, text="Hello", bd=0)
cwgt.create_window(20, 20, window=b1)
root.mainloop()
Ejemplo n.º 45
0
#slider for max transverse mass
slider_maxLepTMass = Scale(OptionsLep,
                           from_=0,
                           to=200,
                           orient=HORIZONTAL,
                           length=170,
                           width=10,
                           variable=LepTmassMax_val,
                           bg="lavender",
                           label="Maximum transverse mass")

emptyf2 = Frame(OptionsLep, width="170")  #just to mantain OptionsLep width

#Question mark to be next to "invariant mass" option
qinvmass = Canvas(OptionsLep, width=16, height=16)
qinvmass.create_image(8, 8, image=questionmark)

infoinvmass = Message(OptionsLep,
                      text="The invariant mass of the charged leptons",
                      bg="White",
                      aspect=300)  #Information message


def on_enterinvmass(event):
    """shows an explanation if cursor placed over question mark"""
    infoinvmass.grid(row=0, rowspan=8)


def on_leaveinvmass(event):
    """hides explanation if cursor not placed on question mark"""
    infoinvmass.grid_forget()
Ejemplo n.º 46
0
class TopLevelView(BaseView):
    TEXT_LABEL_OFFSET = 35
    ROD_BOX_START_X = 50
    ROD_BOX_START_Y = 45
    ROD_BOX_WIDTH = 70
    ROD_BOX_HEIGHT = 25
    ROD_BOX_VERTICAL_OFFSET = 10

    # other values are the same like for the ROD boxes
    ROS_BOX_START_X = 150
    ROS_BOX_START_Y = 45

    def __init__(self, tkRoot, systems, app, logger):
        BaseView.__init__(self, tkRoot, app, logger)

        self.systems = systems  # names of all subsystems

        # Canvas options width, height seem not necessary ...
        self.canvas = Canvas(self.tkRoot, bg=BaseView.CANVAS_BG_COLOR)
        self.canvas.pack(expand=YES, fill=BOTH)

        self.__createRodBoxes()
        self.__createRosBoxes()
        self.__createRodRosLines()

        self.name = "TOP"  # name of this special view
        self.app.addActiveView(self.name, self)  # special top view

        # add logo
        logo = PhotoImage(file="doc/logo.gif")
        self.canvas.create_image(conf.GUI_WIDTH - 20,
                                 conf.GUI_HEIGHT - 20,
                                 image=logo)
        self.canvas.image = logo  # keep a reference, otherwise it won't appear

    def __openRosDetailedView(self, comp):
        try:
            rosTree = self.app.rosTrees[comp.name]
            # every view (except for TopLevelView) has a tree node
            # acting as root for such particular view
            treeRootNode = rosTree.root
            v = View(self.tkRoot, self.app, comp, treeRootNode, self.logger)
            v.createContent()
            self.logger.debug("View created for '%s'" % comp)
        except KeyError:
            m = "ROS data n/a for '%s'" % comp
            self.logger.warn(m)
            tkMessageBox.showwarning("Quit", m, parent=self.tkRoot)

    def openDetailedView(self, comp):
        if comp.group == "ROS":
            # check if view which is to be open has not been opened already
            if self.app.isViewActive(comp.name):
                m = ("View '%s' is already among active windows, "
                     "not created." % comp.name)
                self.logger.warn(m)
                tkMessageBox.showwarning("Quit", m, parent=self.tkRoot)
            else:
                self.__openRosDetailedView(comp)
        else:
            m = "No view available for '%s' " % comp
            self.logger.warn(m)
            tkMessageBox.showwarning("Quit", m, parent=self.tkRoot)

    def __createRodBoxes(self):
        state = NotAssociated()
        group = "ROD"  # title
        self.canvas.create_text(
            TopLevelView.ROD_BOX_START_X + TopLevelView.TEXT_LABEL_OFFSET,
            TopLevelView.ROD_BOX_START_Y - TopLevelView.ROD_BOX_HEIGHT,
            text=group,
            font=self.bigFont)

        for i in range(len(self.systems)):
            x0 = TopLevelView.ROD_BOX_START_X
            y0 = (TopLevelView.ROD_BOX_START_Y +
                  (i * (TopLevelView.ROD_BOX_HEIGHT +
                        TopLevelView.ROD_BOX_VERTICAL_OFFSET)))
            x1 = x0 + TopLevelView.ROD_BOX_WIDTH
            y1 = y0 + TopLevelView.ROD_BOX_HEIGHT

            box = Box(group, self.systems[i], self.canvas)
            box.create(x0, y0, x1, y1, state.color)
            box.text(x0 + TopLevelView.TEXT_LABEL_OFFSET,
                     y0 + TopLevelView.ROD_BOX_HEIGHT / 2, self.systems[i],
                     self.boxTitleFont)
            self.compStore.append(box)

    def __createRosBoxes(self):
        state = Inactive()
        group = "ROS"  # title
        self.canvas.create_text(
            TopLevelView.ROS_BOX_START_X + TopLevelView.TEXT_LABEL_OFFSET,
            TopLevelView.ROS_BOX_START_Y - TopLevelView.ROD_BOX_HEIGHT,
            text=group,
            font=self.bigFont)

        for i in range(len(self.systems)):
            # need to get a tree node controlling the created component
            try:
                rosTree = self.app.rosTrees[self.systems[i]]
                node = rosTree.root
                box = RenderableBox(group, self.canvas, node)
            except KeyError:
                # some defined system don't have data (node) to be controlled by
                box = Box(group, self.systems[i], self.canvas)

            x0 = TopLevelView.ROS_BOX_START_X
            y0 = (TopLevelView.ROS_BOX_START_Y +
                  (i * (TopLevelView.ROD_BOX_HEIGHT +
                        TopLevelView.ROD_BOX_VERTICAL_OFFSET)))
            x1 = x0 + TopLevelView.ROD_BOX_WIDTH
            y1 = y0 + TopLevelView.ROD_BOX_HEIGHT

            idBox = box.create(x0, y0, x1, y1, state.color)
            idText = box.text(x0 + TopLevelView.TEXT_LABEL_OFFSET,
                              y0 + TopLevelView.ROD_BOX_HEIGHT / 2,
                              self.systems[i], self.boxTitleFont)
            dch = DoubleClickHandler(box, self)
            # bind both IDs - box and text in the box
            self.canvas.tag_bind(idBox, "<Double-1>", dch)
            self.canvas.tag_bind(idText, "<Double-1>", dch)

            self.compStore.append(box)

    def __createRodRosLines(self):
        group = "RODROSLINE"
        for i in range(len(self.systems)):
            x0 = TopLevelView.ROD_BOX_START_X + TopLevelView.ROD_BOX_WIDTH
            y0 = (TopLevelView.ROS_BOX_START_Y +
                  (i * (TopLevelView.ROD_BOX_HEIGHT +
                        TopLevelView.ROD_BOX_VERTICAL_OFFSET)) +
                  TopLevelView.ROD_BOX_HEIGHT / 2)
            x1 = TopLevelView.ROS_BOX_START_X
            y1 = y0

            line = Line(group, self.systems[i], self.canvas)
            line.create(x0, y0, x1, y1)
            self.compStore.append(line)
from Tkinter import Tk, Canvas, PhotoImage, mainloop
from math import sin
from time import sleep
from sys import argv

WIDTH, HEIGHT = 640, 480

CORNA = int(argv[1])
CORNB = int(argv[2])
SIDE = float(argv[3])

window = Tk()
canvas = Canvas(window, width=WIDTH, height=HEIGHT, bg="#000000")
canvas.pack()
img = PhotoImage(width=WIDTH, height=HEIGHT)
canvas.create_image((WIDTH / 2, HEIGHT / 2), image=img, state="normal")

for i in range(WIDTH):
    for j in range(HEIGHT):
        x = CORNA + (SIDE * (i / 100.0))
        y = CORNB + (SIDE * (j / 100.0))
        z = x * x + y * y
        c = int(z)
        if c % 2 == 0:
            img.put("#ffffff", (i, j))

mainloop()
Ejemplo n.º 48
0
class liuyao:
	def __init__(self,root,gua64):
		self.cntoint={u'少阳-----':'1',u'少阴-- --':'2',u'老阳--O--':'3',u'老阴--X--':'4'}
		self.tfont=tkFont.Font(family='Fixdsys',size=25,weight=tkFont.BOLD)
		self.gfont=tkFont.Font(family='Fixdsys',size=13,weight=tkFont.BOLD)
		self.dgua=[] #动爻
		self.ygua=[] #原始卦
		self.bbgua=[] #变卦
		self.yguastr=[] #原始卦
		self.gua=[] #只有12的卦
		self.pabout=True #右键显示消失淮南标题
		self.guax=200
		self.guay=100
		self.liushen={'甲':0,'乙':0,'丙':1,'丁':1,'戊':2,'己':3,'庚':4,'辛':4,'壬':5,'癸':5}
		self.liushencn=['青龙','朱雀','勾陈','腾蛇','白虎','玄武']
		self.tiangan={'甲':1,'乙':2,'丙':3,'丁':4,'戊':5,'己':6,'庚':7,'辛':8,'壬':9,'癸':10}
		self.dizhi={'子':1,'丑':2,'寅':3,'卯':4,'辰':5,'巳':6,'午':7,'未':8,'申':9,'酉':10,'戌':11,'亥':12}
		self.kongwangzu=['子','丑','寅','卯','辰','巳','午','未','申','酉','戌','亥']
		self.root=root
		self.root.title(u'===六爻排盘===[淮南内部专用]')
		self.root.minsize(550,380)
		self.root.maxsize(550,380)
		self.canvas=Canvas(root,width=460,height=380,bg='gray')
		self.picyang=PhotoImage(file='tk\\yang.gif')
		self.picyin=PhotoImage(file='tk\\yin.gif')
		self.canvas.place(relx=0,rely=0)
		self.com={}
		for i in xrange(6):
			self.com[i]=Combobox(root,state='readonly')
			self.com[i]['values']=(u'少阳-----',u'少阴-- --',u'老阳--O--',u'老阴--X--')
			self.com[i].current(0)
			self.com[i].place(relx=0.85,rely=0.36-0.07*i,width=80)
		bt1=Button(root,text=u'排盘',command=self.paipan)
		# bt1.place(relx=0.85,rely=0.35+0.7)
		bt1.pack(side='right')
		self.date() #干支
		#===========================
		self.root.bind('<Button-3>',self.about)

	def liushenf(self):  #配六神
		xu=self.liushen[self.ritian.encode('utf-8')]
		for i in xrange(6):
			self.canvas.create_text(self.guax-170,100+150-30*i,font=self.gfont,text=self.liushencn[xu],tag='liushen')
			xu+=1
			if xu>5:
				xu-=6

	def date(self):
		turl=urllib2.urlopen('http://www.nongli.com/item4/index.asp',timeout=10).read()
		soup=BeautifulSoup(turl)
		zu=soup.findAll('td',{'width':'74%','bgcolor':'#FFFFFF'})[1].text
		# print zu
		wanzu=[] #wanzu里面是完成的年月日干支
		wanzu.append(zu.split(' ')[0])
		wanzu.append(zu.split(' ')[2])
		wanzu.append(zu.split(' ')[3])
		for i in xrange(3):
			# print u'干支',wanzu[i]
			self.canvas.create_text(self.guax-90+60*i,30,text=wanzu[i],font=self.gfont,tag='riqi')
		ri=wanzu[2]
		self.ritian=list(ri)[0]
		self.ridi=list(ri)[1]
		self.kongwang()

	def kongwang(self):
		# print u'日干支:',self.ridi,self.ritian
		cha=self.dizhi[self.ridi.encode('utf-8')]-self.tiangan[self.ritian.encode('utf-8')]
		if cha<0:
			cha+=+10
		self.canvas.create_text(self.guax-90+120+30,30,font=self.gfont,text='(',tag='riqi')
		self.canvas.create_text(self.guax-90+120+30+15,30,font=self.gfont,text=self.kongwangzu[cha-2],tag='riqi')
		self.canvas.create_text(self.guax-90+120+30+30,30,font=self.gfont,text=self.kongwangzu[cha-1],tag='riqi')
		self.canvas.create_text(self.guax-90+120+30+45,30,font=self.gfont,text=')',tag='riqi')

	def about(self,event):
		if self.pabout:
			self.canvas.create_text(self.guax,100+250,text='淮南法教专用水印',fill='tan',font=self.tfont,tag='about')
			self.canvas.create_text(self.guax+140,370,text='--无名',fill='tan',tag='about')
			self.pabout=False
		else:
			self.canvas.delete('about')
			self.pabout=True


	def paipan(self):
		for i in xrange(6):
			self.ygua.append(self.cntoint[self.com[i].get()]) #得到原始爻名,转换为1234,添加入gua
		self.gua=self.ygua
		bbgua=self.gua
		print '======================='
		print 'sel.gua',self.gua
		for i in xrange(6):
			if self.ygua[i]=='3':
				self.gua[i]='1'
				self.dgua.append(str(i))
				self.dgua.append('1') 
			elif  self.ygua[i]=='4':
				self.gua[i]='2'
				self.dgua.append(str(i))
				self.dgua.append('2')
		self.guastr=''.join(self.gua)
		# print u'变卦',bbgua
		# print u'字符串卦数',self.guastr
		# print u'数列卦',self.gua
		# print u'动卦',self.dgua
		# print gua64[guastr]
		self.draw()
		self.liushenf()#六神


	def draw(self):
		self.canvas.delete('pic')   #删除所有上次产生的ITEMS
		self.canvas.delete('liushen')
		# print u'当前itme数',self.canvas.find_all()
		#本卦
		for i in xrange(6):
			if self.gua[i]=='1':
				self.canvas.create_image(self.guax,100+150-30*i,image=self.picyang,tag='pic')
			else:
				self.canvas.create_image(self.guax,100+150-30*i,image=self.picyin,tag='pic')	
		
				#下面是六亲
		for i in xrange(6):
			self.canvas.create_text(self.guax-70,100+30*i,font=self.gfont,text=gua64[self.guastr][i],tag='pic')

			#动爻标记
		for i in xrange(0,len(self.dgua),2):
			if self.dgua[i+1]=='1':
				self.canvas.create_text(self.guax+70,250-30*int(self.dgua[i]),font=self.gfont,text='O',tag='pic')
			else:
				self.canvas.create_text(self.guax+70,250-30*int(self.dgua[i]),font=self.gfont,text='X',tag='pic')
			#世
		syw=gua64[self.guastr][6]
		self.canvas.create_text(self.guax+55,280-30*syw,font=self.gfont,text='世',tag='pic')
			#应
		yyw=gua64[self.guastr][7]
		self.canvas.create_text(self.guax+55,280-30*yyw,font=self.gfont,text='应',tag='pic')
			#六合、冲
		hc=gua64[self.guastr][8]
		self.canvas.create_text(self.guax-70,100-30,font=self.gfont,text=hc,tag='pic')
			#游魂、归魂
		zg=gua64[self.guastr][9]
		self.canvas.create_text(self.guax-70,100-30,font=self.gfont,text=zg,tag='pic')
			#卦宫
		gg=gua64[self.guastr][10]
		self.canvas.create_text(self.guax,100-30,font=self.gfont,text=gg,tag='pic')
		#变卦	
		self.biangua()
		self.guastr=''
		self.dgua=[] #动爻
		self.ygua=[] #原始卦
		self.bbgua=[] #变卦
		self.yguastr=[] #原始卦
		self.gua=[] #只有12的卦

	def biangua(self):
		self.bbgua=self.gua
		# print 'biangua',self.bbgua
		'''
sel.gua ['4', '4', '3', '3', '4', '3']
字符串卦数 221121
数列卦 ['2', '2', '1', '1', '2', '1']
动卦 ['0', '2', '1', '2', '2', '1', '3', '1', '4', '2', '5', '1']
当前itme数 (1, 2, 3, 4, 5, 6, 7)
biangua ['1', '1', '2', '2', '1', '2']
bguastr 112212
		'''
		for i in xrange(0,len(self.dgua),2):
			if self.dgua[i+1]=='1':
				self.bbgua[int(self.dgua[i])]='2'
			else:
				self.bbgua[int(self.dgua[i])]='1'
		print 'biangua',self.bbgua
		self.bguastr=''.join(self.bbgua)
		print 'bguastr',self.bguastr
		for i in xrange(6):
			if self.bbgua[i]=='1':
				self.canvas.create_image(self.guax+130,100+150-30*i,image=self.picyang,tag='pic')
			else:
				self.canvas.create_image(self.guax+130,100+150-30*i,image=self.picyin,tag='pic')
						#下面是六亲
		for i in xrange(6):
			self.canvas.create_text(self.guax+200,100+30*i,font=self.gfont,text=gua64[self.bguastr][i],tag='pic')
Ejemplo n.º 49
0
def pixelSolverTester(dut):
    dut.log.info("Cocotb test boot")

    speedBench = True

    # Create Agents
    cocotb.fork(ClockDomainAsyncReset(dut.clk, dut.reset))
    cocotb.fork(simulationSpeedPrinter(dut.clk))

    cycleCounter = [0]
    cocotb.fork(cycleCounterAgent(dut, cycleCounter))

    cmdThread = cocotb.fork(cmdAgent(dut, 1.0 if speedBench else 0.5))

    resultArray = [[0 for x in xrange(resX)] for y in xrange(resY)]
    rspThread = cocotb.fork(
        rspAgent(dut, resultArray, 1.0 if speedBench else 0.5))

    # Wait everybody finish its job
    yield cmdThread.join()
    yield rspThread.join()

    # Flush the mandelbrot into a text file
    uutString = reduce(lambda a, b: a + "\n" + b,
                       [str(e) for e in resultArray])
    uutFile = open('mandelbrot.uut', 'w')
    uutFile.write(uutString)
    uutFile.flush()
    uutFile.close()

    # Count how many iteration were done
    iterationCount = 0
    for y in xrange(resY):
        for x in xrange(resX):
            iterationCount += resultArray[y][x] + 1

    print("Done in %d cycles => %f iteration/cycle" %
          (cycleCounter[0], 1.0 * iterationCount / cycleCounter[0]))

    # Display the mandelbrot picture in a GUI
    from Tkinter import Tk, Canvas, PhotoImage
    zoomFactor = 4
    pictureWidth, pictureHeight = resX * zoomFactor, resY * zoomFactor
    window = Tk()
    canvas = Canvas(window,
                    width=pictureWidth,
                    height=pictureHeight,
                    bg="#000000")
    canvas.pack()
    img = PhotoImage(width=pictureWidth, height=pictureHeight)
    canvas.create_image((pictureWidth / 2, pictureHeight / 2),
                        image=img,
                        state="normal")

    for y in xrange(resY):
        for x in xrange(resX):
            r, g, b = 0, 0, 0
            r = resultArray[y][x] << 4
            for zy in xrange(zoomFactor):
                for zx in xrange(zoomFactor):
                    img.put("#%02x%02x%02x" % (r, g, b),
                            (x * zoomFactor + zx, y * zoomFactor + zy))

    window.mainloop()

    # Check differences with the reference image
    refFile = open('mandelbrot.ref', 'r')
    refString = refFile.read()
    if refString != uutString:
        raise TestFailure(
            "FAIL because of picture missmatch, see mandelbrot.ref vs mandelbrot.uut"
        )
Ejemplo n.º 50
0
class Window(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent, background="white")            
        self.parent = parent        
        self.initUI()
        
        home='/home/little_light/Desktop/workspace/python/data/GSTRB'
        modelFile=home+'/model/demo2.pkl'
        input_var = T.tensor4('inputs',dtype=theano.config.floatX)
        target_var = T.ivector('targets')
        network,loss,params=build_2f(input_var,target_var,regularW=0.0001)
        pvals=cPickle.load(open(modelFile))
        [p.set_value(pval) for (p, pval) in zip(lasagne.layers.get_all_params(network), pvals)]
    
        predict=lasagne.layers.get_output(network, deterministic=True)
        input=lasagne.layers.get_all_layers(network)[0].input_var
        #lasagne.layers.input.input
        self.predict_fn=theano.function(inputs=[input],outputs=predict)
        
    def initUI(self):
        self.parent.title("Simple")
        self.pack(fill=BOTH, expand=1)
        self.tbImg=Entry(self.parent,width=50)
        self.tbImg.place(x=10,y=10)
        self.bLoad=Button(master=self,text="Load", command = self.load)
        self.bLoad.pack()
        self.bLoad.place(x=10,y=30)
        
        self.canvas = Canvas(self, width=400, height=400)      
        self.canvas.pack()
        
        fileName='/home/little_light/Desktop/workspace/python/data/GSTRB/Final_Training/Images/00000/00004_00029.ppm'
        
        
        img = ImageTk.PhotoImage(Image.open(fileName))      
        
        self.canvas.image=img
        self.image_on_canvas=self.canvas.create_image(0,0,image=img,anchor='nw')   
        
        self.canvas.place(x=10,y=60)
        
        self.v = StringVar()
        self.label=Label(master=self,textvariable=self.v)
        self.v.set("Target label:")
        self.label.place(x=10,y=470)
        
        
    def load(self):
        print "load"
        fileName=self.tbImg.get()
        img = ImageTk.PhotoImage(Image.open(fileName))
        self.canvas.image=img
        #self.canvas.create_image(0,0,image=img)
        self.canvas.itemconfig(self.image_on_canvas, image =self.canvas.image)
        img=Image.open(fileName)
        img.load() 
        img2=img.resize((32,32))
        img2.load()
        data = np.asarray(img2, dtype="int32")
        mean=86.2111433696
        data=np.transpose(data,(2,0,1))
        data=np.asarray((data-mean)/256.0,dtype=theano.config.floatX)
        data2=np.zeros((1,3,32,32),dtype=theano.config.floatX)
        data2[0]=data
        data=data2
        print np.argmax(self.predict_fn(data)[0])
        self.v.set("Target label:"+str(np.argmax(self.predict_fn(data)[0])))
Ejemplo n.º 51
0
class ImageViewer(Frame, object):

    class _Panner(object):
        def __init__(self):
            self.viewers = []
            self._factor = 1
            self._drags = []
            self._cdrag = None

        def add(self, val):
            self.viewers.append(val)
            for mark, end in self._drags:
                val.canvas.scan_mark(*mark)
                val.canvas.scan_dragto(*end, gain=1)
            if self._cdrag:
                val.canvas.scan_mark(*self._cdrag[0])
                val.canvas.scan_dragto(*self._cdrag[1], gain=1)

        def move_mark(self, x, y):
            if self._cdrag:
                self._drags.append(self._cdrag)

            self._cdrag = [(x, y), (x, y)]

            for viewer in self.viewers:
                viewer.canvas.scan_mark(x, y)

        def move_actual(self, x, y):
            self._cdrag[1] = (x, y)
            for viewer in self.viewers:
                viewer.canvas.scan_dragto(x, y, gain=1)

        def update(self):
            for viewer in self.viewers:
                viewer._update()

    def __init__(self, master, panner=None):
        super(ImageViewer, self).__init__(master)

        self._image = None
        self._view = None
        self._view_id = None

        self.canvas = Canvas(self, background="#000")
        self.canvas.pack(fill='both', expand=1)
        self.canvas.bind("<MouseWheel>", self.zoom)
        self.canvas.bind("<ButtonPress-1>", self.scroll_start)
        self.canvas.bind("<B1-Motion>", self.scroll_move)
        # self.canvas.bind("<Enter>", self.focus_widget)
        # self.canvas.bind("<Leave>", self.unfocus_widget)

        self.popup_menu = PopupMenu(self.canvas)
        for val in (10, 25, 50, 75, 100, 150, 200, 250, 300, 500):
            self.popup_menu.add_command(label="%d%%"%val, command=(lambda v:(lambda :self.set_factor(v/100.)))(val))

        self.popup_menu.attach()

        self._panner = panner
        if panner is None:
            self._panner = ImageViewer._Panner()
        self._panner.add(self)

        self._focus_prev = None

    def destroy(self):
        self._panner.viewers.remove(self)
        super(ImageViewer, self).destroy()

    @property
    def image(self):
        return self._image

    @image.setter
    def image(self, value):
        self._image = value
        self.after(1, self.show)

    @property
    def factor(self):
        return self._panner._factor

    @factor.setter
    def factor(self, value):
        self._panner._factor = value
        self.after(1, self.show)

    def set_factor(self, value):
        self.factor = value

    def zoom(self, event):
        if event.delta < 0:
            if self.factor == .1:
                return
            self.factor -= .1
        elif event.delta > 0:
            if self.factor == 5:
                return
            self.factor += .1
        self.show()

    def scroll_start(self, event):
        self._panner.move_mark(event.x, event.y)

    def scroll_move(self, event):
        self._panner.move_actual(event.x, event.y)

    def focus_widget(self, event):
        self._focus_prev = self.canvas.focus_get()
        self.focus_set()

    def unfocus_widget(self, event):
        self._focus_prev.focus_set()

    def show(self):
        self._panner.update()

    def _update(self):
        if self._image is None:
            return

        if self._view_id is not None:
            self.canvas.delete(self._view_id)

        x, y = self.image.size
        x, y = int(round(x*self.factor)), int(round(y*self.factor))

        self._view = ImageTk.PhotoImage(self.image.resize((x, y)))

        self._view_id = self.canvas.create_image(0, 0, image=self._view, anchor="nw")
        self.canvas.configure(scrollregsion=self.canvas.bbox("ALL"))
Ejemplo n.º 52
0
class TutorWindow( Toplevel ):
    """
    Window for displaying a basic help
    """
    labels      = {}            # Dictionary for keeping clickable labels
    size_x      = 600           # horizontal size of canvas
    size_y      = 800           # vertical size of canvas
    last_images = []            # handle on images currently on the canvas
    images      = []            # new images to go on the canvas
    curr_key    = None          # Current key that is looked at
    
    # Names of label links and list of pictures to load. These pictures are generated from a pdf by save as, type .png
    help_dict = { "Get Pictures"    : [ "Get_Pictures_Page_1.png" , "Get_Pictures_Page_2.png" , "Get_Pictures_Page_3.png"  ],
                  "Save Pictures"   : [ "Save_Pictures_Page_1.png", "Save_Pictures_Page_2.png", "Save_Pictures_Page_3.png" ],
                  "Pictures Effects": [ "Pic_Effects_Page_1.png"  , "Pic_Effects_Page_2.png"                               ],
                  "Options"         : [ "Options.png"                                                                      ],
                }

    def __init__( self ):
        """
        Initialize window settings
        """
        
        Toplevel.__init__( self )
        self.title( "Tutorial" )
        self.iconbitmap( ICON_FILENAME )
        self.geometry( "+100+50" )
        
        # init frames for window. This window contains complicated frames. i.e. frames with frames inside them.
        fr11 = Frame( self )
        fr1  = Frame( fr11 )
        fr2  = Frame( fr11 )
        fr3  = Frame( self )
        
        # create labels links for displaying different help information
        for name in self.help_dict:
            self.labels[ name ] = Label( fr1, text=name, fg="blue" ) 
            self.labels[ name ].bind( "<ButtonPress-1>", lambda e, arg=name: self.HandleLB( e, arg ) )
            self.labels[ name ].pack( fill=X )
        fr1.pack( side=LEFT )
        
        # create/configure canvas and scrollbar for displaying help pictures
        self.canv = Canvas( fr2, width=self.size_x, height=self.size_y, scrollregion=( 0, 0, 300, 0 ) )
        self.sbar = Scrollbar( fr2 )
        self.sbar.config( command=self.canv.yview )
        self.canv.config( yscrollcommand=self.sbar.set )
        self.canv.focus_set()
        self.sbar.pack( side=RIGHT, fill=Y )
        self.canv.pack( side=LEFT, fill=Y )

        fr2.pack( side=LEFT )
        fr11.pack()
    
        # create ok button for closing the window
        btn = Button( fr3, text="Ok", width=10, command=self.quit )
        btn.pack( side=LEFT )
        fr3.pack()
        
        self.mainloop()
        self.destroy()
        
    def HandleLB( self, event, key ):
        """
        handle clicking a label link
        """
        
        if( key != self.curr_key ):
        
        
            # reset the position of the scrollbar to the top
            self.canv.yview_moveto( 0.0 )

            # load new images
            print "Key: ", key
            self.LoadImages( key )
            
            # change formatting on labels, color red for current one clicked
            self.FormatLabels( key )
            
            # remove old pictures from the canvas before adding new ones
            if( len( self.last_images ) != 0 ):
                for image in self.last_images:
                    self.canv.delete( image )
            self.last_images = []
    
            # There's an offset required in order to show everything correctly, don't know why...
            image_y = 390
    
            # change scrollable area for the canvas to be exact size of all pictures
            self.canv.config( scrollregion=( 0, 0, 300, 776*len( self.images ) ) )
            
            # add new pictures to canvas stacking them on top of each other and making them seamless
            for i in range( len( self.images ) ):
                self.last_images.append( self.canv.create_image( ( self.size_x/2, image_y ), image=self.images[ i ] ) )
                image_y += self.images[ i ].height()
                
            self.curr_key = key
            
    def LoadImages( self, key ):
        """
        load new inmages into class storage
        """
        self.images = []
        print "help_dict: ", self.help_dict        
        # get images from hardcoded array
        for image in self.help_dict[ key ]:
            
            # open PIL image
            print "image: ", path.join( HELP_DIR, image )

            image1 = PILopen( path.join( HELP_DIR, image ) )
    
            # resize to fit canvas area
            image1 = image1.resize( ( self.size_x , self.size_y ), ANTIALIAS )
            
            # make into a tkimage
            im = PhotoImage( image1 )
             
            # add to list of images to display 
            self.images.append( im )
    
    def FormatLabels( self, key ):
        for name in self.labels:
            self.labels[ name ].config( fg="blue" )
            
        self.labels[ key ].config( fg="red" )
Ejemplo n.º 53
0
def capture():
    global captured
    captured = True


root = Tkinter.Tk()
cap = cv2.VideoCapture(0)

canvas = Canvas(root, width=800, height=600)
canvas.grid(row=0, column=0)
button = Button(root, text="Capture", command=capture)
button.grid(row=1, column=0)

ret = False
while not ret:
    ret, img = cap.read()
while True:
    ret, img = cap.read()
    img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    photo = ImageTk.PhotoImage(image=img)
    canvas.create_image(0, 0, anchor='nw', image=photo)
    root.update_idletasks()
    root.update()
    global captured
    if captured:
        print 'capture'
        img.save('/Users/lihaijiang/Documents/PYWork/torchai/img/img_%d.jpg' %
                 cnt)
        cnt = cnt + 1
        captured = False
Ejemplo n.º 54
0
            print "Inside was ", inside, " pixels"
            if inside > 5:
                if check_roundness(filled_pixels):
                    count += 1
                    for pix in filled_pixels:
                        pic.putpixel(pix, (182, 0, 255))

print count

app = Tk()
canvas = Canvas(app)
canvas.pack()
canvas['width'] = width
canvas['height'] = height
pimg = ImageTk.PhotoImage(image=pic)
canvas.create_image(width / 2, height / 2, anchor='center', image=pimg)
app.mainloop()


#Kent Flood fill
def yup(x, y):
    count = []
    global countc
    pixely = 0
    count.append(x)
    count.append(y)
    #print('hi')
    while count != []:
        if newim.getpixel((count[0], count[1])) == (0, 0, 0):
            newim.putpixel((count[0], count[1]), (255, 0, 0))
            pixely += 1
Ejemplo n.º 55
0
    print t, y, vy

    yp = 0.7 * h - 0.7 * h * y / 100.0
    canvas.coords(ship, w / 4, yp)

    if y >= 0.0:
        canvas.after(1, tick)


root = Tk()
canvas = Canvas(root, width=w, height=h, bg='black')
canvas.pack()

img1 = Image.open('earthrise.jpg').resize((w, h))
pmg1 = ImageTk.PhotoImage(img1)
canvas.create_image(w / 2, h / 2, image=pmg1)

img2 = Image.open('eagle.jpg').resize((200, 200))
pmg2 = ImageTk.PhotoImage(img2)
ship = canvas.create_image(w / 4, 0, image=pmg2)

canvas.create_rectangle(w / 4 - 150,
                        int(0.5 + 0.7 * h) + 100,
                        w / 4 + 150,
                        int(0.5 + 0.7 * h) + 125,
                        outline='green',
                        fill='green')

print t, y, vy

canvas.after(1000, tick)
Ejemplo n.º 56
0
class WorldWar(Frame):
    canvas = None
    menu = None
    selected = None
    selected_2 = None
    state = SELECT
    player = PLAYER_ALLY

    def __init__(self, parent):

        # IMAGES #########
        self.NODE_IMG = [
            ImageTk.PhotoImage(Image.open("img/node1.png")),
            ImageTk.PhotoImage(Image.open("img/node2.png")),
            ImageTk.PhotoImage(Image.open("img/node3.png")),
            ImageTk.PhotoImage(Image.open("img/node4.png")),
        ]

        self.BG = ImageTk.PhotoImage(Image.open("img/map.png"))

        self.FLAG_AXIS = ImageTk.PhotoImage(Image.open("img/flag_axis.png"))
        self.FLAG_ALLY = ImageTk.PhotoImage(Image.open("img/flag_ally.png"))

        self.CANNON = ImageTk.PhotoImage(Image.open("img/cannon.png"))
        self.FORTRESS = ImageTk.PhotoImage(Image.open("img/fort.png"))
        #################

        Frame.__init__(self, parent)

        self.parent = parent
        self.init_ui()
        self.update_ui()
        self.update_menu()

    def init_ui(self):
        self.parent.title("World War II")
        self.pack(fill=tk.BOTH, expand=1)

        self.canvas = Canvas(self, width=WINDOW_W - 200, height=WINDOW_H)

        # self.canvas.bind("<Motion>",self.motion)
        self.canvas.bind("<Button-1>", self.click)

        self.canvas.pack(side=tk.LEFT)

    def update_ui(self):
        self.canvas.create_image(0, 0, anchor=tk.NW, image=self.BG)

        for n in Logic.network:
            self.canvas.create_image(n.x, n.y, anchor=tk.CENTER, image=self.NODE_IMG[n.rank])
            if n.occupant == PLAYER_AXIS:
                self.canvas.create_image(n.x, n.y - NODE_R[n.rank] - 5, anchor=tk.S, image=self.FLAG_AXIS)
            if n.occupant == PLAYER_ALLY:
                self.canvas.create_image(n.x, n.y - NODE_R[n.rank] - 5, anchor=tk.S, image=self.FLAG_ALLY)

            if n.cannon or n.cannon_time > -1:
                self.canvas.create_image(n.x - NODE_R[n.rank] - 5, n.y, anchor=tk.E, image=self.CANNON)
            if n.cannon_time > -1:
                self.canvas.create_text(
                    n.x - NODE_R[n.rank] - 5, n.y + NODE_R[n.rank] + 5, anchor=tk.NE, text=str(Logic.cannon_makers)
                )
            if n.fortress or n.fortress_time > -1:
                self.canvas.create_image(n.x + NODE_R[n.rank] + 5, n.y, anchor=tk.W, image=self.FORTRESS)
            if n.fortress_time > -1:
                self.canvas.create_text(
                    n.x + NODE_R[n.rank] + 5, n.y + NODE_R[n.rank] + 5, anchor=tk.NW, text=str(Logic.fortress_makers)
                )

            self.canvas.create_text(n.x, n.y + NODE_R[n.rank] + 5, anchor=tk.N, text=str(n.allowed))

            if self.selected is not None:
                self.canvas.create_oval(
                    self.selected.x - NODE_R[self.selected.rank] - 5,
                    self.selected.y - NODE_R[self.selected.rank] - 5,
                    self.selected.x + NODE_R[self.selected.rank] + 5,
                    self.selected.y + NODE_R[self.selected.rank] + 5,
                    width=3,
                    outline="#0000FF",
                )

                for n in Logic.adjacent_levels(self.selected):
                    self.canvas.create_line(self.selected.x, self.selected.y, n.x, n.y, arrow=tk.LAST, dash=(3, 3))

            if self.selected_2 is not None:
                self.canvas.create_oval(
                    self.selected_2.x - NODE_R[self.selected_2.rank] - 5,
                    self.selected_2.y - NODE_R[self.selected_2.rank] - 5,
                    self.selected_2.x + NODE_R[self.selected_2.rank] + 5,
                    self.selected_2.y + NODE_R[self.selected_2.rank] + 5,
                    width=3,
                    outline="#FF0000",
                )

    def update_menu(self):
        if self.menu is not None:
            self.menu.destroy()
        self.menu = Frame(self, width=200, height=WINDOW_H)
        self.menu.pack(fill=tk.X)

        plr = Label(self.menu, text=("Player: ALLIES" if self.player is PLAYER_ALLY else "Player: AXIS"))
        plr.pack(fill=tk.X, padx=5, pady=5)

        if self.selected_2 is not None:
            if self.selected_2.cannon_time > -1:
                txt = "%d moves to build" % (Logic.cannon_ready - self.selected_2.cannon_time)
                if self.selected_2.cannon:
                    txt = "cannon present"
                lbl_can = Label(self.menu, text=txt, image=self.CANNON, compound=tk.LEFT)
                lbl_can.pack(fill=tk.X, padx=5, pady=5)

            if self.selected_2.fortress_time > -1:
                txt = "%d moves to build" % (Logic.fortress_ready - self.selected_2.fortress_time)
                if self.selected_2.fortress:
                    txt = "fortress present"
                lbl_can = Label(self.menu, text=txt, image=self.FORTRESS, compound=tk.LEFT)
                lbl_can.pack(fill=tk.X, padx=5, pady=5)

            move = Button(self.menu, text="CONFIRM MOVE", command=self.confirm_move)
            move.pack(fill=tk.X, padx=5, pady=5)

            PHOTO = ImageTk.PhotoImage(Image.open(self.selected_2.image))
            data = Label(
                self.menu, text=self.selected_2.text, wraplength=200, padx=5, pady=5, image=PHOTO, compound=tk.BOTTOM
            )
            data.pack(fill=tk.X, padx=5, pady=5)

            return

        if self.state == MOVE:
            an = Label(self.menu, text="Select another node")
            an.pack(fill=tk.X, padx=5, pady=5)
            return

        if self.selected is not None:
            if self.selected.cannon_time > -1:
                txt = "%d moves to build" % (Logic.cannon_ready - self.selected.cannon_time)
                if self.selected.cannon:
                    txt = "cannon present"
                lbl_can = Label(self.menu, text=txt, image=self.CANNON, compound=tk.LEFT)
                lbl_can.pack(fill=tk.X, padx=5, pady=5)

            if self.selected.fortress_time > -1:
                txt = "%d moves to build" % (Logic.fortress_ready - self.selected.fortress_time)
                if self.selected.fortress:
                    txt = "fortress present"
                lbl_can = Label(self.menu, text=txt, image=self.FORTRESS, compound=tk.LEFT)
                lbl_can.pack(fill=tk.X, padx=5, pady=5)

            if self.player == self.selected.occupant:
                move = Button(self.menu, text="MOVE", command=self.move)
                move.pack(fill=tk.X, padx=5, pady=5)

                if not self.selected.cannon:
                    mk_can = Button(self.menu, text="MAKE CANNON", command=self.mk_cannon)
                    mk_can.pack(fill=tk.X, padx=5, pady=5)

                if not self.selected.fortress:
                    mk_ft = Button(self.menu, text="MAKE FORTRESS", command=self.mk_fortress)
                    mk_ft.pack(fill=tk.X, padx=5, pady=5)

            PHOTO = ImageTk.PhotoImage(Image.open(self.selected.image))
            data = Label(
                self.menu, text=self.selected.text, wraplength=200, padx=5, pady=5, image=PHOTO, compound=tk.BOTTOM
            )
            data.pack(fill=tk.X, padx=5, pady=5)

    def confirm_move(self):
        num = askinteger("Troops:", "Enter number of troops :", parent=self)
        if num == 0:
            showerror("Error", "Kuch to hila")
        else:
            result = None
            if self.selected.cannon:
                if askyesno("Move cannon?", parent=self):
                    result = Logic.move(self.selected, self.selected_2, num, True, 0, 0)
                else:
                    result = Logic.move(self.selected, self.selected_2, num, False, 0, 0)
            else:
                result = Logic.move(self.selected, self.selected_2, num, False, 0, 0)
            if result[0]:
                self.next_move()
            else:
                showerror("Error", result[1])
                self.selected_2 = None
                self.state = SELECT
        self.update_ui()
        self.update_menu()

    def move(self):
        self.state = MOVE
        self.update_ui()
        self.update_menu()

    def mk_cannon(self):
        result = Logic.move(self.selected, None, 0, False, 1, 0)
        if result[0]:
            self.next_move()
        else:
            showerror("Error", result[1])

    def mk_fortress(self):
        result = Logic.move(self.selected, None, 0, False, 0, 1)
        if result[0]:
            self.next_move()
        else:
            showerror("Error", result[1])

    def click(self, event):
        if self.state == SELECT:
            self.selected = get_node_at(event.x, event.y)
        else:
            self.selected_2 = get_node_at(event.x, event.y)
            if self.selected_2 == self.selected:
                self.selected_2 = None
        self.update_ui()
        self.update_menu()

    def next_move(self):
        if Logic.network[0].occupant == PLAYER_AXIS:
            showinfo("Game Ends", "Player AXIS wins!")
            sys.exit()
        if Logic.network[17].occupant == PLAYER_ALLY:
            showinfo("Game Ends", "Player ALLY wins!")
            sys.exit()

        self.selected = None
        self.selected_2 = None
        self.state = SELECT
        self.player = PLAYER_AXIS if self.player is PLAYER_ALLY else PLAYER_ALLY
        self.update_ui()
        self.update_menu()
Ejemplo n.º 57
0
class App: 
    def __init__(self, master):
        self.master = master
        
        self.file = 'grid.csv'
        
        self.ownZepName = "goud"
        
        self.updatingFlag = False
        
        self.btnUpPressed = False
        self.btnDownPressed = False
        self.btnLeftPressed = False
        self.btnRightPressed = False
        self.btnPlusPressed = False
        self.btnMinusPressed = False
        
        #keyListener aanzetten
        master.bind("<Key>", self.keyPressed)
        master.bind("<KeyRelease>", self.keyReleased)
        
        leftFrame = Frame(master, width = 200, height = 640)
        leftFrame.grid(row = 0, column = 0)
        
        debugFrame = Frame(leftFrame, width = 200, height = 400)
        debugFrame.grid(row = 0, column = 0)
        controlFrame = Frame(leftFrame, width = 200, height = 200)
        controlFrame.grid(row = 1, column = 0, pady = 10)
        
        rasterFrame = Frame(master, width = 600, height = 640)
        rasterFrame.grid(row = 0, column = 1)
        
        #Scrolledtext in leftTopFrame
        self.scrDebug = ScrolledText(debugFrame, wrap = WORD, state = "disabled", fg = "dark red", width=80)
        self.scrDebug.grid(row = 0, column = 0, padx = 10, pady = 10)
        
        #Buttons
        #simulator
        self.btnToggleSimu = Button(controlFrame, text = "Simulator", width = 14, bg = 'gray85', command = lambda: self.toggleSimulator())
        self.btnToggleSimu.grid(row = 3, column = 2)
        
        self.btnMoveToSimu = Button(controlFrame, text = "Ga naar (Sim)", width = 14, bg = 'gray85', command = lambda: self.moveTo(Name = "goudsimu"))
        self.btnMoveToSimu.grid(row = 1, column = 4)
        
        self.btnHeightSimu = Button(controlFrame, text = "Kies hoogte (Sim)", width = 14, bg = 'gray85', command = lambda: self.setGewensteHoogte(Name ="goudsimu"))
        self.btnHeightSimu.grid(row = 2, column = 4)
        
        #hoogte
        self.gemetenHoogteString = StringVar()
        self.gemetenHoogteString.set(str(0))
        self.lblGemetenHoogte = Label(controlFrame, text="Gemeten Hoogte:  ", anchor = "w")
        self.lblGemetenHoogteVar = Label(controlFrame, textvariable = self.gemetenHoogteString, width = 20)
        self.lblGemetenHoogte.grid(row=0, column=2)
        self.lblGemetenHoogteVar.grid(row=0, column=3)
        
        #move to
        self.btnMoveTo = Button(controlFrame, text="Ga naar (Zep)", bg = 'gray85', width = 14, command = lambda: self.moveTo())
        self.btnMoveTo.grid(row=1,column=2)
        self.txtMoveTo = Entry(controlFrame, width=24)
        self.txtMoveTo.grid(row=1, column=3)
        self.txtMoveTo.bind('<Return>', self.moveTo)
        
        #hoogte 
        self.btnHeight = Button(controlFrame, text="Kies hoogte (Zep)", bg = 'gray85', width = 14, command = lambda: self.setGewensteHoogte())
        self.btnHeight.grid(row=2,column=2)
        self.txtHeight = Entry(controlFrame, width=24)
        self.txtHeight.grid(row=2, column=3)
        self.txtHeight.bind('<Return>', self.setGewensteHoogte)
        
        #images
        self.display = Canvas(rasterFrame, width=600, height=570, bd=0, highlightthickness=0)
        self.display.grid(row=0, column = 0, sticky=W+E+N+S)
        
        foundFigures = Label(controlFrame, text = "Herkende figuren:")
        foundFigures.grid(row = 0, column = 0)        
        self.display2 = Canvas(controlFrame, width = 220, height=165, bd=2, relief = "groove", highlightthickness=0)
        self.display2.grid(row=1, column = 0, sticky=W+E+N+S, rowspan=12)
        self.latestphoto = Image.new("RGB", (220,165), (150,150,150))        
        self.latestImage = ImageTk.PhotoImage(self.latestphoto)
        self.display2.create_image(0, 0, image=self.latestImage, anchor=NW)
        
        #goal
        original = Image.open('goalPin.png')
        resized = original.resize((60,60),Image.ANTIALIAS)
        self.goalImage = ImageTk.PhotoImage(resized)
        
        self.makeBackground()
        self.initZeppelins()
        self.paintCanvas()
        
        self.sim = None
        mq.setGUI(self)
                
    def initZeppelins(self):
        self.zeppelins = []
        self.goal = (-100,-100)
#         self.zeppelins.append(AbstractZeppelin('red', 'simu'))
        self.zeppelins.append(AbstractZeppelin('#EBB400', self.ownZepName))
                
    def convToPixelCoords(self, pos):
        cmHeight = 34.6410162
        cmWidth = 40.0
        xcm, ycm = pos
        x = self.evenXStart + (xcm/cmWidth)*self.triangleWidth
        y = self.yStart + (ycm/cmHeight)*self.triangleHeight
        result = (x,y)
        return result
    
    def createPhoto(self, cvresults):
        self.latestphoto = Image.new("RGB", (220,165), (150,150,150))
        cv = eval(cvresults)
        width = cv[0]
        height = cv[1]
        figures = cv[2]
        coordinates = cv[3]
        for i in xrange(0,len(figures)):
            j = self.allShapes.index(figures[i])
            image = self.shapeImages[j]
            xcoord = int(coordinates[i][0]/(width*1.0)*220)
            ycoord = int(coordinates[i][1]/(height*1.0)*165)
            self.latestphoto.paste(image, (xcoord-12, ycoord-12), mask = image)
               
        self.latestImage = ImageTk.PhotoImage(self.latestphoto)
        self.display2.create_image(0, 0, image=self.latestImage, anchor=NW)
    
    def makeBackground(self):
        #rooster inlezen:
        f = open("../positioning/"+ str(self.file), 'r')
        shapesText = f.read()
        self.raster = []
        self.tabletLocations = []
        nrows = 0
        ncol = 0
        for line in shapesText.split("\n"):
            temp = line.split(",")
            if not len(temp) == 2:
                nrows += 1
                if ncol == 0:
                    ncol = len(temp)
                for s in temp:
                    self.raster.append(s.strip())
            else:
                self.tabletLocations.append((int(temp[0]), int(temp[1])))
        f.close()
        
        tempWidth1 = 600/ncol
        tempHeight1 = int(round((math.sqrt(tempWidth1**2 - (tempWidth1/2)**2)), 0))
        
        tempHeight2 = 570/nrows+2
        tempWidth2 = int(round((math.sqrt(4/3 * tempHeight2**2)),0))
        
        #raster
        self.resizedRaster = Image.new("RGB", (600,570), (240,240,240))
        #vormpjes
        self.allShapes = ['BC','BH','BR','BS','GC','GH','GR','GS','RC','RH','RR','RS','WC','WH','WR','WS','YC','YH','YR','YS']
        self.shapeImages = []
        
        for i in range(20):
            imgFile = "vormpjes/" + self.allShapes[i] + ".png"
            original = Image.open(imgFile)
            self.shapeImages.append(original.resize((24, 24),Image.ANTIALIAS))
            
        original = Image.open("tablet.png")
        self.tabletIm = original.resize((40,40),Image.ANTIALIAS)
            
        self.xlen = ncol
        self.ylen = nrows
        self.triangleWidth = min(tempWidth1, tempWidth2)
        self.triangleHeight = min(tempHeight1, tempHeight2)
        self.evenXStart = (600-((ncol)*self.triangleWidth))/2 + self.triangleWidth/4
        self.oddXStart = self.evenXStart + self.triangleWidth/2
        self.yStart = (600-((nrows)*self.triangleHeight))/2 + self.triangleHeight/4
        
        
        draw = ImageDraw.Draw(self.resizedRaster)
        #grid tekenen
        for y in range(self.ylen):
            for x in range(self.xlen):
                ycoord = self.yStart + y*self.triangleHeight
                
                zelf = self.raster[y*self.xlen + x] != "XX"
                if y>0: 
                    boven = self.raster[(y-1)*self.xlen + x] != "XX"
                if y<self.ylen-1:
                    onder = self.raster[(y+1)*self.xlen + x] != "XX"
                if y>0 and x < self.xlen-1: 
                    oddboven = self.raster[(y-1)*self.xlen + x+1] != "XX"
                if y<self.ylen-1 and x < self.xlen-1:
                    oddonder = self.raster[(y+1)*self.xlen + x+1] != "XX"
                if x<self.xlen-1:
                    naast = self.raster[y*self.xlen + x+1] != "XX"
            
                if y % 2 == 0:
                    xcoord = self.evenXStart + x*self.triangleWidth
                    if x < self.xlen-1 and naast and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0)
                    if y < self.ylen-1 and onder and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0)
                    if y > 0 and boven and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0)
                else:
                    xcoord = self.oddXStart + x*self.triangleWidth
                    if x < self.xlen-1 and naast and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth, ycoord), fill = 0)
                    if y < self.ylen-1 and x < self.xlen-1 and oddonder and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord+self.triangleHeight), fill = 0)
                    if y > 0 and x < self.xlen-1 and oddboven and zelf:
                        draw.line((xcoord, ycoord, xcoord+self.triangleWidth/2, ycoord-self.triangleHeight), fill = 0)
                
        del draw
        
        for loc in self.tabletLocations:
            conv = self.convToPixelCoords((loc[0]/10, loc[1]/10))
            self.resizedRaster.paste(self.tabletIm, (int(conv[0])-20, int(conv[1])-20), mask = self.tabletIm)
        
        #vormpjes tekenen
        for y in range(self.ylen):
            for x in range(self.xlen):
                index = y*self.xlen + x
                if y % 2 == 0:
                    xcoord = self.evenXStart + x*self.triangleWidth
                else:
                    xcoord = self.oddXStart + x*self.triangleWidth
                ycoord = self.yStart + y*self.triangleHeight
                shape = self.raster[index]
                if shape != 'XX':
                    image = self.shapeImages[self.allShapes.index(shape)]
                    self.resizedRaster.paste(image, (xcoord-12, ycoord-12), mask = image)
    
        self.rasterImage = ImageTk.PhotoImage(self.resizedRaster)
        
    def updatePath(self):
        self.rasterBackup = self.rasterImage
        draw = ImageDraw.Draw(self.resizedRaster)
        for z in self.zeppelins:
            length = len(z.locations)
            if length > 1:
                prev = self.convToPixelCoords(z.locations[length-2])
                current = self.convToPixelCoords(z.locations[length-1])
                draw.line((prev[0], prev[1], current[0], current[1]), fill=z.color, width = 3)
        self.rasterImage = ImageTk.PhotoImage(self.resizedRaster)
        del draw
            
        
    def paintCanvas(self):
        #clear the canvas
        #self.display.delete('all')
        #rooster tekenen
        self.updatePath()
        self.display.create_image(0, 0, image=self.rasterImage, anchor=NW)
        
        #Testcode voor zeppelin locatie
        for z in self.zeppelins:
            if z.orientationFound:
                point1x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation + 20))
                point1y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation + 20))
                point2x = self.convToPixelCoords(z.location)[0]+16*math.sin(math.radians(z.orientation - 20))
                point2y = self.convToPixelCoords(z.location)[1]+16*math.cos(math.radians(z.orientation - 20))
                point3x = self.convToPixelCoords(z.location)[0]+28*math.sin(math.radians(z.orientation))
                point3y = self.convToPixelCoords(z.location)[1]+28*math.cos(math.radians(z.orientation))
                arrowPoints = [point1x, point1y, point2x, point2y, point3x, point3y]
                self.display.create_polygon(arrowPoints, fill=z.color, outline='black', width = 1)
            self.display.create_oval(self.convToPixelCoords(z.location)[0]-12, self.convToPixelCoords(z.location)[1]-12,self.convToPixelCoords(z.location)[0]+12, self.convToPixelCoords(z.location)[1]+12, fill=z.color)
                    
        self.display.create_image(self.convToPixelCoords(self.goal)[0]+6, self.convToPixelCoords(self.goal)[1]-18, image = self.goalImage, anchor=CENTER)
    
    def toggleSimulator(self):
        if self.sim == None:
            enemy = "goudsimu"
            self.zeppelins.append(AbstractZeppelin("red", enemy))
            mq.initEnemy(enemy)
            self.sim = simulator.simulator(100,100, enemy)
            return
        self.sim.toggleActive()
    
    def updateGoal(self, location, tablet):
        self.debugPrint("Nieuw doel voor simulator: " + str(tablet) + "   " + str(location))
        self.goal = self.convToPixelCoords(location)
        self.paintCanvas()
        
    def updateLocation(self, location, n):
        self.debugPrint("Nieuwe locatie voor " + n + " ontvangen: " + str(location))
        for z in self.zeppelins:
            if z.name == n:
                z.updateLocation((location[0]/10, location[1]/10))
        self.paintCanvas()
        
    def updateHeight(self, height, n):
        self.debugPrint("Nieuwe hoogte voor " + n + " ontvangen: " + str(height))
        if self.ownZepName == n:
            self.gemetenHoogteString.set(str(height))
        
    def updateAngle(self, angle, n):
        self.debugPrint("Nieuwe orientatie voor " + n + " ontvangen: " + str(angle) + " graden")
        for z in self.zeppelins:
            if z.name == n:
                z.updateAngle(angle)
        self.paintCanvas()
    
    def showCvResults(self, body):
        self.debugPrint("Nieuwe foto vertaling ontvangen: " + body)
        self.createPhoto(body)
       
    #gewenste hoogte aanpassen    
    def setGewensteHoogte(self, event = None, Name = "goud"):
        x = self.txtHeight.get()
        self.txtHeight.delete(0, END)
        self.master.focus()
        try:
            x = int(x)
        except:
            return
        if isinstance(x, int) and x > 0 and x < 8000:
            global neededHeight
            neededHeight = x
            message = "Hoogte instellen op " + str(neededHeight) + " aangevraagd"
            self.debugPrint(message)
            mq.elevate(x, Name)
            
    #gewenste hoogte aanpassen    
    def moveTo(self, event = None, Name = "goud"):
        st = self.txtMoveTo.get()
        self.txtMoveTo.delete(0, END)
        self.master.focus()
        try:
            xst, yst = st.split(',')
            x = int(xst)
            y = int(yst)
        except:
            return
        if isinstance(x, int) and isinstance(y, int):
            message = "Bewegen naar (" + str(x) + "," + str(y) + ") aangevraagd"
            self.debugPrint(message)
            self.goal = x/10,y/10
            self.paintCanvas()
            mq.moveTo(x, y, Name)
     
    #tekst weergeven in debug venster    
    def debugPrint(self, tekst):
        self.scrDebug.config(state = "normal")
        self.scrDebug.insert(END, ">> " + tekst + "\n")
        self.scrDebug.config(state = "disabled")
        self.scrDebug.yview_pickplace("end")
        
    def toggleAutomaticPilot(self):
        if not self.connected:
            return
        self.debugPrint("Automatische piloot toggle aangevraagd")
        self.client.toggleAutomaticPilot() 
        
    def createClient(self):
        try:
            self.client = cl(self, self.ownZepName)
            self.zeppelins.append(AbstractZeppelin('red', self.ownZepName, self, self.client))
            self.connected = True
            self.connectedString.set("Verbonden")
            self.lblConnected.config(fg = "green")
            self.debugPrint("Verbonden met Raspberry Pi")
        except:
            self.debugPrint("Verbinding met Rapsberry Pi niet mogelijk:\n    -Staat de Raspberry Pi aan?\n    -Staat de server aan?\n    -Zit deze computer op de ad-hoc?")
            
        
    def moveForward(self):
        self.debugPrint("Voorwaarts vliegen aangevraagd")
        mq.setMotor1PWM(100)
        mq.setMotor2PWM(100)
        
    def moveBackward(self):
        self.debugPrint("Achterwaarts vliegen aangevraagd")
        mq.setMotor1PWM(-100)
        mq.setMotor2PWM(-100)
    
    def moveLeft(self):
        self.debugPrint("Links draaien aangevraagd")
        mq.setMotor1PWM(100)
        
    def moveRight(self):
        self.debugPrint("Rechts draaien aangevraagd")
        mq.setMotor2PWM(100)
        
    def moveUp(self):
        self.debugPrint("Omhoog vliegen aangevraagd")
        mq.setMotor3PWM(100)
        
    def moveDown(self):
        self.debugPrint("Omlaag vliegen aangevraagd")
        mq.setMotor3PWM(-100)
        
    def horizontalOff(self):
        self.debugPrint("Horizontale motors stoppen aangevraagd")
        mq.setMotor1PWM(0)
        mq.setMotor2PWM(0)
        
    def verticalOff(self):
        self.debugPrint("Verticale motor stoppen aangevraagd")
        mq.setMotor3PWM(0)
        
    #toetsenbord invoer
    def keyPressed(self, event):
        k = event.keysym
        if k == 'Up':
            if not self.btnUpPressed:
                self.btnUpPressed = True
                self.moveForward()
        elif k == 'Down':
            if not self.btnDownPressed:
                self.btnDownPressed = True
                self.moveBackward()   
        elif k == 'Left':
            if not self.btnLeftPressed:
                self.btnLeftPressed = True
                self.moveLeft()
        elif k == 'Right':
            if not self.btnRightPressed:
                self.btnRightPressed = True
                self.moveRight()
        elif k == 'plus':
            if not self.btnPlusPressed:
                self.btnPlusPressed = True
                self.moveUp()
        elif k == 'minus':
            if not self.btnMinusPressed:
                self.btnMinusPressed = True
                self.moveDown()
            
    def keyReleased(self, event):
        k = event.keysym
        if k == 'Up':
            self.btnUpPressed = False
            self.horizontalOff()
        elif k == 'Down':
            self.btnDownPressed = False
            self.horizontalOff()
        elif k == 'Left':
            self.btnLeftPressed = False
            self.horizontalOff()
        elif k == 'Right':
            self.btnRightPressed = False
            self.horizontalOff()
        elif k == 'plus':
            self.btnPlusPressed = False
            self.verticalOff()
        elif k == 'minus':
            self.btnMinusPressed = False
            self.verticalOff()
Ejemplo n.º 58
0
print(json.dumps(needle, sort_keys=True, indent=4, separators=(",", ": ")))

master = Tk()
master.title(basename(filename)[0:len(filename) - len(".json")])

image = Image.open(png)
photo = ImageTk.PhotoImage(image)

width = photo.width()
height = photo.height()

w = Canvas(master, width=width, height=height)
w.pack()

bg = w.create_image(0, 0, anchor=NW, image=photo)

uiareas = []


class UiArea:
    def __init__(self, w, area):
        self.color = "cyan"
        self.w = w
        self.rect = w.create_rectangle(area["xpos"],
                                       area["ypos"],
                                       area["xpos"] + area["width"],
                                       area["ypos"] + area["height"],
                                       outline=self.color)
        self.text = w.create_text(area["xpos"] + area["width"],
                                  area["ypos"] + area["height"],
Ejemplo n.º 59
-1
def failure(reason, cur_dir):
    """
    Displays a "submission failure" picture and emails
    a bug report to maintenance.
    """
    bugmail = {"email": "*****@*****.**"}
    send_email(bugmail, "QR Code Submission Failure", reason, None)
    root = Tk()
    root.focus_set()
    # Get the size of the screen and place the splash screen in the center
    gif = Image.open(str(cur_dir) + '/Images/Failure.gif')
    width = gif.size[0]
    height = gif.size[1]
    flog = (root.winfo_screenwidth()/2-width/2)
    blog = (root.winfo_screenheight()/2-height/2)
    root.overrideredirect(1)
    root.geometry('%dx%d+%d+%d' % (width*1, height + 44, flog, blog))
    # Pack a canvas into the top level window.
    # This will be used to place the image
    failure_canvas = Canvas(root)
    failure_canvas.pack(fill = "both", expand = True)
    # Open the image
    imgtk = PhotoImage(gif)
    # Get the top level window size
    # Need a call to update first, or else size is wrong
    root.update()
    cwidth = root.winfo_width()
    cheight =  root.winfo_height()
    # create the image on the canvas
    failure_canvas.create_image(cwidth/2, cheight/2.24, image=imgtk)
    Button(root, text = str(
        reason), width = 50, height = 2, command = root.destroy).pack()
    root.after(5000, root.destroy)
    root.mainloop()