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()
python类PhotoImage()的实例源码
SlideShow_Pillow.py 文件源码
项目:Python-GUI-Programming-Cookbook-Second-Edition
作者: PacktPublishing
项目源码
文件源码
阅读 29
收藏 0
点赞 0
评论 0
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.
#
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)
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.
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)
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()
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)
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()
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()
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()
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
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()
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()
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)
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")
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
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()
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)
def setupApp(self):
print("Setting up main window...")
self.icon_base64 = {
'app' : """iVBORw0KGgoAAAANSUhEUgAAADAAAAAw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SuQmCC""",
}
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')
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
def setupApp(self):
print("Setting up main window...")
self.icon_base64 = {
'app' : """iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAp0lEQVRo3u3aoQ0CURBF0fsJ0A0VUMM2gFmFRBAIBr2GQBBI1BoaoAYqoBsQgyCIZR2CZJL75ORn/jt+SkQEiTMEKKWkLB8RbwBAPZ0AcFg+AVgdR53Hj3nDYr/htN71Fl3q6qcCs/bam33+GJ+3n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xDCcr9r5wuVEKolJAPYvBbWGgxJnFpKQAAAK6GVhNERMIXJSLtXFa+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')
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
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)
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 ------------------
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
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)
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))
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
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', '')
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)