def update(self, model):
     result = set()
     all_prey = model.find(lambda item:isinstance(item, Prey))
     for item in all_prey:
         if self.contains(item):
             result.add(item)
     self._counter += 1
     closest = self.sightDistance
     existing = all_prey - result
     for item in existing:
         if self.distance(item.get_location()) < closest:
             closest = self.distance(item.get_location())
             self.set_angle(math.atan2(item.get_location()[1] - self.get_location()[1], item.get_location()[0] - self.get_location()[0]))
     if len(result) > 0:
         self.set_dimension(self.get_dimension()[0] + len(result), self.get_dimension()[1] + len(result))
         self._image = PhotoImage(Image.open('deathstar.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS))
         self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height()))
         self._counter = 1
     if self._counter == 30:
         self.radius -= 1
         self.set_dimension(self.get_dimension()[0] - 1, self.get_dimension()[1] - 1)
         self._image = PhotoImage(Image.open('deathstar.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS))
         self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height()))
         self._counter = 1
     self.move()
     if self.get_dimension() < (Hunter.death,Hunter.death):
         result.add(self)
     return result
Example #2
0
    def make_canvas(self):
        """
        Criação do canvas para edição da máscara de correção
        """
        h = Scrollbar(self.root, orient=HORIZONTAL)
        v = Scrollbar(self.root, orient=VERTICAL)
        self.canvas = Canvas(self.root, scrollregion=(0, 0, 1000, 1000), yscrollcommand=v.set, xscrollcommand=h.set)
        
        h['command'] = self.canvas.xview
        v['command'] = self.canvas.yview

        self.canvas.grid(column=0, row=0, sticky=(N,W,E,S))
        h.grid(column=0, row=1, sticky=(W,E))
        v.grid(column=1, row=0, sticky=(N,S))
        self.root.grid_columnconfigure(0, weight=1)
        self.root.grid_rowconfigure(0, weight=1)
        if self.image:
            imgtk = PhotoImage(image=Image.open(self.image))                 # not file=imgpath
            imgwide  = imgtk.width()                         # size in pixels
            imghigh  = imgtk.height()                        # same as imgpil.size
            fullsize = (0, 0, imgwide, imghigh)              # scrollable
            self.canvas.delete('all')                             # clear prior photo
            self.canvas.config(height=imgwide, width=imghigh)   # viewable window size
            self.canvas.config(scrollregion=fullsize)             # scrollable area size
            self.imageid=self.canvas.create_image(0, 0, image=imgtk, anchor=NW)
            self.images.append(imgtk)
            self.canvas.bind("<Button-1>", self.xy)
            self.canvas.bind("<B1-Motion>", self.add_rectangle)
            self.canvas.bind("<B1-ButtonRelease>", self.done_stroke)
            self.canvas.bind_all('<Button-2>', self.select)
            self.canvas.bind_all('<B2-Motion>', self.on_drag)
            self.canvas.bind_all("<B2-ButtonRelease>", self.update_item)
            self.canvas.bind('<Button-3>', self.config_item)
            self.canvas.bind_all('<Delete>',self.delete_item)            
            self.canvas.focus()
Example #3
0
def pil_image_dir():
    from PIL.ImageTk import PhotoImage
    imgdir = 'images'
    if len(sys.argv) > 1:
        imgdir = sys.argv[1]
    imgfiles = os.listdir(imgdir)

    main = Tk()
    main.title('Image Viewer')
    quit = Button(
        main, text='Quit all', command=main.quit, font=('courier', 25))
    quit.pack()
    savephotos = []

    for imgfile in imgfiles:
        imgpath = os.path.join(imgdir, imgfile)
        win = Toplevel()
        win.title(imgfile)
        try:
            imgobj = PhotoImage(file=imgpath)
            Label(win, image=imgobj).pack()
            print(imgpath, imgobj.width(), imgobj.height())
            savephotos.append(imgobj)
        except Exception:
            errmsg = 'skipping %s\n%s' % (imgfile, sys.exc_info()[1])
            Label(win, text=errmsg).pack()
        main.mainloop()
 def update(self, model):
     self._explosion = model.world()[1]/2
     all_swallowed = True
     if self.get_dimension() >= model.world():
         model.big_bang = None
     elif self.get_dimension() >= (self._explosion,self._explosion):
         total = model.world()
         for item in model.items:
             item.set_location(random.uniform(1,total[0] - 1),random.uniform(1,total[1] - 1))
         self.set_dimension(total[0], total[1])
     else:
         for item in model.items:
             location = item.get_location()
             location = (int(location[0]),int(location[1]))
             if location != self._center:
                 all_swallowed = False
                 if location[0] < self._center[0]:
                     new_x = location[0] + 1
                 elif location[0] > self._center[0]:
                     new_x = location[0] - 1
                 else:
                     new_x = location[0]
                 if location[1] < self._center[1]:
                     new_y = location[1] + 1
                 elif location[1] > self._center[1]:
                     new_y = location[1] - 1
                 else:
                     new_y = location[1]
                 item.set_location(new_x,new_y)
             else:
                 self.change_dimension(1, 1)
                 self._image = PhotoImage(Image.open('bigbang.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS))
     if all_swallowed:
         self.change_dimension(10, 10)
         self._image = PhotoImage(Image.open('bigbang.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS))
Example #5
0
    def drawImage(self, imgpil, forcesize=()):
        """
        将图片绘制在窗体的canvas中
        """
        imgtk = PhotoImage(image=imgpil)                 # not file=imgpath
        scrwide, scrhigh = forcesize or self.maxsize()   # wm screen size x,y   #设置窗口显示的宽高
        imgwide  = imgtk.width()                         # size in pixels       #图片的宽高
        imghigh  = imgtk.height()                        # same as imgpil.size

        fullsize = (0, 0, imgwide, imghigh)              # scrollable           #画布总区域
        viewwide = min(imgwide, scrwide)                 # viewable             #画布显示区域
        viewhigh = min(imghigh, scrhigh)

        canvas = self.canvas
        canvas.delete('all')                             # clear prior photo    #删除画布上之前的图像
        canvas.config(height=viewhigh, width=viewwide)   # viewable window size #设置画布显示的区域大小
        canvas.config(scrollregion=fullsize)             # scrollable area size #设置画布可滚动区域总大小
        canvas.create_image(0, 0, image=imgtk, anchor=NW)                       #生成并显示图片并设置图片对齐方式

        if imgwide <= scrwide and imghigh <= scrhigh:    # too big for display? #图片大小比窗体大小小的话则打开窗体大小为普通
            self.state('normal')                         # no: win size per img
        elif sys.platform[:3] == 'win':                  # do windows fullscreen#否则若为windows系统则使窗体全屏
            self.state('zoomed')                         # others use geometry()
        self.saveimage = imgpil                                                 #PIL.Image类型
        self.savephoto = imgtk                           # keep reference on me #PIL.ImageTk.PhotoImage,保持图片引用
        trace((scrwide, scrhigh), imgpil.size)
Example #6
0
    def load_next(self):
        try:
            img = Image.open(self.paths[self.load_pos])
            resize(img, self.thumb_h, self.thumb_w)
            photo = PhotoImage(img)
            col, row = self.column, self.row
            self.photos.append(photo)
            x, y = self.calculate_pos(self.column, self.row)
            photo.cid = self._canvas.create_image(x, y, image=photo)
            photo.index = self.load_pos
            self._canvas.tag_bind(photo.cid, '<Button-1>', lambda e: self.button_callback(e, photo, col, row))
            self._canvas.tag_bind(photo.cid, '<Double-Button-1>', self.activate)
            self._canvas.addtag_withtag('photo', photo.cid)
            self.column += 1
            self.loaded += 1
        except OSError:
            logger.info('Could not open %s', self.paths[self.load_pos])
            self.load_pos += 1
        except Image.DecompressionBombWarning:
            self.load_pos += 1

        if self.column >= self.max_columns:
            self.row += 1
            self.column = 0
        if self.load_pos < len(self.paths) - 1 and self.loaded < self.LIMIT:
            self.load_pos += 1
            self.widget.after_idle(self.load_next)
        elif self.loaded >= self.LIMIT:
            self.loaded = 0
            x, y = self.calculate_pos(self.column, self.row)
            button = Button(self._canvas, text='Load More', command=self.continue_loading)
            cid = self._canvas.create_window(x, y, window=button)
            self._canvas.addtag_withtag('loadbutton', cid)
        self._canvas['scrollregion'] = self._canvas.bbox('all')
class Black_Hole(Simulton):
    
    def __init__(self,x,y):
        self._image = PhotoImage(file='Black_Hole.gif')
        Simulton.__init__(self,x,y,self._image.width(),self._image.height())
        self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height()))


    def update(self, model):
        from hunter import Hunter
        result = set()
        for item in model.find(lambda item:isinstance(item, Prey) or isinstance(item,Hunter)):
            if self.contains(item):
                result.add(item)
        return result
    

    def contains(self,s):
        if not isinstance(s,tuple):
            s = (s.get_location()[0],s.get_location()[1])
        return math.sqrt((self.get_location()[0] - s[0])**2 + (self.get_location()[1] - s[1])**2) <= self.radius
    
    
    def display(self,canvas):
        canvas.create_image(*self.get_location(),image=self._image)
Example #8
0
def image_canvas_simple():
    win = Tk()
    img = PhotoImage(file=gifdir+'ora-lp4e.gif')
    can = Canvas(win)
    can.pack(fill=BOTH)
    can.config(width=img.width(), height=img.height())
    can.create_image(2, 2, image=img, anchor=NW)
    win.mainloop()
Example #9
0
	def __init__(self, imgdir, imgfile):
		Toplevel.__init__(self)
		self.title(imgfile)
		imgpath = os.path.join(imgdir, imgfile)
		imgobj = PhotoImage(file=imgpath)
		Label(self, image = imgobj).pack()
		print(imgpath, imgobj.width(), imgobj.height())
		self.savephoto = imgobj #Keep reference on me
class Pulsator(Black_Hole):
    counter = 30
    death = 15
    
    def __init__(self,x,y,size = 30):
        Black_Hole.__init__(self,x,y)
        self.set_dimension(size, size)
        self._image = PhotoImage(Image.open('space_amoeba.gif').convert('RGBA').resize((size, size), Image.ANTIALIAS))
        self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height()))
        self._counter = 1
        
        
    def update(self, model):
        result = Black_Hole.update(self,model)
        self._counter += 1
        if len(result) > 0:
            self.set_dimension(self.get_dimension()[0] + len(result), self.get_dimension()[1] + len(result))
            self._image = PhotoImage(Image.open('space_amoeba.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS))            
            self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height()))
            self._counter = 1
        if self._counter == Pulsator.counter:
            self.set_dimension(self.get_dimension()[0] - 1, self.get_dimension()[1] - 1)
            self._image = PhotoImage(Image.open('space_amoeba.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS))
            self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height()))
            self._counter = 1
        if self.get_dimension() < (Pulsator.death,Pulsator.death):
            result.add(self)
        return result
Example #11
0
def pil_image_viewer():
    from PIL.ImageTk import PhotoImage
    imgdir = 'images'
    imgfile = 'florida-2009-1.jpg'
    if len(sys.argv) > 1:
        imgfile = sys.argv[1]
    imgpath = os.path.join(imgdir, imgfile)

    win = Tk()
    win.title(imgfile)
    imgobj = PhotoImage(file=imgpath)
    Label(win, image=imgobj).pack()
    win.mainloop()
    print(imgobj.width(), imgobj.height())
class Special(Simulton):
    
    
    def __init__(self,x,y):
        self._image = PhotoImage(Image.open('bigbang.gif').convert('RGBA').resize((20, 20), Image.ANTIALIAS))
        Simulton.__init__(self,x,y,self._image.width(),self._image.height())
        self._center = (int(x),int(y))
        self._explosion = 500


    def update(self, model):
        self._explosion = model.world()[1]/2
        all_swallowed = True
        if self.get_dimension() >= model.world():
            model.big_bang = None
        elif self.get_dimension() >= (self._explosion,self._explosion):
            total = model.world()
            for item in model.items:
                item.set_location(random.uniform(1,total[0] - 1),random.uniform(1,total[1] - 1))
            self.set_dimension(total[0], total[1])
        else:
            for item in model.items:
                location = item.get_location()
                location = (int(location[0]),int(location[1]))
                if location != self._center:
                    all_swallowed = False
                    if location[0] < self._center[0]:
                        new_x = location[0] + 1
                    elif location[0] > self._center[0]:
                        new_x = location[0] - 1
                    else:
                        new_x = location[0]
                    if location[1] < self._center[1]:
                        new_y = location[1] + 1
                    elif location[1] > self._center[1]:
                        new_y = location[1] - 1
                    else:
                        new_y = location[1]
                    item.set_location(new_x,new_y)
                else:
                    self.change_dimension(1, 1)
                    self._image = PhotoImage(Image.open('bigbang.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS))
        if all_swallowed:
            self.change_dimension(10, 10)
            self._image = PhotoImage(Image.open('bigbang.gif').convert('RGBA').resize((self.get_dimension()[0], self.get_dimension()[1]), Image.ANTIALIAS))
    
    
    def display(self,canvas):
        canvas.create_image(*self.get_location(),image=self._image)
class Ball(Prey):
    radius = 5
    
    def __init__(self,x,y):
        self._image = PhotoImage(file='asteroid.gif')
        Prey.__init__(self,x,y,self._image.width(),self._image.height(),random.random()*math.pi*2,5)
        
        
    def update(self,model):
        self.move()
        return set()
    
    
    def display(self,canvas):
        canvas.create_image(*self.get_location(),image=self._image)
Example #14
0
class Floater(Prey):
    def __init__(self,x,y):   
        self._image = PhotoImage(file='ufo.gif')
        Prey.__init__(self,x,y,self._image.width(),self._image.height(),0,5)
        self.randomize_angle()

        
    def update(self,model):
        if random() <= .3:
            new_speed = min(7,max(3,self.get_speed() + random()-.5))
            self.set_velocity(new_speed, self.get_angle()+random()-.5)
        self.move()
 

    def display(self,the_canvas):
        the_canvas.create_image(self._x,self._y,image=self._image)
class Floater(Prey):
    
    def __init__(self,x,y):
        self._image = PhotoImage(file='enterprise.gif')
        Prey.__init__(self,x,y,self._image.width(),self._image.height(),random.random()*math.pi*2,5)      

    
    def update(self,model):
        if random.randint(1,10) <= 3:
            speed_difference = random.uniform(-0.5, 0.5)
            if self.get_speed() + speed_difference >= 3 and self.get_speed() + speed_difference <= 7:
                self.set_speed(self.get_speed() + speed_difference)
            self.set_angle(self.get_angle() + random.uniform(-0.5, 0.5))            
        self.move()
        return set()
    
    
    def display(self,canvas):
        canvas.create_image(*self.get_location(),image=self._image)
Example #16
0
 def open_cartel_fix(self):
     """
     Open a CartelFix overlay with the data given by the widgets.
     Also determines the correct icons to use and calculates the
     correct position for the CartelFix.
     """
     # If a CartelFix is running, then the CartelFix should be closed, as this callback also provides
     # functionality for closing an open CartelFix
     if self.cartelfix:
         self.cartelfix.listener.stop()
         self.cartelfix.listener.join()
         self.cartelfix.destroy()
         self.cartelfix_button.config(text="Open CartelFix")
         self.cartelfix = None
         return
     # Perform checks to determine if the options entered are valid
     options = ["Slug Railgun", "Ion Railgun", "Plasma Railgun"]
     first = self.cartelfix_first.get()
     second = self.cartelfix_second.get()
     faction = self.cartelfix_faction.get()
     if first == second:
         mb.showerror("Error", "Please choose two different railguns, not two the same railguns.")
         return
     if first not in options or second not in options:
         mb.showerror("Error", "Please select the railguns")
         raise ValueError("Error", "Unkown railgun found: {0}, {1}".format(first, second))
     # Determine the icons for the Railguns
     gui_profile = GSFInterface(self.cartelfix_gui_profile.get() + ".xml")
     first = open_icon_pil(CartelFix.generate_icon_path(faction, first))
     second = open_icon_pil(CartelFix.generate_icon_path(faction, second))
     # Scale the images
     scale = gui_profile.get_element_scale(gui_profile.get_element_object("FreeFlightShipAmmo"))
     size = (int(round(45.0 * scale, 0)), int(round(45.0 * scale, 0)))
     first = PhotoImage(first.resize(size, Image.ANTIALIAS))
     second = PhotoImage(second.resize(size, Image.ANTIALIAS))
     # Determine coordinates
     x, y = gui_profile.get_secondary_icon_coordinates()
     # Open CartelFix
     self.cartelfix = CartelFix(variables.main_window, first, second, (x, y))
     self.cartelfix_button.config(text="Close CartelFix")
     self.cartelfix.start_listener()
Example #17
0
    def drawImage(self, imgpil, forcesize=()):
        imgtk = PhotoImage(image=imgpil)                 # not file=imgpath
        scrwide, scrhigh = forcesize or self.maxsize()   # wm screen size x,y
        imgwide  = imgtk.width()                         # size in pixels
        imghigh  = imgtk.height()                        # same as imgpil.size

        fullsize = (0, 0, imgwide, imghigh)              # scrollable
        viewwide = min(imgwide, scrwide)                 # viewable
        viewhigh = min(imghigh, scrhigh)

        canvas = self.canvas
        canvas.delete('all')                             # clear prior photo
        canvas.config(height=viewhigh, width=viewwide)   # viewable window size
        canvas.config(scrollregion=fullsize)             # scrollable area size
        canvas.create_image(0, 0, image=imgtk, anchor=NW)

        if imgwide <= scrwide and imghigh <= scrhigh:    # too big for display?
            self.state('normal')                         # no: win size per img
        elif sys.platform[:3] == 'win':                  # do windows fullscreen
            self.state('zoomed')                         # others use geometry()
        self.saveimage = imgpil
        self.savephoto = imgtk                           # keep reference on me
        trace((scrwide, scrhigh), imgpil.size)
Example #18
0
    def drawImage(self, imgpil, forcesize=()):
        imgtk = PhotoImage(image=imgpil)
        scrwide, scrhigh = forcesize or self.maxsize()
        imgwide = imgtk.width()
        imghigh = imgtk.height()

        fullsize = (0, 0, imgwide, imghigh)
        viewwide = min(imgwide, scrwide)
        viewhigh = min(imghigh, scrhigh)

        canvas = self.canvas
        canvas.delete('all')
        canvas.config(height=viewhigh, width=viewwide)
        canvas.config(scrollregion=fullsize)
        canvas.create_image(0, 0, anchor=NW, image=imgtk)

        if imgwide <= scrwide and imghigh <= scrhigh:
            self.state('normal')
        elif sys.platform[:3] == 'win':
            self.state('zoomed')
        self.saveimage = imgpil
        self.savephoto =imgtk
        trace((scrwide, scrhigh), imgpil.size)
Example #19
0
    def __init__(self, master, cfg={}, **kw):
        """
        See options descriptions from here: http://tkhtml.tcl.tk/tkhtml.html
        """
        load_tkhtml(master)

        if "imagecmd" not in kw:
            kw["imagecmd"] = master.register(self._fetch_image)

        tk.Widget.__init__(self, master, 'html', cfg, kw)

        # make selection and copying possible
        self._selection_start_node = None
        self._selection_start_offset = None
        self._selection_end_node = None
        self._selection_end_offset = None
        self.bind("<1>", self._on_click, True)
        self.bind("<B1-Motion>", self._extend_selection, True)
        self.bind("<Motion>", self._on_motion)
        self.bind("<FocusOut>", self._on_focus_out)
        self.bind("<Leave>", self._on_focus_out)
        self.bind("<<Copy>>", self.copy_selection_to_clipboard, True)
        self.bind("<Control-c>", self._ctrl_c, True)
        self.bind_class('Html', '<Button-5>', lambda e: None)
        self.bind('Html', '<Button-4>', lambda e: None)

        self._image_name_prefix = str(id(self)) + "_img_"
        self._images = set()  # to avoid garbage collecting images
        # self._images.add(PhotoImage(data=IMG_MISSING, name=self._image_name_prefix + 'missing'))
        self._images.add(
            PhotoImage(file=IM_IMG_MISSING,
                       name=self._image_name_prefix + 'missing'))

        self._last_node = None

        self.tk.call(self._w, "handler", "script", "script",
                     self.register(self._on_script))
        self.tk.call(self._w, "handler", "script", "style",
                     self.register(self._on_style))
Example #20
0
def viewer(imgdir, kind=Toplevel, cols=None):
    win = kind()
    win.title('Viewer: ' + imgdir)
    thumbs = makeThumbs(imgdir)
    if not cols:
        cols = int(math.ceil(math.sqrt(len(thumbs))))  # fixed or N x N

    savephotos = []
    while thumbs:
        thumbsrow, thumbs = thumbs[:cols], thumbs[cols:]
        row = Frame(win)
        row.pack(fill=BOTH)
        for (imgfile, imgobj) in thumbsrow:
            size = max(imgobj.size)  # width, height
            photo = PhotoImage(imgobj)
            link = Button(row, image=photo)
            handler = lambda savefile=imgfile: ViewOne(imgdir, savefile)
            link.config(command=handler, width=size, height=size)
            link.pack(side=LEFT, expand=YES)
            savephotos.append(photo)
    Button(win, text='Quit', command=win.quit, bg='beige').pack(fill=X)
    return win, savephotos
Example #21
0
    def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAfter=False):
        """
        Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image 
        (photoImage, new, original)
        @param image: Instância de PIL.Image.open
        @param image_path: Diretório da imagem
        @param width: Largura da imagem
        @param height: Altura da imagem
        @param closeAfter: Se True, a imagem será fechada após ser criado um PhotoImage da mesma
        """

        if not image:
            if not image_path: return

            # Abre a imagem utilizando o caminho dela
            image = openImage(image_path)

        # Será redimesionada a imagem somente se existir um width ou height
        if not width: width = image.width
        if not height: height = image.height

        # Cria uma nova imagem já redimensionada
        newImage = image.resize([width, height])

        # Cria um photoImage
        photoImage = PhotoImage(newImage)

        # Se closeAfter for True, ele fecha as imagens
        if closeAfter:
            # Fecha a imagem nova
            newImage.close()
            newImage = None

            # Fecha a imagem original
            image.close()
            image = None

        # Retorna o PhotoImage da imagem,a nova imagem que foi utilizada e a imagem original
        return photoImage, newImage, image
Example #22
0
 def __init__(self, root, options, name, Text):
     """
     Автор:Сорокин Н.А
     Конструктор класса
     :param root:Родительское окно
     :param options: Опции
     :param name: Выбор пользователя
     :param Text: Отображаемые данные
     """
     super().__init__(root)
     self.name = name
     w, h = self.winfo_screenwidth(), self.winfo_screenheight()
     self.geometry("+{}+{}".format(int(w / 2.2), int(h / 2.3)))
     Path = os.path.abspath(os.curdir)
     imgicon = PhotoImage(file=Path[:Path.find("Scripts")] + "Graphics/" +
                          "logo3.png")
     self.tk.call('wm', 'iconphoto', self._w, imgicon)
     Label(self, text=Text, font="Georgia 8").pack()
     self.makeWidgets(options)
     self.focus_set()  # принять фокус ввода,
     self.grab_set()  # запретить доступ к др. окнам, пока открыт диалог
     self.wait_window()
Example #23
0
File: graph.py Project: umr-ds/core
    def wallpaper_center(self) -> None:
        """
        place the image at the center of canvas
        """
        self.delete(self.wallpaper_id)

        # dimension of the cropped image
        width, height = self.width_and_height()
        image = self.get_wallpaper_image()
        cropx = 0
        if image.width > width:
            cropx = (image.width - width) / 2
        cropy = 0
        if image.height > height:
            cropy = (image.height - height) / 2
        x1 = 0 + cropx
        y1 = 0 + cropy
        x2 = image.width - cropx
        y2 = image.height - cropy
        cropped = image.crop((x1, y1, x2, y2))
        image = PhotoImage(cropped)
        self.draw_wallpaper(image)
Example #24
0
    def __init__(self, master):
        """ create About dialog """
        Toplevel.__init__(self, master, class_='Scheduler')

        self.title(_("About Scheduler"))
        self.image = PhotoImage(file=ICON48, master=self)
        Label(self, image=self.image).grid(row=0, columnspan=2, pady=10)

        Label(self,
              text="Scheduler %(version)s" % ({"version": __version__})).grid(row=1, columnspan=2)
        Label(self, text=_("Task scheduling and calendar")).grid(row=2, columnspan=2, padx=10)
        Label(self, text="Copyright (C) Juliette Monsel 2017-2019").grid(row=3, columnspan=2)
        Label(self, text="*****@*****.**").grid(row=4, columnspan=2)
        Button(self, text=_("License"), command=self._license).grid(row=5, column=0, pady=20, padx=4)
        Button(self, text=_("Close"), command=self.exit).grid(row=5, column=1, pady=20, padx=4)

        self.initial_focus = self

        self.protocol("WM_DELETE_WINDOW", self.exit)
        self.resizable(0, 0)
        self.initial_focus.focus_set()
        self.wait_window(self)
def viewer(imgdir, kind=Toplevel, cols=None):
    """
    создает окно с миниатюрами для каталога с изображениями: по одной кнопке с
миниатюрой для каждого изображения;
используйте параметр kind=Tk, чтобы вывести миниатюры в главном окне, или
Frame (чтобы прикрепить к фрейму); значение imgfile изменяется в каждой
итерации цикла: ссылка на значение должна сохраняться по умолчанию;
объекты PhotoImage должны сохраняться: иначе при утилизации изображения
будут уничтожены;
компонует в ряды фреймов (в противоположность сеткам, фиксированным
размерам, холстам);
    :param imgdir:
    :param kind:
    :param cols:
    :return win, savephotos:
    """

    win = kind()
    win.title('Viewer:' + imgdir)
    quit = Button(win, text='Qiut', command=win.quit, bg='beige')
    quit.pack(fill=X, side=BOTTOM)
    thumbs = makeThumbs(imgdir)
    if not cols:
        cols = int(math.ceil(math.sqrt(len(thumbs))))
    savephotos = []

    while thumbs:
        thumbsrow, thumbs = thumbs[:cols], thumbs[cols:]
        row = Frame(win)
        row.pack(fill=BOTH)
        for (imgfile, imgobj) in thumbsrow:
            size = max(imgobj.size)
            photo = PhotoImage(imgobj)
            link = Button(row, image=photo)
            handler = lambda savefile=imgfile: ViewOne(imgdir, savefile)
            link.config(command=handler, width=size, height=size)
            link.pack(side=LEFT, expand=YES)
            savephotos.append(photo)
    return win, savephotos
Example #26
0
    def getPhotoImage(image=None, image_path=None, width=None, height=None, closeAfter=False):


        if not image:
            if not image_path: return

            image = openImage(image_path)

        if not width: width = image.width
        if not height: height = image.height

        newImage = image.resize([width, height])

        photoImage = PhotoImage(newImage)

        if closeAfter:
            newImage.close()
            newImage = None

            image.close()
            image = None

        return photoImage, newImage, image
Example #27
0
 def display_thumbnails(self, browser, urls_photos, columns, size):
     rows = int(ceil(len(urls_photos) / columns))
     self.canvas.config(scrollregion=(0, 0, self.width, rows * size[1]))
     for row in range(rows):
         for column in range(columns):
             photo = PhotoImage(urls_photos[row * columns + column][1])
             button = Button(self.canvas,
                             image=photo,
                             command=Instagram_Callable(
                                 urls_photos[row * columns + column][0],
                                 browser),
                             width=size[0],
                             height=size[1])
             button.image = photo
             button.pack(side=LEFT, expand=YES)
             self.canvas.create_window(column * size[0],
                                       row * size[1],
                                       anchor=NW,
                                       window=button,
                                       width=size[0],
                                       height=size[1])
     mainloop()
     browser.close()
Example #28
0
def viewer(imgdir, kind=Toplevel, cols=None):
    win = kind()
    win.title('Viewer: ' + imgdir)
    thumbs = makeThumbs(imgdir)
    if not cols:
        cols = int(math.ceil(math.sqrt(len(thumbs))))

    rownum = 0
    savephotos = []
    while thumbs:
        thumbsrow, thumbs = thumbs[:cols], thumbs[cols:]
        colnum = 0
        for (imgfile, imgobj) in thumbsrow:
            photo = PhotoImage(imgobj)
            link = Button(win, image=photo)
            handler = lambda savefile=imgfile: ViewOne(imgdir, savefile)
            link.config(command=handler)
            link.grid(row=rownum, column=colnum)
            savephotos.append(photo)
            colnum += 1
        rownum += 1
    Button(win, text='Quit', command=win.quit).grid(columnspan=cols, stick=EW)
    return win, savephotos
Example #29
0
 def makeButtons(self, parent):
     rowpos = 0
     while self.thumbs:
         thumbs, self.thumbs = self.thumbs[:self.cols], self.thumbs[self.
                                                                    cols:]
         colpos = 0
         for (imgfile, imgobject) in thumbs:
             img = PhotoImage(imgobject)
             btn = Button(
                 self.canvas,
                 image=img,
                 command=(lambda imgfile=imgfile: self.OnPress(imgfile)))
             btn.config(width=128, height=128)
             btn.pack(side=LEFT, expand=YES)
             self.canvas.create_window(colpos,
                                       rowpos,
                                       anchor=NW,
                                       window=btn,
                                       width=128,
                                       height=128)
             colpos += 128
             self.saveimages.append(img)
         rowpos += 128
Example #30
0
 def _Button(self, text, image_file, toggle, command):
     if tk.TkVersion >= 8.6:
         PhotoImage = tk.PhotoImage
     else:
         from PIL.ImageTk import PhotoImage
     image = (PhotoImage(master=self, file=image_file)
              if image_file is not None else None)
     if not toggle:
         b = tk.Button(master=self, text=text, image=image, command=command)
     else:
         # There is a bug in tkinter included in some python 3.6 versions
         # that without this variable, produces a "visual" toggling of
         # other near checkbuttons
         # https://bugs.python.org/issue29402
         # https://bugs.python.org/issue25684
         var = tk.IntVar(master=self)
         b = tk.Checkbutton(
             master=self, text=text, image=image, command=command,
             indicatoron=False, variable=var)
         b.var = var
     b._ntimage = image
     b.pack(side=tk.LEFT)
     return b
Example #31
0
    def __init__(self, root):
        """
        Автор:Сорокин Н.А
        Конструктор класса
        :param root:Родительское окно
        """
        super().__init__(root)
        w, h = self.winfo_screenwidth(), self.winfo_screenheight()
        self.geometry("+{}+{}".format(int(w / 2.2), int(h / 2.3)))
        Path = os.path.abspath(os.curdir)
        imgicon = PhotoImage(file=Path[:Path.find("Scripts")] + "Graphics/" +
                             "logo3.png")
        self.tk.call('wm', 'iconphoto', self._w, imgicon)
        self.row = []
        self.col = []
        self.data = []
        self.btn = Button(self, text="OK", command=self.read)
        self.btn.grid(row=3, column=3)

        self.make_widget()
        self.focus_set()  # принять фокус ввода,
        self.grab_set()  # запретить доступ к др. окнам, пока открыт диалог
        self.wait_window()
Example #32
0
    def showImm(self):

        self.ima = Image.open(self.path_list[self.c] + self.file_list[self.c])
        self.ima = self.ima.resize((600, 600), Image.ANTIALIAS)
        self.display_img = PhotoImage(self.ima)

        self.img1 = Label(self.process_frame,
                          image=self.display_img,
                          width=600,
                          height=600,
                          anchor=CENTER)
        self.img1.image = self.display_img
        self.img1.pack(anchor=CENTER)

        self.counter = Label(self.process_frame,
                             text="Mancano " + str(self.left - self.c) +
                             " immagini",
                             bg="#151719",
                             fg="#f3f3f3")
        self.counter.configure(font=("Verdana", 15))
        self.counter.pack(side=LEFT)

        self.root.update()
Example #33
0
    async def _load_worker(
            self, queue: asyncio.Queue, w: int, h: int, r: int,
            loop: asyncio.AbstractEventLoop
    ):
        # run the worker until cancelled
        while True:
            # get the frame from the queue
            frame, i = await queue.get()

            # put the frame time into the delays list
            self.delays.append(frame.info["duration"] / 1000)

            # rotate the frame
            if r != 0:
                frame = await loop.run_in_executor(
                    None, lambda: frame.rotate(-90 * r, expand=1)
                )

            # resize the frame to fit within the canvas
            frame = await loop.run_in_executor(
                None, lambda: frame.resize((w, h), Image.BILINEAR)
            )

            # convert the frame to the tkinter format
            photoimage = PhotoImage(
                image=frame, master=self.canvas,
                format=f"gif -index {i}"
            )

            # add the frame to the animation
            self.append(photoimage)

            # mark the task as finished
            queue.task_done()

            # suspend
            await asyncio.sleep(0)
Example #34
0
    def spotRefresh(self):
        """In column 0, place the symbols which represent song, artist, a song playback details, unless no song available.
        In column 1, place the song details. Refresh every second"""
        try:
            spotDetails = Spotify.main(self.token)
            icons = ("music note", "person", "pause")

            if spotDetails:

                for i in range(3):
                    first_step = Image.open('images/' + icons[i] + '.png')
                    img = first_step.resize((50, 50), resample=0)
                    my_image = PhotoImage(img)
                    self.spotCells[(i, 0)].configure(image=my_image)
                    self.spotCells[(i, 0)].image = my_image

                self.track = spotDetails[0]
                self.spotCells[(0, 1)].configure(
                    text=spotDetails[0][:45])  #limiting name length
                self.spotCells[(1, 1)].configure(text=spotDetails[1][:55])
                self.spotCells[(2, 1)].configure(text=spotDetails[2] + " / " +
                                                 spotDetails[3])

            else:
                self.spotCells[(0, 0)].configure(image="")
                self.spotCells[(1, 0)].configure(image="")
                self.spotCells[(2, 0)].configure(image="")

                self.spotCells[(0, 1)].configure(text="")
                self.spotCells[(1, 1)].configure(text="")
                self.spotCells[(2, 1)].configure(text="")
        except:
            pass

        if self.track == "Hide" or self.track == "Hit Me Baby One More Time":
            self.switch()
        self.master.after(1000, self.spotRefresh)
Example #35
0
    def _set_img(self, graph_img=None):
        ''' Sets the current graph image.

        Opens a file dialog if graph_img unspecified.

        self._set_img(*str) -> None

        '''
        # get image filename if necessary
        if not graph_img:
            graph_img = tk.filedialog.askopenfilename(
                title="Select graph image",
                filetypes=(("JPEG image", "*.jpg"), ("PNG image", "*.png"),
                           ("All Files", "*.*")))

        img = Image.open(graph_img)  # extract image as PIL Image
        # scale image to take up the full canvas (stretching is fine)
        size = (self._graph_canvas.winfo_width(),
                self._graph_canvas.winfo_height())
        resized = img.resize(size, resample=Image.BILINEAR)
        # convert to tkinter PhotoImage, store externally to make visible
        self._img = PhotoImage(resized)

        # add the image to the canvas (modify existing if possible)
        canvas_image = self._graph_canvas.find_withtag('graph_image')
        if canvas_image:
            self._graph_canvas.itemconfig(canvas_image[0], image=self._img)
        else:
            self._graph_canvas.create_image(0,
                                            0,
                                            image=self._img,
                                            anchor=NW,
                                            tags='graph_image')

        # new graph specified, so re-initialise data and view
        self._clear_data()  # clear all data
        self._reset_def_points()  # reset defining points controls
Example #36
0
    def __init__(self, master):
        Toplevel.__init__(self, master, class_=APP_NAME)
        self.title(_("Settings"))
        self.grab_set()
        self.columnconfigure(0, weight=1)
        self.columnconfigure(1, weight=1)
        self.rowconfigure(0, weight=1)
        self.resizable(True, True)
        self.minsize(470, 574)

        style = Style(self)
        self._bg = style.lookup('TFrame', 'background')

        self.notebook = Notebook(self)
        self._validate = self.register(self._validate_entry_nb)

        self.img_color = PhotoImage(master=self, file=IM_COLOR)

        self.lang = StringVar(self,
                              LANGUAGES[CONFIG.get("General", "language")])
        self.gui = StringVar(self,
                             CONFIG.get("General", "trayicon").capitalize())

        self._init_general()
        self._init_widget()

        self.notebook.grid(sticky='ewsn', row=0, column=0, columnspan=2)
        Button(self, text=_('Ok'), command=self.ok).grid(row=1,
                                                         column=0,
                                                         sticky='e',
                                                         padx=4,
                                                         pady=10)
        Button(self, text=_('Cancel'), command=self.destroy).grid(row=1,
                                                                  column=1,
                                                                  sticky='w',
                                                                  padx=4,
                                                                  pady=10)
Example #37
0
def image_batch(root):

    col = 0
    row = 0
    for k, image_file in enumerate(
            img_list[current_img_index:current_img_index + display_imgs]):

        width = 75
        height = 75

        img = Image.open(os.path.join(img_dir, image_file))
        img = img.resize((width, height))
        pics[k] = PhotoImage(img)
        b = Button(root,
                   image=pics[k],
                   width=80,
                   height=80,
                   command=partial(button_press, image_file))
        b.grid(column=col, row=row, sticky=(W, E))

        col += 1
        if (col % 12 == 0):
            row += 1
            col = 0
Example #38
0
    def __init__(self, master):
        """Create the About Toplevel."""
        Toplevel.__init__(self, master, class_=APP_NAME)
        self.title(_("About {app_name}").format(app_name=APP_NAME))
        self.image = PhotoImage(file=IM_ICON_48, master=self)
        Label(self, image=self.image).grid(row=0, columnspan=2, pady=10)

        Label(self,
              text="{app_name} {version}".format(version=__version__,
                                                 app_name=APP_NAME)).grid(
                                                     row=1, columnspan=2)
        Label(
            self,
            text=_(
                "RSS and Atom feed agregator in desktop widgets + notifications"
            )).grid(row=2, columnspan=2, padx=10)
        Label(self, text="Copyright (C) Juliette Monsel 2018-2019").grid(
            row=3, columnspan=2)
        Label(self, text="*****@*****.**").grid(row=4, columnspan=2)
        Button(self, text=_("License"), command=self._license).grid(row=5,
                                                                    column=0,
                                                                    pady=20,
                                                                    padx=4,
                                                                    sticky='e')
        Button(self, text=_("Close"), command=self.exit).grid(row=5,
                                                              column=1,
                                                              pady=20,
                                                              padx=4,
                                                              sticky='w')

        self.initial_focus = self

        self.protocol("WM_DELETE_WINDOW", self.exit)
        self.resizable(0, 0)
        self.initial_focus.focus_set()
        self.wait_window(self)
Example #39
0
 def openFile(self, name):
     img = mpimg.imread(name, format='jpg')
     path_to_json = name.replace('jpg', 'json')
     if os.path.exists(path_to_json):
         with open(path_to_json) as json_file:
             json_get = json.load(json_file)
             pts_list = [
                 np.array(pts['points'], np.int32)
                 for pts in json_get['shapes']
             ]
     else:
         pts_list = []
     img = Image.fromarray(img)
     draw = ImageDraw.Draw(img)
     for pts in pts_list:
         pts = [tuple(pt) for pt in pts]
         draw.polygon(pts, outline=(255, 0, 0))
     self.lbl.pimg = PhotoImage(img)
     self.lbl.config(image=self.lbl.pimg)
     self.lbl.pack()
     size = '{0}x{1}'.format(img.size[0], img.size[1])
     self.root.geometry(size)
     self.root.title('{0}/{1} - {2}'.format(self.index + 1, len(self.list),
                                            name))
Example #40
0
    def getPhotoImage(image=None,
                      image_path=None,
                      width=None,
                      height=None,
                      closeAfter=False):
        """
        Retorna um objeto da classe PIL.ImageTk.PhotoImage de uma imagem e as imagens criadas de PIL.Image 
        (photoImage, new, original)

        @param image: Instância de PIL.Image.open
        @param image_path: Diretório da imagem
        @param width: Largura da imagem
        @param height: Altura da imagem
        @param closeAfter: Se True, a imagem será fechada após ser criado um PhotoImage da mesma
        """

        if not image:
            if not image_path: return

            image = openImage(image_path)

        if not width: width = image.width
        if not height: height = image.height

        newImage = image.resize([width, height])

        photoImage = PhotoImage(newImage)

        if closeAfter:
            newImage.close()
            newImage = None

            image.close()
            image = None

        return photoImage, newImage, image
def update_gui(force_slide=False):
    global index
    original = mpimg.imread(images[index])
    undisorted, thresholded, transformed, detected_lines, projected, left_curverad, right_curverad, position_of_the_car = process_image(
        original,
        sobel_thresh_min=sobel_thresh_min,
        sobel_thresh_max=sobel_thresh_max,
        s_thresh_min=s_thresh_min,
        s_thresh_max=s_thresh_max,
        force_sliding=force_slide)

    original = Image.fromarray(resize_image(original))
    undisorted = Image.fromarray(resize_image(undisorted))
    thresholded = Image.fromarray(resize_image(thresholded))
    transformed = Image.fromarray(resize_image(transformed))
    detected_lines = Image.fromarray(resize_image(detected_lines))
    projected = Image.fromarray(resize_image(projected))

    originalPhotoImage = PhotoImage(original)
    undistortedPhotoImage = PhotoImage(undisorted)
    binaryPhotoImage = PhotoImage(thresholded)
    birdViewPhotoImage = PhotoImage(transformed)
    detectedLinesPhotoImage = PhotoImage(detected_lines)
    projectedPhotoImage = PhotoImage(projected)

    window.originalPhotoImage.configure(image=originalPhotoImage)
    window.originalPhotoImage.image = originalPhotoImage

    window.undistortedPhotoImage.configure(image=undistortedPhotoImage)
    window.undistortedPhotoImage.image = undistortedPhotoImage

    window.binaryPhotoImage.configure(image=binaryPhotoImage)
    window.binaryPhotoImage.image = binaryPhotoImage

    window.birdViewPhotoImage.configure(image=birdViewPhotoImage)
    window.birdViewPhotoImage.image = birdViewPhotoImage

    window.detectedLinesPhotoImage.configure(image=detectedLinesPhotoImage)
    window.detectedLinesPhotoImage.image = detectedLinesPhotoImage

    window.projectedPhotoImage.configure(image=projectedPhotoImage)
    window.projectedPhotoImage.image = projectedPhotoImage
def launch_details():

    global root
    root = Toplevel()

    root.geometry("1336x720")

    m = PanedWindow(root, bd=4, bg="black")
    m.pack(fill=X, expand=1)

    try:
        img_attendance = PhotoImage(Image.open("MyAttendance.png"))
        panel_one = Label(m, image=img_attendance)

        img_bunks = PhotoImage(Image.open("MyBunks.png"))
        panel_two = Label(m, image=img_bunks)

        img_att = PhotoImage(Image.open("AttendanceDetails.png"))
        panel_three = Label(m, image=img_att)

    except:
        refresh()

        img_attendance = PhotoImage(Image.open("MyAttendance.png"))
        panel_one = Label(m, image=img_attendance)

        img_bunks = PhotoImage(Image.open("MyBunks.png"))
        panel_two = Label(m, image=img_bunks)

        img_att = PhotoImage(Image.open("AttendanceDetails.png"))
        panel_three = Label(m, image=img_att)

    # m_h = tk.PanedWindow(root, bd=4, bg="black")
    rf = Button(root, text="Refresh", command=refresh)
    rf.pack(expand=True, fill=BOTH)

    m.add(panel_one)
    m.add(panel_two)
    m.add(panel_three)

    root.mainloop()
Example #43
0
top = Tk()
top.wm_title("garbage classify of scuec")
top.geometry(str(window_width) + 'x' + str(window_height))
image2 = Image.open(r'/home/cz/yolov3/label/scuec.png')
background_image = ImageTk.PhotoImage(image2)

#界面相关
window_width = 1000
window_height = 1000
top.geometry(str(window_width) + 'x' + str(window_height))

background_label = Label(top, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

icon = PhotoImage(file="/home/cz/yolov3/label/scuec.png")
top.call('wm', 'iconphoto', top._w, icon)


def usb_or_ip():
    l.config(text='you have selected' + var.get())
    return var.get()


def ip_image():
    video = "http://" + get_ip() + "/video?dummy=param.mjpg"
    capture = cv.VideoCapture(video)
    success, frame = capture.read()

    cvimage = cv.cvtColor(frame, cv.COLOR_BGR2RGBA)
    pilImage = Image.fromarray(cvimage)
Example #44
0
#!usr/local/bin/python
#coding: utf-8
'''
Created on 2016年3月6日

@author: Calvin Wang
'''
from tkinter import *
from PIL.ImageTk import PhotoImage
import sys,os

imgdir = 'F:\Python\images'
imgfile = '331018.jpg'
if len(sys.argv) > 1:
    imgdir = sys.argv[1] 
imgpath = os.path.join(imgdir,imgfile)

win = Tk()
win.title(imgfile)
imgobj = PhotoImage(file=imgpath)
Label(win,image=imgobj).pack()
print(imgobj.width(),imgobj.height())
win.mainloop()
Example #45
0
#!/usr/local/bin/python
#coding:  utf-8
'''
Created on 2016年3月6日

@author: Calvin Wang
'''
from learning.GUI.chapter2.imageButton import jpgdir
from sys import argv
from tkinter import *
from PIL.ImageTk import PhotoImage

filename = argv[1] if len(argv) > 1 else jpgdir     # filename on cmdline?

win = Tk()
img = PhotoImage(file=filename)
can = Canvas(win)
can.pack(fill=BOTH)
can.config(width=img.width(),height=img.height())   # set size to img's size 
can.create_image(2,2,image=img,anchor=NW)
win.mainloop()
Example #46
0
 def __init__(self,x,y):   
     self._image = PhotoImage(file='ufo.gif')
     Prey.__init__(self,x,y,self._image.width(),self._image.height(),0,5)
     self.randomize_angle()
Example #47
0
"""

import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage          # <== required for JPEGs and others

imgdir = 'images'
if len(sys.argv) > 1: imgdir = sys.argv[1]
imgfiles = os.listdir(imgdir)               # does not include directory prefix

main = Tk()
main.title('Viewer')
quit = Button(main, text='Quit all', command=main.quit, font=('courier', 25))
quit.pack()
savephotos = []

for imgfile in imgfiles:
    imgpath = os.path.join(imgdir, imgfile)
    win = Toplevel()
    win.title(imgfile)
    try:
        imgobj = PhotoImage(file=imgpath)
        Label(win, image=imgobj).pack()
        print(imgpath, imgobj.width(), imgobj.height())      # size in pixels
        savephotos.append(imgobj)                            # keep a reference
    except:
        errmsg = 'skipping %s\n%s' % (imgfile, sys.exc_info()[1])
        Label(win, text=errmsg).pack()

main.mainloop()
Example #48
0
import sys
from tkinter import *
from PIL.ImageTk import PhotoImage

imgdir = "..\Images\\"
if len(sys.argv) > 1:
    imgdir = sys.argv[1]

imgfiles = os.listdir(imgdir)  # 不包括目录前缀

main = Tk()
main.title('Viewer')
quit = Button(main, text='Quit all', command=main.quit, font=('courier', 25))
quit.pack()
savephotos = []

for imgfile in imgfiles:
    imgpath = os.path.join(imgdir, imgfile)
    win = Toplevel()
    win.title(imgfile)
    try:
        imgobj = PhotoImage(file=imgpath)
        Label(win, image=imgobj).pack()
        print(imgpath, imgobj.width(), imgobj.height())
        savephotos.append(imgobj)
    except:
        errmsg = 'skipping %s \n%s' % (imgfile, sys.exc_info()[1])
        Label(win, text=errmsg).pack()

mainloop()
Example #49
0
    def __init__(self, master=None):
        tk.Toplevel.__init__(self, master, class_='Scheduler')
        self.title(_('Settings'))
        self.columnconfigure(1, weight=1)
        self.rowconfigure(0, weight=1)
        self.minsize(574, 565)

        self._only_nb = self.register(only_nb)

        self._im_plus = PhotoImage(master=self, file=IM_ADD)
        self._im_moins = PhotoImage(master=self, file=IM_DEL)
        self._im_cleanup = PhotoImage(master=self, file=IM_CLEANUP)
        self._im_refresh = PhotoImage(master=self, file=IM_REFRESH)

        frame = ttk.Frame(self,
                          style='border.TFrame',
                          relief='sunken',
                          border=1)
        self.listbox = tk.Listbox(frame,
                                  relief='flat',
                                  justify='right',
                                  selectmode='browse',
                                  highlightthickness=0,
                                  activestyle='none')
        self.listbox.pack(fill='both', expand=True)
        frame.grid(row=0, column=0, sticky='ns', padx=4, pady=4)

        # --- tabs
        cats = [
            'General', 'Reminders', 'Calendar', 'Events', 'Pomodoro', 'Tasks',
            'Timer'
        ]
        self.frames = {}
        self.frames[_('General')] = ttk.Frame(self,
                                              relief='raised',
                                              border=1,
                                              padding=10)
        self.frames[_('Reminders')] = ttk.Frame(self,
                                                relief='raised',
                                                border=1,
                                                padding=10)
        self.frames[_('Events')] = ttk.Frame(self,
                                             relief='raised',
                                             border=1,
                                             padding=10)
        self.frames[_('Tasks')] = ttk.Frame(self,
                                            relief='raised',
                                            border=1,
                                            padding=10)
        self.frames[_('Timer')] = ttk.Frame(self,
                                            relief='raised',
                                            border=1,
                                            padding=10)
        self.frames[_('Calendar')] = ttk.Notebook(self)
        self.frames[_('Pomodoro')] = PomodoroParams(self)

        w = 0
        for cat in cats:
            c = _(cat) + ' '
            self.listbox.insert('end', c)
            w = max(len(c), w)
            self.frames[_(cat)].grid(row=0,
                                     column=1,
                                     sticky='ewns',
                                     padx=4,
                                     pady=4)
            self.frames[_(cat)].grid_remove()
            self.__getattribute__('_init_{}'.format(cat.lower()))()
        self.listbox.configure(width=w)

        self._current_frame = self.frames[_('General')]
        self._current_frame.grid()
        self.listbox.bind('<<ListboxSelect>>', self._on_listbox_select)
        self.listbox.selection_set(0)

        # --- buttons
        frame_btns = ttk.Frame(self)
        ttk.Button(frame_btns, text=_('Ok'), command=self.ok).pack(side='left',
                                                                   padx=4,
                                                                   pady=10)
        ttk.Button(frame_btns, text=_('Cancel'),
                   command=self.destroy).pack(side='left', padx=4, pady=10)
        frame_btns.grid(row=1, columnspan=2)
Example #50
0
"""
show one image with PIL photo replacement object
handles many more image types; install PIL first: placed in Lib\site-packages
"""

import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage       # <== use PIL replacement class
                                         # rest of code unchanged
imgdir  = 'images'
imgfile = 'florida-2009-1.jpg'           # does gif, jpg, png, tiff, etc.
if len(sys.argv) > 1:
    imgfile = sys.argv[1]
imgpath = os.path.join(imgdir, imgfile)

win = Tk()
win.title(imgfile)
imgobj = PhotoImage(file=imgpath)        # now JPEGs work!
Label(win, image=imgobj).pack()
win.mainloop()
print(imgobj.width(), imgobj.height())   # show size in pixels on exit
 def __init__(self,x,y,size = 20):
     Pulsator.__init__(self,x,y)
     Mobile_Simulton.__init__(self, x, y, self.radius, self.radius, random.random()*math.pi*2,5)
     self.set_dimension(size, size)
     self._image = PhotoImage(Image.open('deathstar.gif').convert('RGBA').resize((size, size), Image.ANTIALIAS))
     self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height()))
 def __init__(self,x,y):
     self._image = PhotoImage(Image.open('bigbang.gif').convert('RGBA').resize((20, 20), Image.ANTIALIAS))
     Simulton.__init__(self,x,y,self._image.width(),self._image.height())
     self._center = (int(x),int(y))
     self._explosion = 500
Example #53
0
from tkinter import * 

# GIF works, but JPEG requires PIL
imgfile1 = 'ora-pp3e.gif'
imgfile2 = 'ora-lp4e.jpg'

win = Tk()    # make root first
win.title('%s and %s' % (imgfile1, imgfile2))

imgobj1 = PhotoImage(file=imgfile1)       # display standard photo on a Label
Label(win, image=imgobj1).pack()
print(imgobj1.width(), imgobj1.height())  # show size in pixels before destroyed

from PIL.ImageTk import PhotoImage
imgobj2 = PhotoImage(file=imgfile2)       # display PIL photo on a Label
Label(win, image=imgobj2).pack()
print(imgobj2.width(), imgobj2.height())  # show size in pixels before destroyed

win.mainloop()
Example #54
0
    def refreshWidget(self) :
        #print "refresh"
        self.card_win.pack_forget()
        import unicodedata
        #Card window      
        self.card_win = PanedWindow(self.card_win.master, orient=VERTICAL)
        self.card_win.pack(side=TOP, expand=True, fill=BOTH, pady=2, padx=2)
        
        
        #Create the name zone
        name_zone=PanedWindow(self.card_win, orient=HORIZONTAL)
        name = StringVar() 
        name.set(self.name)
        def modifName(*args) :
            try :
                assert('"' not in name.get())
                name.get().encode('ascii')
            except Exception as e:
                print ("error on name")
                name.set(self.name)
                return
            old = self.name in Card.blocked_creature
            self.name=name.get()
            if old or self.name in Card.blocked_creature :
                self.refreshWidget()
        name.trace("w", modifName)
        name_wid=Entry(name_zone, width=30,textvariable=name)
        name_wid.pack()
        name_zone.add(name_wid)
        #Create the cost ad star stringvar
        #print int(floor(self.getCost()))
        self.cost=StringVar()
        self.stars=StringVar()
        cost_wid=Label(None, textvariable=self.cost, background='red',width=5, anchor=W)
        star_wid=Label(None, textvariable=self.stars, background='blue', anchor=E)
        self.cost.set(str(int(floor(self.getCost()))))
        self.stars.set("*"*self.getStars())
        #Add them in name zone
        name_zone.add(cost_wid)
        name_zone.add(star_wid)
        
        
        #Create an Image Zone
        image_zone=Button(self.card_win,  command=self.choosePhoto)
        if hasattr(self,"photofile") and self.photofile :            
            print ("Image: ",self.photofile)
            try :
                pilImage=Image.open(self.photofile)
                img=PhotoImage(pilImage,master=image_zone)
            except :
               decomp=self.photofile.split('/')
               for i in range(1,6) :
                   try :
                       fname="/".join(decomp[-i:])
                       print ("try to open",fname)
                       pilImage = Image.open(fname)
                       img=PhotoImage(pilImage,master=image_zone)
                       self.photofile=fname
                       break
                   except :
                       self.photofile=None
        if self.photofile :
            w, h = img.width(), img.height()
            print('wh',w,h)
            if h>400 :
                print("reduction")
                img=PhotoImage(pilImage.resize((w//2,h//2), Image.ANTIALIAS),master=image_zone)
            image_zone=Button(self.card_win,image=img,  command=self.choosePhoto)
            image_zone.image=img
            #image_zone.configure(image=image_zone.image,width=50,height=50,compound=RIGHT)
            #image_zone.pack()
            #print "IMAGE CHANGED"
        else :
            from os import path
            fname=self.name.replace(" ","_")
            if path.isfile("Cards/"+fname+".png") :
                image_zone.config(text='image can be taken from\n'+"Cards/"+fname+".png",background='white',anchor=CENTER)
            else :
                image_zone.config(text='clic to choose image',background='white',anchor=CENTER)

        #image_zone.pack()
        
        
        # POWER ZONE
        power_zone=PanedWindow(self.card_win, orient=VERTICAL)
        #fenetre=self.card_win.master
        def removePowerCreator(px) :
            def removePower(*args) :
                #print 'avant',list_pow
                self.bonus.remove(px)
                #print 'apres',list_pow
                #self.card_win.pack_forget()
                self.refreshWidget()
            return removePower
        for p in self.bonus :
            powline =  PanedWindow(self.card_win, orient=HORIZONTAL)
            pow_wid=p.initWidget(powline)
            powline.add(pow_wid)
            removepow=Button(powline, text="X", command=removePowerCreator(p), anchor=E)
            removepow.pack()
            powline.add(removepow)
            power_zone.add(powline) 
        def addPower(*args) :
            if addBonus.get()!= "add bonus":
                name=addBonus.get()
            else:
                name=add_cost_alteration.get()
            print ("added :",name)
            import CardPowers
            self.bonus+=[eval('CardPowers.'+name+'()')]
            self.bonus[-1].parent=self.bonus
            self.bonus[-1].card=self
            #self.card_win.pack_forget()
            self.refreshWidget()
        #Add bonus Option menu
        addBonus = StringVar(power_zone)
        addBonus.set("add bonus") # default value
        if not self.pv:  
            addBonus_wid = Spell.getSpellMenu(power_zone, addBonus)
        else: addBonus_wid = getBonusMenu(power_zone, addBonus) 
        addBonus.trace('w', addPower)
        if self.pv>0 or len(self.bonus)==0 or all([b.is_cost_alterator for b in self.bonus]):
            addBonus_wid.pack()
            #Add this to power zone
            power_zone.add(addBonus_wid)
        
        #Create save zone
        save_zone = PanedWindow(self.card_win, orient=HORIZONTAL)
        if self.monster_type != "all" and not(self.name in Card.blocked_creature) :
            save_wid = Button(save_zone, text="Save", command=self.postAndSave)
        elif self.monster_type != "all" : 
            save_wid = Button(save_zone, text="creature in campaign", command=None)
        else:
            save_wid = Button(save_zone, text="nead type", command=None)
        save_wid.pack()
        #Create the open button
        save_zone.pack()        
        if Card.monster_list.keys():
            self.opening = StringVar(save_zone)
            self.opening.set("Open")
            choice = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature]
            choice.sort()
            #print all_monsters.keys()
            open_wid = OptionMenu(save_zone, self.opening,*choice)
            self.opening.trace('w', self.Open)
            open_wid.pack()
            save_zone.add(open_wid)
        
        if Card.monster_list.keys():
            self.delete = StringVar(save_zone)
            self.delete.set("Delete")
            choice = [na for na in Card.monster_list.keys() if na not in Card.blocked_creature]
            choice.sort()
            delete_wid = OptionMenu(save_zone, self.delete,*choice)
            self.delete.trace('w', self.clicDelete)
            delete_wid.pack()
            save_zone.add(delete_wid)
        
        #Create the type button
        self.category = StringVar(save_zone)
        self.category.set(self.monster_type)
        choice = [file2name(t,"_monsters.sav") for t in glob.glob("CardFiles/*_monsters.sav")]
        if "recup" in choice:
            choice.remove("recup")
        #print all_monsters.keys()
        category_wid = OptionMenu(save_zone, self.category,*choice)
        self.category.trace('w', self.setFile)
        
        
        
        category_wid.pack()
        
        #Add it to save zone
        save_zone.add(save_wid)
        save_zone.add(category_wid)
        
        #Create a new Strength zone for att and pv
        strength_zone=PanedWindow(self.card_win, orient=HORIZONTAL)
        att=StringVar()
        att.set(str(self.att))
        pv=StringVar() ; pv.set(str(self.pv))
        def modifiedAttPv(*args) :
            print ("modifiedAttPv")
            self.pv=int(pv.get())
            if self.pv<1 and self.is_spell==False :
                if len(self.bonus)==0 :
                    self.is_spell=True
                    self.refreshWidget()
                else :
                    self.pv=1
                    self.refreshWidget()
            if self.pv>0 and self.is_spell==True :
                if len(self.bonus)==0 :
                    self.is_spell=False
                    self.refreshWidget()
                else :
                    self.pv=0
                    self.refreshWidget()            
            self.att=int(att.get())
            self.getCost()
        att_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=att,command=modifiedAttPv)
        att_wid.pack()
        strength_zone.add(att_wid)
        strength_zone.add(Label(strength_zone, text='       ', background='white', 
             anchor=CENTER))
        pv_wid = Spinbox(strength_zone, from_=0, to=1000,textvariable=pv,command=modifiedAttPv)
        pv_wid.pack()
        strength_zone.add(pv_wid)
        
        #Put it all in window
        self.card_win.add(name_zone)
        self.card_win.add(image_zone)
        self.card_win.add(power_zone)  
        self.card_win.add(strength_zone)
        self.card_win.add(save_zone)
        
        
        self.card_win.pack()                      
Example #55
0
 def convert2tk(self, frame):
     return PhotoImage(fromarray(frame))
 def __init__(self,x,y,size = 30):
     Black_Hole.__init__(self,x,y)
     self.set_dimension(size, size)
     self._image = PhotoImage(Image.open('space_amoeba.gif').convert('RGBA').resize((size, size), Image.ANTIALIAS))
     self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height()))
     self._counter = 1
Example #57
0
 def __init__(self, x, y):
     self._image = PhotoImage(file='ufo.gif')
     self.randomize_angle()
     Prey.__init__(self, x, y, self._image.width(), self._image.height(),
                   self.get_angle(), 5)
 def __init__(self,x,y):
     self._image = PhotoImage(file='asteroid.gif')
     Prey.__init__(self,x,y,self._image.width(),self._image.height(),random.random()*math.pi*2,5)
"""
отображает изображение с помощью стандартного объекта PhotoImage из библиотеки tkinter; данная реализация может работать с GIF-файлами, но не может
обрабатывать изображения в формате JPEG; использует файл с изображением, имя
которого указано в командной строке, или файл по умолчанию; используйте Canvas
вместо Label, чтобы обеспечить возможность прокрутки, и т.д.
"""

import os, sys
from tkinter import *
from PIL.ImageTk import PhotoImage  # импорт из PIL, хотя устанавливался Pillow - обертка для PIL !!! PIL устарел

imgdir = 'images'
imgfile = 'carmel.JPG'
if len(sys.argv) > 1:  # аргумент командной строки задан?
    imgfile = sys.argv[1]
imgpath = os.path.join(imgdir, imgfile)
win = Tk()
win.title(imgfile)
imgobj = PhotoImage(file=imgpath)
Label(win, image=imgobj).pack()  # прикрепить к метке Label
print(imgobj.width(), imgobj.height())  # вывести размеры в пикселях,
win.mainloop()  # пока объект не уничтожен
 def __init__(self,x,y):
     self._image = PhotoImage(file='Black_Hole.gif')
     Simulton.__init__(self,x,y,self._image.width(),self._image.height())
     self.radius = (self._image.height()/2)+((self._image.width()**2)/(8 * self._image.height()))