Python PIL.ImageTk 模块,PhotoImage() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PIL.ImageTk.PhotoImage()

项目:Python-GUI-Programming-Cookbook-Second-Edition    作者:PacktPublishing    | 项目源码 | 文件源码
def __init__(self, msShowTimeBetweenSlides=1500):
        # initialize tkinter super class
        Tk.__init__(self)

        # time each slide will be shown
        self.showTime = msShowTimeBetweenSlides

        # look for images in current working directory where this module lives
        chapter_folder = path.realpath(path.dirname(__file__))
        resources_folder = path.join(chapter_folder, 'Resources')
        listOfSlides = [slide for slide in listdir(resources_folder) if slide.endswith('gif') or slide.endswith('jpg')]

        # endlessly read in the slides so we can show them on the tkinter Label 
        chdir(resources_folder)
        self.iterableCycle = cycle((ImageTk.PhotoImage(file=slide), slide) for slide in listOfSlides)

        # create tkinter Label widget which can also display images
        self.slidesLabel = Label(self)

        # create the Frame widget
        self.slidesLabel.pack()
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def resize(self,event):
        sc = self.canvas
        sc.delete(ALL)            # erase the whole canvas
        width  = sc.winfo_width()
        height = sc.winfo_height()

        imgSize = min(width, height)
        self.pad = imgSize/16
        viewport = (self.pad,self.pad,width-self.pad,height-self.pad)
        self.T = mapper(self.world,viewport)

        if self.showImage:
           flu = self.fluImg.resize((int(0.8*0.8*imgSize), int(0.8*imgSize)), Image.ANTIALIAS) 
           self.flu = ImageTk.PhotoImage(flu)
           sc.create_image(width/2,height/2,image=self.flu)
        else:
           self.canvas.create_rectangle([[0,0],[width,height]], fill = self.bgcolor)

        self.redraw()             # redraw the clock    

    ## Sets the clock colors.
    #
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __init__(self, master, text, foreground="black", truetype_font=None, font_path=None, family=None, size=None, **kwargs):   
        if truetype_font is None:
            if font_path is None:
                raise ValueError("Font path can't be None")

            # Initialize font
            truetype_font = ImageFont.truetype(font_path, size)

        width, height = truetype_font.getsize(text)

        image = Image.new("RGBA", (width, height), color=(0,0,0,0))
        draw = ImageDraw.Draw(image)

        draw.text((0, 0), text, font=truetype_font, fill=foreground)

        self._photoimage = ImageTk.PhotoImage(image)
        Label.__init__(self, master, image=self._photoimage, **kwargs)
项目:Neural-Photo-Editor    作者:ajbrock    | 项目源码 | 文件源码
def update_photo(data=None,widget=None):
    global Z
    if data is None: # By default, assume we're updating with the current value of Z
        data = np.repeat(np.repeat(np.uint8(from_tanh(model.sample_at(np.float32([Z.flatten()]))[0])),4,1),4,2)
    else:
        data = np.repeat(np.repeat(np.uint8(data),4,1),4,2)

    if widget is None:
        widget = output
    # Reshape image to canvas
    mshape = (4*64,4*64,1)
    im = Image.fromarray(np.concatenate([np.reshape(data[0],mshape),np.reshape(data[1],mshape),np.reshape(data[2],mshape)],axis=2),mode='RGB')

    # Make sure photo is an object of the current widget so the garbage collector doesn't wreck it
    widget.photo = ImageTk.PhotoImage(image=im)
    widget.create_image(0,0,image=widget.photo,anchor=NW)
    widget.tag_raise(pixel_rect)

# Function to update the latent canvas.
项目:ascii-art-py    作者:blinglnav    | 项目源码 | 文件源码
def __init__(self, master, image):
        Canvas.__init__(self, master, width=image.size[0], height=image.size[1])

        # fill the canvas
        self.tile = {}
        self.tilesize = tilesize = 32
        xsize, ysize = image.size
        for x in range(0, xsize, tilesize):
            for y in range(0, ysize, tilesize):
                box = x, y, min(xsize, x+tilesize), min(ysize, y+tilesize)
                tile = ImageTk.PhotoImage(image.crop(box))
                self.create_image(x, y, image=tile, anchor=NW)
                self.tile[(x, y)] = box, tile

        self.image = image

        self.bind("<B1-Motion>", self.paint)
项目:ascii-art-py    作者:blinglnav    | 项目源码 | 文件源码
def __init__(self, master, image, name, enhancer, lo, hi):
        Frame.__init__(self, master)

        # set up the image
        self.tkim = ImageTk.PhotoImage(image.mode, image.size)
        self.enhancer = enhancer(image)
        self.update("1.0")  # normalize

        # image window
        Label(self, image=self.tkim).pack()

        # scale
        s = Scale(self, label=name, orient=HORIZONTAL,
                  from_=lo, to=hi, resolution=0.01,
                  command=self.update)
        s.set(self.value)
        s.pack()
项目:ascii-art-py    作者:blinglnav    | 项目源码 | 文件源码
def __init__(self, master, im):
        if isinstance(im, list):
            # list of images
            self.im = im[1:]
            im = self.im[0]
        else:
            # sequence
            self.im = im

        if im.mode == "1":
            self.image = ImageTk.BitmapImage(im, foreground="white")
        else:
            self.image = ImageTk.PhotoImage(im)

        Label.__init__(self, master, image=self.image, bg="black", bd=0)

        self.update()

        try:
            duration = im.info["duration"]
        except KeyError:
            duration = 100
        self.after(duration, self.next)
项目:Quiver    作者:DeflatedPickle    | 项目源码 | 文件源码
def load_image(self, image=""):
        self.widget_canvas_image.delete("all")

        self.image_open = Image.open(image, "r")
        self.image_photo = ImageTk.PhotoImage(self.image_open)

        self.original_width = self.image_photo.width()
        self.original_height = self.image_photo.height()

        self.widget_canvas_image.configure(scrollregion=(0, 0, self.image_photo.width(), self.image_photo.height()))
        self.widget_canvas_image.configure(width=self.image_photo.width(), height=self.image_photo.height())
        self.drawn_image = self.widget_canvas_image.create_image(0, 0, anchor="nw", image=self.image_photo,
                                                                 tags="image")
        self.title("{} - {}".format(self.title(), "".join(os.path.splitext(image))))

        self.check_tile_buttons()
        self.draw_background()
项目:Quiver    作者:DeflatedPickle    | 项目源码 | 文件源码
def zoom_in(self):
        self.widget_canvas_image.delete("image")

        self.image_photo = ImageTk.PhotoImage(self.image_open.resize(
            (self.image_photo.width() + self.original_width, self.image_photo.height() + self.original_height)))
        self.widget_canvas_image.configure(scrollregion=(self.check_scrollregion()))
        self.widget_canvas_image.configure(width=self.check_size()[0], height=self.check_size()[1])
        # self.drawn_image = self.widget_canvas_image.create_image(0, 0, anchor="nw", image=self.image_photo, tags="image")

        self.zoom_current += 1
        # print(self.zoom_current)

        self.zoom_width = self.image_photo.width()
        self.zoom_height = self.image_photo.height()

        self.draw_tiles()
        self.draw_background()
        self.check_zoom()
项目:Quiver    作者:DeflatedPickle    | 项目源码 | 文件源码
def zoom_out(self):
        self.widget_canvas_image.delete("image")

        self.image_photo = ImageTk.PhotoImage(self.image_open.resize(
            (self.image_photo.width() - self.original_width, self.image_photo.height() - self.original_height)))
        self.widget_canvas_image.configure(scrollregion=(self.check_scrollregion()))
        self.widget_canvas_image.configure(width=self.check_size()[0], height=self.check_size()[1])
        # self.drawn_image = self.widget_canvas_image.create_image(0, 0, anchor="nw", image=self.image_photo, tags="image")

        self.zoom_current -= 1
        # print(self.zoom_current)

        self.zoom_width = self.image_photo.width()
        self.zoom_height = self.image_photo.height()

        self.draw_tiles()
        self.draw_background()
        self.check_zoom()
项目:PyLabyrinthe    作者:yoann-darche    | 项目源码 | 文件源码
def __init__(self, ctxGfx, initPv=100, spriteFile='sprite/Hero/hero.png'):
        """
        Fonction d'initialisation du Player mode Graphique
        :param gfxCtx: Context TK
        :param initPv: Point de vie Initial
        :param spriteFile: Fichier image représantant le joueur
        :return: NA
        """

        # Référence sur context graphique
        self._ctxGfx = ctxGfx

        Player.__init__(self,initPv)

        # Contient le sprite du joueur
        # self.Sprite = Tk.PhotoImage(file=spriteFile, master=self._ctxGfx.fenetre)
        self.Sprite = Image.open(spriteFile)
        self._img = None

        # Déclanche l'affichage
        self._hasChanged = True
项目:ATX    作者:NetEaseGame    | 项目源码 | 文件源码
def interactive_save(image):
    img_str = cv2.imencode('.png', image)[1].tostring()
    imgpil = Image.open(StringIO(img_str))

    root = Tkinter.Tk()
    root.geometry('{}x{}'.format(400, 400))
    imgtk = ImageTk.PhotoImage(image=imgpil)
    panel = Tkinter.Label(root, image=imgtk) #.pack()
    panel.pack(side="bottom", fill="both", expand="yes")
    Tkinter.Button(root, text="Hello!").pack()
    save_to = tkSimpleDialog.askstring("Save cropped image", "Enter filename")
    if save_to:
        if save_to.find('.') == -1:
            save_to += '.png'
        print 'Save to:', save_to
        cv2.imwrite(save_to, image)
    root.destroy()
项目:AutomatorX    作者:xiaoyaojjian    | 项目源码 | 文件源码
def interactive_save(image):
    img_str = cv2.imencode('.png', image)[1].tostring()
    imgpil = Image.open(StringIO(img_str))

    root = Tkinter.Tk()
    root.geometry('{}x{}'.format(400, 400))
    imgtk = ImageTk.PhotoImage(image=imgpil)
    panel = Tkinter.Label(root, image=imgtk) #.pack()
    panel.pack(side="bottom", fill="both", expand="yes")
    Tkinter.Button(root, text="Hello!").pack()
    save_to = tkSimpleDialog.askstring("Save cropped image", "Enter filename")
    if save_to:
        if save_to.find('.') == -1:
            save_to += '.png'
        print 'Save to:', save_to
        cv2.imwrite(save_to, image)
    root.destroy()
项目:Circadia    作者:hooyah    | 项目源码 | 文件源码
def updateScreen(self, canvas):
        """ update the image with a new canvas"""

        w = canvas.width
        h = canvas.height

        img = Image.new('RGB', (w, h))
        drw = ImageDraw.Draw(img)
        for x in xrange(w):
            for y in xrange(h):
                col = canvas.getPixel(x, y)
                drw.point((x,y), fill=(int(col[0]*255), int(col[1]*255), int(col[2]*255)))

        scl = img.resize( (87, 324), resample=Image.BILINEAR )
        self.lampSrc.paste(scl, (55,227))
        self.lampImg = ImageTk.PhotoImage(self.lampSrc)
        self.backgroundLabel.config(image=self.lampImg)
项目:JetsonTX1_im2txt    作者:Netzeband    | 项目源码 | 文件源码
def _openImage(self):
    FileTypes = [('JPG Image Files', '*.jpg'), ('All files', '*')]
    Dialog = tkFileDialog.Open(self._ControlFrame, filetypes = FileTypes)
    FileName = Dialog.show()

    if not FileName == '' and not FileName == ():
      print("Open file: "+str(FileName))

      if self._IsVideoRunnung:
        self._pressPause()

      Image = image.open(FileName)
      Image = Image.resize(self._getLabelSize(self._VideoLabel, Image.width/Image.height), image.ANTIALIAS)
      Image = imagetk.PhotoImage(Image)
      self._VideoLabel.imgtk = Image
      self._VideoLabel.configure(image=Image)          

      self._OutputText.delete('1.0', tk.END)

      File = tf.gfile.GFile(FileName, "r")
      Captions = self._CaptionFunc(File.read())

      for i, Caption in enumerate(Captions):
        self._OutputText.insert(tk.END, str(i+1)+") "+Caption+"\n")
项目:PyF9    作者:Saren-Arterius    | 项目源码 | 文件源码
def set_associate(self):
        if not ASSOCIATE_ENABLED:
            self.reset_associate()
            return
        self.button_function.configure(text='(??)')
        self.associate_count = 0
        for i, btn in enumerate(self.input_buttons):
            char = self.find_associate(self.last_char, i)
            self.current_associate[i] = char
            image = PImage.new("RGBA", (48, 48),
                               (255, 255, 255, 255) if platform.system() == "Darwin" else (255, 255, 255, 0))
            d = ImageDraw.Draw(image)
            d.text((0, 0), char, font=font, fill=(255, 255, 255, 255))
            photo = ImageTk.PhotoImage(image)
            btn.image = photo
            btn.configure(image=photo)
        self.is_associate = True
项目:blueearth    作者:littleningmeng    | 项目源码 | 文件源码
def pop_qrcode_window(qrcode_buff):
    if dont_show_qrcode():
        return 

    def on_button_clicked():
        try:
            open(magic_file_name, "w").write("""Hi, guy
If you like this app, a little donation will make it better!
Re-run the app to remove QR-code on your wallpaper""" )
        except:
            pass

        finally:
            sys.exit(1)

    tk = Tk()
    tk.wm_attributes('-topmost', 1)
    tk.title(u"???????BLUEEARTH?????")
    img2 = Image.open(StringIO(qrcode_buff))
    tk_img = ImageTk.PhotoImage(img2)
    label = Label(tk, image=tk_img)
    label.pack()
    button = Button(tk, text="Don't show this anymore", command=on_button_clicked, bg="green")
    button.pack()
    tk.mainloop()
项目:cozmo-python-sdk    作者:anki    | 项目源码 | 文件源码
def _draw_frame(self):
        if ImageTk is None:
            return

        try:
            image = self._img_queue.popleft()
        except IndexError:
            # no new image
            return

        self._first_image = False
        photoImage = ImageTk.PhotoImage(image)

        self.label.configure(image=photoImage)
        self.label.image = photoImage
        # Dynamically expand the image to fit the window. And fill in both X and Y directions.
        self.label.pack(fill=tkinter.BOTH, expand=True)
项目:FBIThemePreviewer    作者:jurassicplayer    | 项目源码 | 文件源码
def setupApp(self):
        print("Setting up main window...")
        self.icon_base64 = {
            'app' : """iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAp0lEQVRo3u3aoQ0CURBF0fsJ0A0VUMM2gFmFRBAIBr2GQBBI1BoaoAYqoBsQgyCIZR2CZJL75ORn/jt+SkQEiTMEKKWkLB8RbwBAPZ0AcFg+AVgdR53Hj3nDYr/htN71Fl3q6qcCs/bam33+GJ+3nfl3r/Z2B2BA8ggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAEC/pkSEZH+2CPzxc0LSCMmWnbVMHAAAAAASUVORK5CYII=""",
            'fbi' : """iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAlElEQVRYw+2YSw6AIAxEqeH+Vx5XJvhBVCyIebMitcpLRwoaAkJobFnugiQ1gzDLcsTCje5wpTrE2gdUVq6YM339HQQQQABHB4x3ko/6lqRdfOmduXw3wLMJ0riZBUkr0KcN/18Wb23bVs1je3S1mFVca30aW8auq/iKvW8f1dhJAAQQwN6NusW38WPAhj8XEEKol2b2bkM1u6bHlAAAAABJRU5ErkJggg==""",
            'textcolor' : """iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAABIklEQVRYw+2YUQ7CMAiGYfFi3kRvUr2IL72Hnozfh6Vba7p2sZDwUBJCzLb084cNWgZAnm0h5zYBJ+AEnIDGdundwMymX3IA3Fy/1UmY2bzPcAdyacDtP6JtLNaqSFz17XIkwDDS6ocsfUBjyL8Bc8gzfqDMGW9mcum8YamOe16vMSJG7D/bHPlaCp71pKDIHpM6ImNrqAHmcHltIToBtFKQNUZ+ZobIzwd2rW4WIRppRmq9+Mll1OyFajUYsMeU4gAnNZjDadag6rhVS/NwyjUVpIAtbl0iwEeKczi3NWihoFoNhgeK6G5P8nqX0R3g/brCpfgL7kLBHDIHd7PtrKXZjYJHdvsMDiJaB5iV/bPOpKR5wppvH9X++DwCnoATsG1fA0G6TzK0GV0AAAAASUVORK5CYII=""",
            'screenshot' : """iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAr0lEQVRYw+2XOw7AIAxDCcr9r5wuVEKolJAPYvBbWGgxJnFpKQAAAK6GVhNERMIXJSLtXFa+MEzc7n5rxrG8IvrRehCcUjfN8XFMFRhRihah9fYuhkAITIofCe/iyABvuSiaLwp7xFmjZ+dZd1D3JoyLjgZZNsRZ9fblksV1jir8lcPWcrg+ZvhUtKQL/GuGmbBjTWJ1IeQGZFxYvEGtvfqTo7Zc9lDkfwQAAAAw5QFkJVklKZGd2AAAAABJRU5ErkJggg==""",
            'opendir' : """iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAbElEQVRYw+2WMQ4AIAjEwPj/L+Pk7JGAOrQzwYoXgxkAAHyNK0UREVIzd78uuOVOZ+87VEtOcTJ2GqJS0yaYoToO0hNXRysTh5ltWhL8RBzG798MgggiiCCCCCL4Fnmbadjm6wQ7NmUAAIA7LC2EJS/bJR+TAAAAAElFTkSuQmCC""",
            'save' : """iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAk0lEQVRYw+2XzQ4AEQyEjXj/V+6eSCN76BYldr6TIEzG+EuJEELI0cDaUURkeDIASwRWcY7x9RgukWaBAFJv4ludrtftXdksMkdlqQr+GpccGXgtcqvACfupUVY6MkNoOcmt7Rm8UqBriT0HtjcKJSJ7IzfQnUtsdecXxwwdpIO7HQx7UXtf1qF/kpG/CSGEEOLjAb/NVySMpPXIAAAAAElFTkSuQmCC""",
            }
        self.icon = {
            'app'        : tk.PhotoImage(data=self.icon_base64['app']),
            'fbi'        : tk.PhotoImage(data=self.icon_base64['fbi']),
            'textcolor'  : tk.PhotoImage(data=self.icon_base64['textcolor']),
            'screenshot' : tk.PhotoImage(data=self.icon_base64['screenshot']),
            'opendir'    : tk.PhotoImage(data=self.icon_base64['opendir']),
            'save'       : tk.PhotoImage(data=self.icon_base64['save']),
            }
        self.call('wm', 'iconphoto', self._w, self.icon['app'])
        self.resizable(width=False, height=False)
        self.title('FBI Theme Previewer')
项目:FBIThemePreviewer    作者:jurassicplayer    | 项目源码 | 文件源码
def loadImage(self, folderpath, filename):
        print("Loading image: {}".format(os.path.join(folderpath, "{}.png".format(filename))))
        try:
            filepath = os.path.join(folderpath, "{}.png".format(filename))
            if filename in ['progress_bar_content_25', 'progress_bar_content_50', 'progress_bar_content_75']:    return
            elif filename == 'progress_bar_content' or filename == 'selection_overlay':
                tmp_image = Image.open(filepath)
                if filename == 'selection_overlay':
                    tmp_image = tmp_image.convert('RGBA').resize((320, 15), Image.ANTIALIAS)
                if filename == 'progress_bar_content':
                    self.i['{}_25'.format(filename)] = ImageTk.PhotoImage(tmp_image.crop((0, 0, int(280*0.25), 30)))
                    self.i['{}_50'.format(filename)] = ImageTk.PhotoImage(tmp_image.crop((0, 0, int(280*0.50), 30)))
                    self.i['{}_75'.format(filename)] = ImageTk.PhotoImage(tmp_image.crop((0, 0, int(280*0.75), 30)))
                self.i[filename] = ImageTk.PhotoImage(tmp_image)
            else:
                self.i[filename] = tk.PhotoImage(file=filepath)
        except Exception as e:
            return filename
项目:FBIThemePreviewer    作者:jurassicplayer    | 项目源码 | 文件源码
def setupApp(self):
        print("Setting up main window...")
        self.icon_base64 = {
            'app' : """iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAp0lEQVRo3u3aoQ0CURBF0fsJ0A0VUMM2gFmFRBAIBr2GQBBI1BoaoAYqoBsQgyCIZR2CZJL75ORn/jt+SkQEiTMEKKWkLB8RbwBAPZ0AcFg+AVgdR53Hj3nDYr/htN71Fl3q6qcCs/bam33+GJ+3nfl3r/Z2B2BA8ggQIECAAAECBAgQIECAAAECBAgQIECAAAECBAgQIECAAAEC/pkSEZH+2CPzxc0LSCMmWnbVMHAAAAAASUVORK5CYII=""",
            'fbi' : """iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAlElEQVRYw+2YSw6AIAxEqeH+Vx5XJvhBVCyIebMitcpLRwoaAkJobFnugiQ1gzDLcsTCje5wpTrE2gdUVq6YM339HQQQQABHB4x3ko/6lqRdfOmduXw3wLMJ0riZBUkr0KcN/18Wb23bVs1je3S1mFVca30aW8auq/iKvW8f1dhJAAQQwN6NusW38WPAhj8XEEKol2b2bkM1u6bHlAAAAABJRU5ErkJggg==""",
            'textcolor' : """iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAABIklEQVRYw+2YUQ7CMAiGYfFi3kRvUr2IL72Hnozfh6Vba7p2sZDwUBJCzLb084cNWgZAnm0h5zYBJ+AEnIDGdundwMymX3IA3Fy/1UmY2bzPcAdyacDtP6JtLNaqSFz17XIkwDDS6ocsfUBjyL8Bc8gzfqDMGW9mcum8YamOe16vMSJG7D/bHPlaCp71pKDIHpM6ImNrqAHmcHltIToBtFKQNUZ+ZobIzwd2rW4WIRppRmq9+Mll1OyFajUYsMeU4gAnNZjDadag6rhVS/NwyjUVpIAtbl0iwEeKczi3NWihoFoNhgeK6G5P8nqX0R3g/brCpfgL7kLBHDIHd7PtrKXZjYJHdvsMDiJaB5iV/bPOpKR5wppvH9X++DwCnoATsG1fA0G6TzK0GV0AAAAASUVORK5CYII=""",
            'screenshot' : """iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAr0lEQVRYw+2XOw7AIAxDCcr9r5wuVEKolJAPYvBbWGgxJnFpKQAAAK6GVhNERMIXJSLtXFa+MEzc7n5rxrG8IvrRehCcUjfN8XFMFRhRihah9fYuhkAITIofCe/iyABvuSiaLwp7xFmjZ+dZd1D3JoyLjgZZNsRZ9fblksV1jir8lcPWcrg+ZvhUtKQL/GuGmbBjTWJ1IeQGZFxYvEGtvfqTo7Zc9lDkfwQAAAAw5QFkJVklKZGd2AAAAABJRU5ErkJggg==""",
            'opendir' : """iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAbElEQVRYw+2WMQ4AIAjEwPj/L+Pk7JGAOrQzwYoXgxkAAHyNK0UREVIzd78uuOVOZ+87VEtOcTJ2GqJS0yaYoToO0hNXRysTh5ltWhL8RBzG798MgggiiCCCCCL4Fnmbadjm6wQ7NmUAAIA7LC2EJS/bJR+TAAAAAElFTkSuQmCC""",
            'save' : """iVBORw0KGgoAAAANSUhEUgAAACgAAAAoCAYAAACM/rhtAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAk0lEQVRYw+2XzQ4AEQyEjXj/V+6eSCN76BYldr6TIEzG+EuJEELI0cDaUURkeDIASwRWcY7x9RgukWaBAFJv4ludrtftXdksMkdlqQr+GpccGXgtcqvACfupUVY6MkNoOcmt7Rm8UqBriT0HtjcKJSJ7IzfQnUtsdecXxwwdpIO7HQx7UXtf1qF/kpG/CSGEEOLjAb/NVySMpPXIAAAAAElFTkSuQmCC""",
            }
        self.icon = {
            'app'        : Image.open(BytesIO(base64.b64decode(self.icon_base64['app']))),
            'fbi'        : tk.PhotoImage(data=self.icon_base64['fbi']),
            'textcolor'  : tk.PhotoImage(data=self.icon_base64['textcolor']),
            'screenshot' : tk.PhotoImage(data=self.icon_base64['screenshot']),
            'opendir'    : tk.PhotoImage(data=self.icon_base64['opendir']),
            'save'       : tk.PhotoImage(data=self.icon_base64['save']),
            }
        app_icon = ImageTk.PhotoImage(self.icon['app'])
        self.call('wm', 'iconphoto', self._w, app_icon)
        self.resizable(width=False, height=False)
        self.title('FBI Theme Previewer')
项目:SpaceBorgOne    作者:piborg    | 项目源码 | 文件源码
def AnimatedSend(self):
        waited = (time.time() - self.animStartTime) * 1000
        if waited < TRANSMISSION_LAG_MS:
            # Load the next frame
            if self.frame >= len(self.gifFrames):
                self.frame = 0
            self.imgSend = self.gifFrames[self.frame].resize(self.animSize, Image.ANTIALIAS)
            self.itkSend = ImageTk.PhotoImage(self.imgSend)
            self.picSend.delete('IMG')
            self.picSend.create_image(0, 0, image = self.itkSend, anchor = Tkinter.NW, tags = 'IMG')
            self.frame += 1
            # Wait for animation step
            delay = int(100 - ((time.time() - self.animLastFrame) * 1000))
            if delay < 0:
                delay = 0
            self.animLastFrame = time.time()
            self.after(delay, self.AnimatedSend)
        else:
            # End the animation. transmit the command
            self.picSend.place_forget()
            SendOnly(self.animCommand)

    # Start the transmission animation
项目:yachess    作者:devinalvaro    | 项目源码 | 文件源码
def draw_pieces(self):
        self.canvas.delete('piece')

        for square in chess.SQUARES:
            piece = self.board.piece_at(square)

            if piece is not None:
                image_name = 'img/%s.png' % (piece.symbol())
                piece_name = '%s%s' % (piece.symbol(), square)

                if image_name not in self.icons:
                    image = Image.open(image_name).resize((64, 64))
                    self.icons[image_name] = ImageTk.PhotoImage(image)

                row = square // 8
                column = square % 8

                self.add_piece(piece_name, self.icons[image_name], row, column)
                self.place_piece(piece_name, row, column)
项目:Narwhal    作者:peterwaksman    | 项目源码 | 文件源码
def readText(event):
    text = T.get()
    BB.Read(text)
    if False and BB.data.comp( BB.prevdata ):
        return

    h = Image.new("RGB",(IMGWIDTH,IMGHEIGHT), "white")    

    BB.data.drawScene( h )

    img = ImageTk.PhotoImage(h)

    panel = Label(root, image = img)
    panel.grid(row=8, column = 0)

    panel.configure( image=img )
    panel.image = img

    s = BB.Write()
    print s

    response.set(s)


#----------- APP ------------------
项目:Narwhal    作者:peterwaksman    | 项目源码 | 文件源码
def readText(event):
    text = T.get()
    Q.Read(text)

    h = Image.new("RGB",(IMGHWIDTH,IMGHEIGHT), "white")    

    #drawReferenceFeatures(h)

    #K = ABT.sketch
    #K.Draw(h)  

    img = ImageTk.PhotoImage(h)

    panel = Label(root, image = img)
    panel.grid(row=8, column = 0)

    panel.configure( image=img )
    panel.image = img

    s = Q.Write()#''#ABT.responder.getStageResponse()
    response.set(s)

#This creates the main root of an application
项目:audiojack-ui    作者:anilee    | 项目源码 | 文件源码
def get_results(self, input):
        try:
            results = audiojack.get_results(input)[:8]
            images = []
            for i, result in enumerate(results):
                if run:
                    image_data = Image.open(StringIO(audiojack.get_cover_art_as_data(results[i][3]).decode('base64')))
                    image_data = image_data.resize((200, 200), Image.ANTIALIAS)
                    images.append(ImageTk.PhotoImage(image=image_data))
                else:
                    break
            if run:
                self.q.put([results, images])
            else:
                self.q.put(0)
        except (ExtractorError, DownloadError):   # If the URL is invalid,
            self.q.put(-1)   # put -1 into the queue to indicate that the URL is invalid.
        except NetworkError:
            self.q.put(-2)
项目:mountain_tapir    作者:tttppp    | 项目源码 | 文件源码
def makeImage(self, purpose, dimensions, canvas):
        """Make a :class:`PIL.Image` and put it in the supplied canvas.

        :param purpose: A string describing the purpose of the image. This is
            used for both logging and also when persisting the image so that TK
            doesn't garbage collect it.
        :param dimensions: An iterable pair - (width, height).
        :param canvas: The :class:`tkinter.Canvas` where the image will be
            displayed.
        """
        image = self.getImageObject(dimensions, purpose)
        if image is not None:
            photoImage = ImageTk.PhotoImage(image)
            self.images[purpose].append(photoImage)
            canvas.create_image(0, 0, image=photoImage, anchor="nw")
            canvas.config(scrollregion=canvas.bbox(TK.ALL))
项目:mountain_tapir    作者:tttppp    | 项目源码 | 文件源码
def setThumbnail(self, imageButtonPair):
            """Try to load the image from the path and display it on the button.

            :param imageButtonPair: A pair containing an image path and a button."""
            button = imageButtonPair[1]
            if not button.winfo_exists():
                # This might happen if the refresh button has been pressed, or navigation has taken place.
                return
            imagePath = imageButtonPair[0]
            if imagePath not in OpenImageDialog.thumbnailCache.keys():
                imageFile = ImageFile(imagePath)
                image = imageFile.getImageObject((64, 50), 'openDialog')
                OpenImageDialog.thumbnailCache[imagePath] = image
            image = OpenImageDialog.thumbnailCache[imagePath]
            if image is not None:
                button.image = ImageTk.PhotoImage(image)
                try:
                    button.config(image=button.image)
                except TK.TclError:
                    # This might happen if the dialog has been closed.
                    return
项目:network-pj-chatroom    作者:KevinWang15    | 项目源码 | 文件源码
def digest_message(self, data):
        time = datetime.datetime.fromtimestamp(
            int(data['time']) / 1000
        ).strftime('%Y-%m-%d %H:%M:%S')
        self.append_to_chat_box(data['sender_name'] + "  " + time + '\n',
                                ('me' if client.memory.current_user['id'] == data[
                                    'sender_id'] else 'them'))
        # type 0 - ???? 1 - ????
        if data['message']['type'] == 0:
            self.tag_i += 1
            self.chat_box.tag_config('new' + str(self.tag_i),
                                     lmargin1=16,
                                     lmargin2=16,
                                     foreground=data['message']['fontcolor'],
                                     font=(None, data['message']['fontsize']))
            self.append_to_chat_box(data['message']['data'] + '\n',
                                    'new' + str(self.tag_i))
        if data['message']['type'] == 1:
            client.memory.tk_img_ref.append(ImageTk.PhotoImage(data=data['message']['data']))
            self.chat_box.image_create(END, image=client.memory.tk_img_ref[-1], padx=16, pady=5)
            self.append_to_chat_box('\n', '')
项目:StackIt    作者:poppu-mtg    | 项目源码 | 文件源码
def __init__(self):
        self.image1 = Image.open(mGui.btn2text.get()[9:] + '-scroll.png')
        w1, h1 = self.image1.size
        self.imagefull = Image.new("RGB", (w1 * 2, h1), "black")
        self.imagefull.paste(self.image1, (0, 0))
        self.imagefull.paste(self.image1, (w1, 0))

        self.photo1 = ImageTk.PhotoImage(self.imagefull)
        width1 = self.photo1.width()
        height1 = self.photo1.height()

        novi1 = Toplevel()
        self.canvas1 = Canvas(novi1, width=1980, height=34)
        self.canvas1.pack(expand=1, fill=BOTH) # <--- Make your canvas expandable.
        x = (width1)/2.0
        y = (height1)/2.0
        self.item = self.canvas1.create_image(x, y, image=self.photo1) # <--- Save the return value of the create_* method.
        self.x00, self.y00 = self.canvas1.coords(self.item)
        self.canvas1.bind('<Button-1>', self.next_image)
项目:Farmbot_GeneralAP    作者:SpongeYao    | 项目源码 | 文件源码
def display_panel_mergeframe(self, arg_frame, arg_stepX, arg_stepY): 
        print '*** ',len(arg_frame.shape)
        if len(arg_frame.shape)==3:
            tmp_frame= cv2.cvtColor(arg_frame, cv2.COLOR_BGR2RGB)
        else: 
            tmp_frame= cv2.cvtColor(arg_frame, cv2.COLOR_GRAY2RGB)

        tmp_frame= cv2.resize(tmp_frame,(self.mergeframe_splitX,self.mergeframe_splitY),interpolation=cv2.INTER_LINEAR)
        begX= gui_vars.interval_x+self.mergeframe_splitX*arg_stepX
        begY= self.mergeframe_spaceY+ self.mergeframe_splitY* arg_stepY 
        self.mergeframe[begY:begY+ self.mergeframe_splitY, begX: begX+ self.mergeframe_splitX]= tmp_frame
        #begY= self.mergeframe_height- 50- self.mergeframe_splitY*arg_stepY
        #self.mergeframe[begY-self.mergeframe_splitY:begY, begX: begX+ self.mergeframe_splitX]= tmp_frame
        self.mergeframe_stepX= arg_stepX
        self.mergeframe_stepY= arg_stepY
        print '>> mergeframe_splitY, splitX= ', self.mergeframe_splitY, ', ', self.mergeframe_splitX
        print '>> tmp_frame.shape[0,1]= ', tmp_frame.shape[0],', ',tmp_frame.shape[1]

        result = Image.fromarray(self.mergeframe)
        result = ImageTk.PhotoImage(result)
        self.panel_mergeframe.configure(image = result)
        self.panel_mergeframe.image = result
项目:image-copy-move-detection    作者:rahmatnazali    | 项目源码 | 文件源码
def onDetect(self):
        if self.imageName == "":
            mbox.showerror("Error", 'Citra masukan belum terisi\nSilakan pilih dengan menekan tombol "Open File"')
        else:

            self.textBoxLog.config(state='normal')
            self.textBoxLog.insert(END, "Mendeteksi: "+self.imageName+"\n")
            self.textBoxLog.see(END)
            self.textBoxLog.config(state='disabled')

            imageResultPath = CopyMoveDetection.detect(self.imagePath, self.imageName, '../testcase_result/', blockSize=32)
            newImageRight = Image.open(imageResultPath)
            imageRightLabel = ImageTk.PhotoImage(newImageRight)
            self.labelRight = Label(self, image=imageRightLabel)
            self.labelRight.image = imageRightLabel
            self.labelRight.place(x=525, y=100)

            self.textBoxLog.config(state='normal')
            self.textBoxLog.insert(END, "Selesai.")
            self.textBoxLog.see(END)
            self.textBoxLog.config(state='disabled')
            pass
        pass
项目:Video-Streaming    作者:henadaus    | 项目源码 | 文件源码
def __init__(self,*args,**kwargs):
        tk.Tk.__init__(self,*args,**kwargs)

        self.setup=tk.Button(self,text="Setup",command=self.setupFunc)
        self.setup.pack()

        self.play=tk.Button(self,text="Play",command=self.playFunc)
        self.play.pack()

        self.pause=tk.Button(self,text="Pause",command=self.pauseFunc)
        self.pause.pack()

        self.teardown=tk.Button(self,text="Teardown",command=self.teardownFunc)
        self.teardown.pack()

        self.img=ImageTk.PhotoImage(Image.open('tuned.jpg'))
        self.video=tk.Label(self,image=self.img)
        self.video.pack()

        self.status="INIT"

        self.c=0
        self.initialize()
项目:Towards-a-Biologically-Plausible-Backprop    作者:bscellier    | 项目源码 | 文件源码
def update_canvas(self, first_time = False):

        units  = [(28,28)]  +[(10,n/10) for n in self.hidden_sizes]+[(1,10)]
        pixels = [(140,140)]+ [(n/2,50) for n in self.hidden_sizes]+[(250,25)]

        arrays = [256*layer.eval().reshape(dimensions) for layer,dimensions in zip(self.net.layers,units)]
        images = [Image.fromarray(array).resize(dimensions) for array,dimensions in zip(arrays,pixels)]
        self.imgTks = [ImageTk.PhotoImage(image) for image in images]

        [energy, cost, _] = self.net.measure()

        if first_time:
            self.img_canvas    = [self.canvas.create_image(400, (self.n_layers-k)*100, image=imgTk) for k,imgTk in enumerate(self.imgTks)]
            self.energy_canvas = self.canvas.create_text( 20, 100, anchor=W, font="Purisa", text="Energy = %.1f" % (energy))
            self.cost_canvas   = self.canvas.create_text( 20, 200, anchor=W, font="Purisa", text="Cost = %.4f"   % (cost))
        else:
            for img_canvas, imgTk in zip(self.img_canvas,self.imgTks):
                self.canvas.itemconfig(img_canvas, image=imgTk)
            self.canvas.itemconfig(self.energy_canvas, text="Energy = %.1f" % (energy))
            self.canvas.itemconfig(self.cost_canvas,   text="Cost = %.4f"   % (cost))
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def update(self):
        while self.running:
            # Read the length of the image as a 32-bit unsigned int.
            data_len = struct.unpack('<L', self.connection.read(struct.calcsize('<L')))[0]
            if data_len:
                printD('Updating...')
                printD('data_len: %s' % data_len)
                data = self.connection.read(data_len)
                deserialized_data = msgpack.unpackb(data, object_hook=msgpack_numpy.decode)
                printD('Frame received')
                #print(deserialized_data)
                #stdout.flush()
                img = Image.fromarray(deserialized_data)
                newImage = ImageTk.PhotoImage(img)
                self.gui.stream_label.configure(image=newImage)
                self.gui.stream_label.image = newImage
                printD("image updated")
            else:
                time.sleep(0.001)
项目:Sample-Code    作者:meigrafd    | 项目源码 | 文件源码
def update_2(self):
        if self.running == False:
            return
        # Read the length of the image as a 32-bit unsigned int.
        data_len = struct.unpack('<L', self.connection.read(struct.calcsize('<L')))[0]
        if data_len:
            printD('Updating...')
            printD('data_len: %s' % data_len)
            data = self.connection.read(data_len)
            deserialized_data = msgpack.unpackb(data, object_hook=msgpack_numpy.decode)
            printD('Frame received')
            #print(deserialized_data)
            #stdout.flush()
            img = Image.fromarray(deserialized_data)
            newImage = ImageTk.PhotoImage(img)
            self.gui.stream_label.configure(image=newImage)
            self.gui.stream_label.image = newImage
        self.gui.master.after(70, self.update_2)
项目:ActiveBoundary    作者:MiriamHu    | 项目源码 | 文件源码
def make_image(self):
        self.image_frame = Frame()
        self.image_frame.grid(row=3, column=1, columnspan=1)

        self.confirm_button = Button(self.image_frame, command=self.confirm_callback, text="Confirm", state=DISABLED)
        self.confirm_button.grid(row=3, column=1)
        class_var = StringVar()
        self.dropdown_class = OptionMenu(self.image_frame, class_var, self.classes_dictionary[self.classes[0]],
                                         self.classes_dictionary[self.classes[1]], command=self.class_dropdown_callback)
        self.dropdown_class.var = class_var
        self.dropdown_class.grid(row=2, column=1)

        if self.point_query_image.shape[1] == 1:
            query_img = self.point_query_image[0, :, :].squeeze()
        else:
            query_img = self.point_query_image.squeeze().transpose(1, 2, 0)
        query_img = Image.fromarray(np.uint8(255 * query_img))
        query_img = ImageTk.PhotoImage(query_img)
        imglabel = Label(self.image_frame, image=query_img, text="point query", compound=BOTTOM)
        imglabel.image = query_img
        imglabel.grid(row=1, column=1)
        self.image_frame.pack()
        return True
项目:RaspberryPiBarcodeScanner    作者:briandorey    | 项目源码 | 文件源码
def __orders_tab_clicked(self, from_barcode = False):
        #
        # Orders tab click event
        #

        self.current_tab = "orders"

        # update the images in the tab bar to show the selected tab
        self.ordersicon = ImageTk.PhotoImage(Image.open(self.system_path + "tabbar-orders-selected.bmp"))
        self.orders_button.config(image = self.ordersicon)

        self.productsicon = ImageTk.PhotoImage(Image.open(self.system_path + "tabbar-products.bmp"))
        self.products_button.config(image = self.productsicon)

        self.partsicon = ImageTk.PhotoImage(Image.open(self.system_path + "tabbar-parts.bmp"))
        self.parts_button.config(image = self.partsicon)

        # clear any content from the content_scroll_frame and get a list of the current orders
        self.uicommon.clear_frame(self.content_scroll_frame)
        if (not from_barcode):
            self.orders.orders_list(self.content_scroll_frame)

        return()
项目:RaspberryPiBarcodeScanner    作者:briandorey    | 项目源码 | 文件源码
def __products_tab_clicked(self, from_barcode = False):
        #
        # Products tab click events
        #

        self.current_tab = "products"

        # update the images in the tab bar to show the selected tab
        self.ordersicon = ImageTk.PhotoImage(Image.open(self.system_path + "tabbar-orders.bmp"))
        self.orders_button.config(image = self.ordersicon)

        self.productsicon = ImageTk.PhotoImage(Image.open(self.system_path + "tabbar-products-selected.bmp"))
        self.products_button.config(image = self.productsicon)

        self.partsicon = ImageTk.PhotoImage(Image.open(self.system_path + "tabbar-parts.bmp"))
        self.parts_button.config(image = self.partsicon)

        # clear any content from the content_scroll_frame and get a list of the products
        self.uicommon.clear_frame(self.content_scroll_frame)
        if (not from_barcode):
            self.products.products_list(self.content_scroll_frame)

        return()
项目:RaspberryPiBarcodeScanner    作者:briandorey    | 项目源码 | 文件源码
def __parts_tab_clicked(self, from_barcode = False):
        #
        # Parts tab click event
        #

        self.current_tab = "parts"

        # update the images in the tab bar to show the selected tab
        self.ordersicon = ImageTk.PhotoImage(Image.open(self.system_path + "tabbar-orders.bmp"))
        self.orders_button.config(image = self.ordersicon)

        self.productsicon = ImageTk.PhotoImage(Image.open(self.system_path + "tabbar-products.bmp"))
        self.products_button.config(image = self.productsicon)

        self.partsicon = ImageTk.PhotoImage(Image.open(self.system_path + "tabbar-parts-selected.bmp"))
        self.parts_button.config(image = self.partsicon)

        # clear any content from the content_scroll_frame and get a list of the parts
        self.uicommon.clear_frame(self.content_scroll_frame)
        if (not from_barcode):
            self.parts.parts_list(self.content_scroll_frame)

        return()
项目:DualFisheye    作者:ooterness    | 项目源码 | 文件源码
def update_preview(self, psize):
        # Safety check: Ignore calls during construction/destruction.
        if not self.init_done: return
        # Copy latest user settings to the lens object.
        self.lens.fov_deg = self.f.get()
        self.lens.radius_px = self.r.get()
        self.lens.center_px[0] = self.x.get()
        self.lens.center_px[1] = self.y.get()
        # Re-scale the image to match the canvas size.
        # Note: Make a copy first, because thumbnail() operates in-place.
        self.img_sc = self.img.copy()
        self.img_sc.thumbnail(psize, Image.NEAREST)
        self.img_tk = ImageTk.PhotoImage(self.img_sc)
        # Re-scale the x/y/r parameters to match the preview scale.
        pre_scale = float(psize[0]) / float(self.img.size[0])
        x = self.x.get() * pre_scale
        y = self.y.get() * pre_scale
        r = self.r.get() * pre_scale
        # Clear and redraw the canvas.
        self.preview.delete('all')
        self.preview.create_image(0, 0, anchor=tk.NW, image=self.img_tk)
        self.preview.create_oval(x-r, y-r, x+r, y+r,
                                 outline='#C00000', width=3)

    # Make a combined label/textbox/slider for a given variable:
项目:dr1det    作者:narbi    | 项目源码 | 文件源码
def show_alert(drone,dBm, mac, ssid, channel):
    global drone_img
    frequency = get_frequency(channel)
    distance = get_distance(dBm,frequency)
    distance=round(distance,2)

    text_file = open("logs.txt", "a")
    text_file.write("\n"+str(datetime.datetime.now())+"\t"+mac+"\t"+ssid+"\t"+drone+" DRONE\t~"+str(distance)+"m.")
    text_file.close()
    if mac not in open('ignore.list').read():
        ssid = ssid.split('_')
        Label(f2, text='\n\n ALERT \n ', fg="red",font = "Verdana 10 bold").pack()
        Label(f2, text='\n DRONE '+drone+' '+ssid[0]+' detected in approximately '+str(distance)+' meters \n\n{:%Y-%b-%d %H:%M:%S}'.format(datetime.datetime.now()),font = "Verdana 10 bold").pack()
        image = Image.open("images/"+drone+".png")
        image = image.resize((400, 400), Image.ANTIALIAS)
        drone_img = ImageTk.PhotoImage(image)
        Label(f2, image = drone_img).pack(side = "top", fill = "both", expand = "no")
        Button(f2, text ="Ignore", command = lambda: ignore_it(mac)).pack(padx=255, pady=20, side=LEFT)
        # Button(f2, text ="Deauth", command = lambda: deauth(channel)).pack(padx=5, pady=20, side=LEFT)
        play_sound()
        f2.after(9000, no_drone,f3)
    else:
        f2.after(0, no_drone,f3)
    return
项目:imagepaste    作者:robinchenyu    | 项目源码 | 文件源码
def convert2byte(self, depth=255):
        (minimum, maximum) = self.getextrema()
        m = 1
        if maximum != minimum:
            m = depth / (maximum-minimum)
        b = -m * minimum
        return self.point(lambda i, m=m, b=b: i * m + b).convert("L")

    # returns a ImageTk.PhotoImage object, after rescaling to 0..255
项目:imagepaste    作者:robinchenyu    | 项目源码 | 文件源码
def tkPhotoImage(self):
        from PIL import ImageTk
        return ImageTk.PhotoImage(self.convert2byte(), palette=256)


# --------------------------------------------------------------------
# Image series

# given a list of filenames, return a list of images
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def convert2byte(self, depth=255):
        (minimum, maximum) = self.getextrema()
        m = 1
        if maximum != minimum:
            m = depth / (maximum-minimum)
        b = -m * minimum
        return self.point(lambda i, m=m, b=b: i * m + b).convert("L")

    # returns a ImageTk.PhotoImage object, after rescaling to 0..255
项目:Projects    作者:it2school    | 项目源码 | 文件源码
def tkPhotoImage(self):
        from PIL import ImageTk
        return ImageTk.PhotoImage(self.convert2byte(), palette=256)


# --------------------------------------------------------------------
# Image series

# given a list of filenames, return a list of images
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def __init__(self, master, text, width, foreground="black", truetype_font=None, font_path=None, family=None, size=None, **kwargs):   
        if truetype_font is None:
            if font_path is None:
                raise ValueError("Font path can't be None")

            # Initialize font
            truetype_font = ImageFont.truetype(font_path, size)

        lines = textwrap.wrap(text, width=width)

        width = 0
        height = 0

        line_heights = []
        for line in lines:
            line_width, line_height = truetype_font.getsize(line)
            line_heights.append(line_height)

            width = max(width, line_width)
            height += line_height

        image = Image.new("RGBA", (width, height), color=(0,0,0,0))
        draw = ImageDraw.Draw(image)

        y_text = 0
        for i, line in enumerate(lines):
            draw.text((0, y_text), line, font=truetype_font, fill=foreground)
            y_text += line_heights[i]

        self._photoimage = ImageTk.PhotoImage(image)
        Label.__init__(self, master, image=self._photoimage, **kwargs)
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def convert2byte(self, depth=255):
        (minimum, maximum) = self.getextrema()
        m = 1
        if maximum != minimum:
            m = depth / (maximum-minimum)
        b = -m * minimum
        return self.point(lambda i, m=m, b=b: i * m + b).convert("L")

    # returns a ImageTk.PhotoImage object, after rescaling to 0..255
项目:workflows.kyoyue    作者:wizyoung    | 项目源码 | 文件源码
def tkPhotoImage(self):
        from PIL import ImageTk
        return ImageTk.PhotoImage(self.convert2byte(), palette=256)


# --------------------------------------------------------------------
# Image series

# given a list of filenames, return a list of images
项目:Sorting-Hat    作者:WillSkywalker    | 项目源码 | 文件源码
def __init__(self, hat):
        super(SortingHatGUI, self).__init__()
        self.hat = hat
        self.title('???')
        self.configure(bg='#000000')

        title_image = ImageTk.PhotoImage(Image.open('resources/hat.jpg'))
        banner = tk.Label(self, image=title_image)
        banner.image = title_image
        banner.grid(columnspan=3)

        self.initial_screen(init=True)

        self.resizable(width=False, height=False)
        threading.Thread(target=play_hedwig_theme, daemon=True).start()