def generate_image(image_url, part_uid, connected, lock=None): if lock is not None: lock.acquire() if image_url == "locallystored": if os.path.isfile( str(Path.home()) + "/Barnyard-2/" + part_uid + ".jpg"): path = str(Path.home()) + "/Barnyard-2/" + part_uid + ".jpg" return_value = AsyncImage(source=path) else: path = str(Path.home()) + "/Barnyard-2/" + part_uid + ".png" return_value = AsyncImage(source=path) elif connected: return_value = AsyncImage(source=image_url) else: # Offline mode: get downloaded image on hdd path = str(Path.home() ) + "/Barnyard-2/" + "downloaded_" + part_uid + ".png" print(path) return_value = AsyncImage(source=path) if lock is not None: lock.release() return return_value
class NowPlayingScreen(GridLayout): def __init__(self, cc, **kwargs): super(NowPlayingScreen, self).__init__(**kwargs) self.cols = 3 time.sleep(1) self.track_artist = Label(text=cc.media_controller.status.artist) self.track_title = Label(text=cc.media_controller.status.title) image = next(i for i in cc.media_controller.status.images if i.height > 500) self.album_art = AsyncImage(source=image.url) # Add the UI elements to the layout: self.add_widget(self.track_artist) self.add_widget(self.track_title) self.add_widget(self.album_art) def update_track_title(self, text): self.track_title.text = text def update_track_artist(self, text): self.track_artist.text = text def update_album_art(self, media_images): self.album_art.source = \ next(i for i in media_images if i.height > 500).url self.album_art.reload()
def __init__(self, *args, **kwargs): super(PhotoStrip, self).__init__(size_hint=(1, 1), pos_hint={ 'center_x': 0.5, 'center_y': 0.5 }, do_scroll_x=False, *args, **kwargs) self.register_event_type('on_press') self.register_event_type('on_release') self.strip = AsyncImage(source='photos-strip.png', allow_stretch=True, size_hint_y=1.8) self.add_widget(self.strip) self.image0 = image_button() self.image0.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image0) self.image1 = image_button() self.image1.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image1) self.image2 = image_button() self.image2.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image2) self.image3 = image_button() self.image3.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image3) self.strip.bind(size=self.update_buttons, pos=self.update_buttons)
def build(self): root = RootWidget() c = CustomLayout() root.add_widget(c) c.add_widget( AsyncImage( source= "http://www.znh.tw/rapa/wp-content/uploads/2016/02/11080927_1604252076479061_6424375858444252074_n-540x600.jpg", size_hint=(1, .5), pos_hint={ 'center_x': .5, 'center_y': .5 })) root.add_widget( AsyncImage( source= 'http://www.znh.tw/rapa/wp-content/uploads/2016/02/11080927_1604252076479061_6424375858444252074_n-540x600.jpg' )) c = CustomLayout() c.add_widget( AsyncImage( source= "http://www.znh.tw/rapa/wp-content/uploads/2016/02/11080927_1604252076479061_6424375858444252074_n-540x600.jpg", size_hint=(1, .5), pos_hint={ 'center_x': .5, 'center_y': .5 })) root.add_widget(c) return root
def build(self): # TODO: add a layout like this (that actually works) #self.layout = BoxLayout(orientation='vertical', spacing=10) col = Widget() self.image = AsyncImage(allow_stretch=True, keep_ratio=False, size=(480, 480)) # call this function once to load the first image self.nextImage(self) scatter = Scatter(do_rotation=False, auto_bring_to_front=False, size=self.image.get_norm_image_size()) scatter.add_widget(self.image) col.add_widget(scatter) button = Button(text='Next', size_hint=(1.0, 0.1)) button.bind(on_press=self.buttonPressed) button.bind(on_release=self.nextImage) col.add_widget(button) return col
def show_images(self): # image_list must always contain camera_icon, otherwise image_list[0] in <Images> fails copy_list = [im for im in app.daten.image_list if not im[0].endswith(utils.camera_icon)] l = len(copy_list) if l == 0: app.do_capture() return elif l == 1: t = copy_list[0] if t[1] is None: self.show_single_image(t[0]) else: maxdim = self.app.getConfigValue("maxdim", 1024) if self.app.useGoogle: im = self.app.gphoto.getImage(t[1], maxdim) else: im = self.app.serverIntf.getImage(t[1], maxdim) if im is None: self.app.message("Kann Bild nicht laden") else: self.show_single_image(im) return self.bl.clear_widgets() for i, cp in enumerate(copy_list): im = AsyncImage(source=cp[0], on_touch_down=self.show_single_image) im.size = app.root.sm.size im.mediaId = cp[1] im.number = i # without auto_bring_to_front=False the boxlayout children are reshuffled sc = Scatter(do_rotation=False, do_translation=False, do_scale=False, size=im.size, auto_bring_to_front=False, size_hint=(None, None)) sc.add_widget(im) self.bl.add_widget(sc)
def build(self): root = RootWidget() c = CustomLayout() root.add_widget(c) c.add_widget( AsyncImage( source= "F:/Photos/Favourite personalities/FB_IMG_1566583215036.jpg", size_hint=(1, .5), pos_hint={ 'center_x': .5, 'center_y': .5 })) root.add_widget( AsyncImage( source= 'F:/Photos/Favourite personalities/FB_IMG_1570087505868.jpg')) c = CustomLayout() c.add_widget( AsyncImage( source= "F:/Photos/Favourite personalities/FB_IMG_1571324704011.jpg", size_hint=(1, .5), pos_hint={ 'center_x': .5, 'center_y': .5 })) root.add_widget(c) return root
def build(self): root = RootWidget() c = CustomLayout() root.add_widget(c) c.add_widget( AsyncImage(source="./Q版野餐.jpg", size_hint=(1, .5), pos_hint={ 'center_x': .5, 'center_y': .5 })) root.add_widget( AsyncImage(source='./P_主頁示意圖.jpg') ) #http://www.stuffistumbledupon.com/wp-content/uploads/2012/05/Have-you-seen-this-dog-because-its-awesome-meme-puppy-doggy.jpg')) c = CustomLayout() c.add_widget( AsyncImage( source= "http://www.stuffistumbledupon.com/wp-content/uploads/2012/04/Get-a-Girlfriend-Meme-empty-wallet.jpg", size_hint=(1, .5), pos_hint={ 'center_x': .5, 'center_y': .5 })) root.add_widget(c) return root
def load_zipimage(self, source, frames): # keep running the test until loaded (or timeout) maxfps = self.maxfps timeout = 30 * maxfps # load ZIP with images named: 000.png, 001.png, ... image = AsyncImage( source=source, anim_delay=0.0333333333333333 ) image.test_loaded = False self.render(image) # bind to 'on_load' because there are various # steps where the image is (re)loaded, but # the event is triggered only at the end image.bind(on_load=lambda *_, **__: setattr( image, 'test_loaded', True )) while timeout and not image.test_loaded: self.advance_frames(1) timeout -= 1 proxyimg = image._coreimage self.assertTrue(proxyimg.anim_available) self.assertEqual(len(proxyimg.image.textures), frames) return image
def __init__(self, title='', duration='', thumbnail='', source_videos=None, source_audios=None, **kwargs): super(YoutubeDisplayLayout, self).__init__(**kwargs) info_box = BoxLayout(orientation='vertical') self.source_videos = source_videos self.source_audios = source_audios self.title = TextInput( text=title ) # text input canvas clear when its removed, make an error self.duration = Label(text=str(duration)) info_box.add_widget(self.title) info_box.add_widget(self.duration) self.thumbnail = AsyncImage(source=thumbnail, size_hint=(.2, 1)) self.add_widget(self.thumbnail) self.add_widget(info_box) self.register_event_type('on_click') with self.canvas.before: self.color = Color(rgba=(0, 0, 0, 0)) self.rect = Rectangle(size=self.size, pos=self.pos) self.bind(pos=self.updateRect, size=self.updateRect)
def draw(self): from matplotlib import transforms from PIL import Image as pImage from PIL import ImageOps # tr = transforms.Affine2D().rotate_deg(90) # buf = io.BytesIO() # plt.ion() from comrad.constants import PATH_MAPS odir=PATH_MAPS if not os.path.exists(odir): os.makedirs(odir) ofn=os.path.join(odir,f't_{len(self.points)}.png') # plt.gca().invert_yaxis() plt.savefig(ofn, format='png',transparent=True,pad_inches=0.1,bbox_inches = 'tight') # flip? # im = pImage.open(ofn) # im = im.rotate(90) # im.save(ofn) if not self.img: self.img= AsyncImage(source=ofn) self.img.background_color=(0,0,0,0) self.img.overlay_color=(0,0,0,0) # self.img.texture.flip_horizontal() self.img.pos_hint={'center_x':0.48,'center_y':0.5} # self.img.size=Window.size # self.img.texture = img self.img.add_widget(self.label_layout,1) self.layout.add_widget(self.img,1) else: self.img.source=ofn
def __init__(self): super(Condiciones, self).__init__() self.flag = 1 self.DI = AsyncImage(size_hint=(1, 10), source=resource_path('img/Dirichlet.png')) self.NE = AsyncImage(size_hint=(1, 10), source=resource_path('img/Neumann.png')) self.add_widget(self.DI)
def Nprepare_gallery(self): img_sl = self.ids.details.ids.img_sl from kivy.uix.image import AsyncImage for img, href in self.images: IMG = AsyncImage(source=href) IMG.large_src = href.replace('_mt', '') IMG.large_name = img img_sl.add_widget(IMG)
def __init__(self, *args, **kwargs): super(MainBox, self).__init__(**kwargs) #~ video = Video(source='http://163.10.10.103', play=True) self.video = AsyncImage( source= 'http://*****:*****@163.10.10.103/cgi-bin/viewer/video.jpg', nocache=True) self.add_widget(self.video) Clock.schedule_interval(self.refresh, 1)
class ShowAPhoto(BoxLayout): def __init__(self, **kwargs): super(ShowAPhoto,self).__init__(**kwargs) self.prepare_image_list() self.add_image_widget() self.register_keydown_event() def prepare_image_list(self): if(images_finder.is_images_contained(sys.argv)) : image_arg = images_finder.find_fist_images_in_list(sys.argv) self.prepare_list(image_arg) else: self.prepare_list('./') def add_image_widget(self): self.aimage = AsyncImage(source=self.get_next_file()) self.aimage.bind(source=self._on_image_load) self.add_widget(self.aimage) def register_keydown_event(self): self._keyboard = Window.request_keyboard(self._keyboard_closed, self, 'text') self._keyboard.bind(on_key_down=self._on_keyboard_down) def _on_image_load(self,image,source): self.set_app_title(source) def set_app_title(self, title): EventLoop.window.title = title def prepare_list(self,filepath): folderpath = os.path.dirname(filepath)+'/' file_list = images_finder.list_all_images_in_folder(folderpath) iterator= bidirection_iterator.BidirectionIterator(file_list) if filepath != './': iterator.move_before(filepath) self.file_iterator = iterator def get_next_file(self): return self.file_iterator.next() def get_previous_file(self): return self.file_iterator.previous() def _keyboard_closed(self): print('My keyboard have been closed') self._keyboard.unbind(on_key_down=self._on__keyboard_down) self._keyboard = None def _on_keyboard_down(self, keyboard, keycode, text, modifiers): if keycode[1] == 'left': self.aimage.source = self.get_previous_file() else: self.aimage.source = self.get_next_file()
def build(self): fig, ax = plt.subplots(figsize=(8, 3.9)) self.filename = (self.user_data_dir + "/test.png") plt.plot([1, 2, 3], [1, 2, 3]) plt.savefig(self.filename) plt.clf() # cla for multiple subplots layout = GridLayout(rows=3, padding=[0, 0, 0, -1]) # grid on top 1 row self.top_grid = GridLayout(cols=5, size_hint_y=(.15), padding=[0, 0, 0, -1]) # Button for loading data load_btn = Button(text="Load Data") load_btn.bind(on_press=self.load) self.top_grid.add_widget(load_btn) # Button for setting x column self.x_btn = Button(text="x column") self.top_grid.add_widget(self.x_btn) # Button for setting y column multi-line selection self.y_btn = Button(text="y column") self.top_grid.add_widget(self.y_btn) # Button for plotting self.plot_btn = Button(text="Plot it") self.plot_btn.bind(on_press=self.plot) self.top_grid.add_widget(self.plot_btn) # Button for layout.add_widget(self.top_grid) self.img = AsyncImage(source=self.filename, nocache=True) layout.add_widget(self.img) # grid on bottom 1 row self.bottom_grid = GridLayout(cols=5, size_hint_y=(.15), padding=[0, 0, 0, -1]) # Button for share button # Button for color scheme layout.add_widget(self.bottom_grid) # self.btn = Button( # text='change', # size_hint=(None, None)) # self.btn.bind(on_press=self.callback) # layout.add_widget(self.btn) return layout
def __init__(self, source, **kwargs): super().__init__(**kwargs) self.image = AsyncImage() self.loader_clock = Clock.schedule_interval(self.adjust_size, self.image.anim_delay) self.image.bind(on_load=lambda inst: ( self.adjust_size(), self.loader_clock.cancel(), )) self.source = source self.bind(size=self.adjust_size, pos=self.adjust_size)
class Container(Widget): source = ObjectProperty() image = ObjectProperty() def __init__(self, source, **kwargs): super().__init__(**kwargs) self.image = AsyncImage() self.loader_clock = Clock.schedule_interval(self.adjust_size, self.image.anim_delay) self.image.bind(on_load=lambda inst: ( self.adjust_size(), self.loader_clock.cancel(), )) self.source = source self.bind(size=self.adjust_size, pos=self.adjust_size) def on_source(self, instance, value): if isinstance(value, str): self.image.source = value else: self.image.texture = value self.adjust_size() def adjust_size(self, *args): if not self.parent or not self.image.texture: return (par_x, par_y) = self.parent.size if par_x == 0 or par_y == 0: with self.canvas: self.canvas.clear() return par_scale = par_x / par_y (img_x, img_y) = self.image.texture.size img_scale = img_x / img_y if par_scale > img_scale: (img_x_new, img_y_new) = (img_x, img_x / par_scale) else: (img_x_new, img_y_new) = (img_y * par_scale, img_y) crop_pos_x = (img_x - img_x_new) / 2 crop_pos_y = (img_y - img_y_new) / 2 subtexture = self.image.texture.get_region(crop_pos_x, crop_pos_y, img_x_new, img_y_new) with self.canvas: self.canvas.clear() Color(1, 1, 1) Rectangle(texture=subtexture, pos=self.pos, size=(par_x, par_y))
def create_recipe(self): content = self.manager.children[0].children[-1].children[0].children[0] if self.recipe_info['name'] in PreviewScreenBoxLayout.favorites: FavoriteButton.status = FavoriteButton.fav else: FavoriteButton.status = FavoriteButton.not_fav self.manager.children[0].children[-1].children[-1].children[ -2].children[0].source = FavoriteButton.status content.children[-1].height = 300 content.children[-1].children[0].clear_widgets() content.children[-1].children[0].add_widget( AsyncImage( source= f'img/img_for_recipes/{self.recipe_info["img_folder_name"]}')) content.children[-1].children[0].add_widget( AsyncImage( source= f'img/img_for_recipes/1_{self.recipe_info["img_folder_name"]}') ) content.children[-1].children[0].add_widget( AsyncImage( source= f'img/img_for_recipes/2_{self.recipe_info["img_folder_name"]}') ) content.children[-2].text = self.recipe_info['name'] content.children[-4].text = self.recipe_info['history'] content.children[-4].text_size = [Window.width, None] content.children[-4].texture_update() content.children[-4].size = content.children[-4].texture_size content.children[-4].texture_update() text_instr = 'Инструкция к приготовлению:\n\n' + self.recipe_info[ 'instruction'] text_instr = text_instr.replace(r'<\n>', '\n') content.children[-6].text = text_instr content.children[-6].text_size = [Window.width, None] content.children[-6].texture_update() content.children[-6].size = content.children[-6].texture_size content.children[-6].texture_update() content.children[-8].text = self.recipe_info['advice'] content.children[-8].text_size = [Window.width, None] content.children[-8].texture_update() content.children[-8].size = content.children[-8].texture_size content.children[-8].texture_update() content.height = sum(x.height for x in content.children)
class PhotoStrip(ScrollView): def on_press(self, filename): pass def on_release(self, filename): pass def __init__(self, *args, **kwargs): super(PhotoStrip, self).__init__(size_hint=(1,1), pos_hint={'center_x': 0.5, 'center_y': 0.5}, do_scroll_x=False, *args, **kwargs) self.register_event_type('on_press') self.register_event_type('on_release') self.strip = AsyncImage(source='photos-strip.png', allow_stretch=True, size_hint_y=1.8) self.add_widget(self.strip) self.image0 = image_button() self.image0.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image0) self.image1 = image_button() self.image1.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image1) self.image2 = image_button() self.image2.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image2) self.image3 = image_button() self.image3.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image3) self.strip.bind(size=self.update_buttons,pos=self.update_buttons) def set_path(self, path): print path path = filesystem.normpath(path) print path self.scroll_y = 1 if 'effect_y' in dir(self): # Kivy 1.6.0 doesn't have effect_y self.effect_y.value = self.effect_y.min # This is to work around a bug with the ScrollView (https://github.com/kivy/kivy/issues/2038) self.image0.source = filesystem.join(path, '0.jpg') self.image1.source = filesystem.join(path, '1.jpg') self.image2.source = filesystem.join(path, '2.jpg') self.image3.source = filesystem.join(path, 'blank') def press_btn(self, btn): self.dispatch('on_press', btn.source) def release_btn(self, btn): self.dispatch('on_release', btn.source) def update_buttons(self, instance, value): spacing = 20 padding = 25 offset = padding for img in [self.image0, self.image1, self.image2, self.image3]: img.size = (instance.norm_image_size[0]/60)*43, (instance.norm_image_size[1]-((spacing*3)+(padding*2)))/4 img.center_x = instance.center_x img.center_y = instance.top-((img.height/2)+offset) offset += img.height+spacing
def callback(self): def update_height(img, *args): img.height = img.width / img.image_ratio dirpath = sys.argv[1] files = glob.glob(os.path.join(dirpath, '*.*')) btn = Button(text="Test", size_hint_y=None, height=100) btn.bind(on_press= lambda x: Popen('python LCDNet.py')) self.ids.wall.add_widget(btn) for f in files: image = AsyncImage(source=f, size_hint=(1, None), keep_ratio=True, allow_stretch=True) image.bind(width=update_height, image_ratio=update_height) self.ids.wall.add_widget(image)
def build(self): layout = GridLayout(cols=2, row_force_default=True, row_default_height=40) #layout = BoxLayout(orientation="vertical", spacing=10, padding=40) label = Label(text=" This is a Universal App", font_size="28sp", bold=True, color=(0, 0, 0, 1), italic=True) button = Button( text="Print this", font_size="20sp", size_hint=(0.2, 0.2), pos_hint={ 'center_x': 0.8, "center_y": 0.8 }, on_press=self.printpress, on_release=self.printrelease, ) img = AsyncImage( source="http://cdn3.sbnation.com/assets/3786371/DOGE-12.jpg") message = TextInput(text="Enter you message here") layout.add_widget(label) layout.add_widget(button) layout.add_widget(img) layout.add_widget(message) return layout
def build(self): carousel = Carousel(direction='right') for i in range(10): src = "http://placehold.it/480x270.png&text=slide-%d&.png" % i image = AsyncImage(source=src, allow_stretch=True) carousel.add_widget(image) return carousel
class TestApp(App): i = 0 img = AsyncImage(size_hint=(1, 0.9), source=src[i], keep_ratio=False) img.source = src[2] def alert(self, msg): popup = Popup(title='Hi', content=Label(text=msg), size_hint=(0.5, .2)) popup.open() def press(self, btn): if btn.id == '1' and self.i < (len(src) - 1): self.i += 1 self.img.source = src[self.i] elif btn.id == '2' and self.i > 0: self.i -= 1 self.img.source = src[self.i] elif btn.id == '3': self.img.allow_stretch = btn.state == 'down' elif btn.id == '4': self.img.keep_ratio = btn.state == 'down' def build(self): layout = BoxLayout(orientation='vertical') btns = BoxLayout(orientation='horizontal', size_hint=(1, 0.1)) btns.add_widget(Button(text='>>>', id='1', on_press=self.press)) btns.add_widget(Button(text='<<<', id='2', on_press=self.press)) btns.add_widget( ToggleButton(text='Stretch', id='3', on_press=self.press)) btns.add_widget(ToggleButton(text='Ratio', id='4', on_press=self.press)) layout.add_widget(self.img) layout.add_widget(btns) return layout
def __init__(self): super(Ensamblaje, self).__init__() self.i = 1 self.MG = AsyncImage(size_hint=(1, 10), source=resource_path('img/Ensamblaje' + str(self.i) + '.png')) self.add_widget(self.MG)
def build(self): #img = Image(source='boo.jpg') img = AsyncImage( source= 'https://inteng-storage.s3.amazonaws.com/img/iea/y5wWnBlP6X/sizes/ai-main_resize_md.jpg' ) return img
def associate_tag(self, instance): for entry in self._entry_list: self._box_layout.remove_widget(entry) self._box_layout.remove_widget(self._tag_association_button) for text_box_label in self._text_box_labels: self._box_layout.remove_widget(text_box_label) if self._part_info.uid is None: self._association_label_image = AsyncImage(source=os.getcwd() + "/tap.png") self._association_label = Label( text="Tap an NFC tag now to associate") self._box_layout.add_widget(self._association_label_image) self._box_layout.add_widget(self._association_label) _thread.start_new_thread(self._get_next_nfc_tag_uid, ()) else: try: uid_sheet_info_modifier = UidSheetInfoModifier() except: # No connection... Use CSV Backup uid_sheet_info_modifier = UidCsvInfoModifier() self._update_part_info() uid_sheet_info_modifier.add_part(self._part_info) self.go_back()
def load_zipimage(self, source, frames): # load ZIP with images named: 000.png, 001.png, ... from kivy.uix.image import AsyncImage event = Event() image = AsyncImage(anim_delay=0.0333333333333333) # bind to 'on_load' because there are various # steps where the image is (re)loaded, but # the event is triggered only at the end image.bind(on_load=lambda *args, **kwargs: event.set()) image.source = source self.wait_for_event_or_timeout(event) self.render(image) proxyimg = image._coreimage self.assertTrue(proxyimg.anim_available) self.assertEqual(len(proxyimg.image.textures), frames) return image
def list_files(self, name): print('display thread') self.ids.grid.clear_widgets() self.ids.spinner.active = True url = 'http://point3hub.com/mcroni/albums/' try: r = requests.get(url) except requests.packages.urllib3.exceptions.ProtocolError: print('cant connect') self.ids.spinner.active = False img = AsyncImage(source='network.png', keep_ratio=False, allow_stretch=True) self.ids.grid.add_widget(img) else: r = requests.get(url) data = r.text soup = BeautifulSoup(data, 'html.parser') for link in soup.find_all('a'): if link.get('href').endswith('.jpg'): self.passed.append(link.get('href')) self.ids.spinner.active = False # print(self.passed) for pic in self.passed: src = 'http://point3hub.com/mcroni/albums/{}'.format(pic) print(src) # self.p.append(src) self.album = SM(source=str(src)) self.ids.grid.clear_widgets() self.ids.grid.add_widget(self.album) self.ids.spinner.active = False
def select_all_tasks(self, conn): """This method performs a select all SQL statment and populates the BoxLayout With the Button, Label and AsyncPicture widgets.""" cur = conn.cursor( ) #create sqlite cursor object allowing sql statements to be executed cur.execute("SELECT * FROM manga_list") db_list = cur.fetchall( ) #creates list of manga_list table allowing for loop to run and populate the BoxLayout for row in db_list: """Label widget generated with font 30px and markup property. The markup allows the func. populate_delete_row to run when label is pressed""" lbl = Label(text='[ref=' ']' + row[1] + '[/ref]', id=row[1], font_size=30, markup=True, on_ref_press=self.populate_delete_row) pic = AsyncImage( source='images/' + row[3] ) #picture widgetmade with image address given by user located in col 3 btn = Button(text='OPEN WEBPAGE', size_hint_y=None, id=row[2]) #button widget btn.bind( on_release=self.open_url ) #gives btn widget action to run open_url method when pressed #The below is used to place the newly declared widgets onto the BoxLayout self.ids.grid.add_widget(lbl) self.ids.grid.add_widget(pic) self.ids.grid.add_widget(btn)
def load_images(self, *args): with self.canvas: for x in range(0, 2): for y in range(0, 2): source="http://b.tile.openstreetmap.org/1/%s/%s.png" % (x, y) r = 256 / self.scale AsyncImage(source=source, mipmap=False, allow_stretch=True, pos=(x*256 , (1-y)*256), size=(r, r))
def on_index(self, instance, value): if self.media: if isinstance(self.media, Video): self.media.play = False self.media = None value = value % len(self.item.medias) media = self.item.medias[value] name, ext = splitext(media) ext = ext[1:].lower() # convert media url to local media path (all medias are already downloaded) from museolib.utils import no_url media = join(self.parent.parent.parent.parent.app.expo_dir, 'otherfiles', no_url(media)) if not isfile(media): print " ### Oops, this media is not downloaded !" try: if ext in ('mp3', 'ogg', 'flac', 'wav'): w = Label(text="It's a song : " + media) if not isfile(media): w = Label(text="Song not downloaded.") elif ext in ('avi', 'mkv', 'mp4', 'ogv', 'mpg', 'mpeg', 'dv'): w = Video(source=media, play=True) else: w = AsyncImage(source=media) except: w = Label(text='Unable to read that media') self.content.clear_widgets() self.content.add_widget(w) self.media = w
def test_reload_asyncimage(self): from kivy.resources import resource_find from tempfile import mkdtemp from os import symlink, unlink from shutil import rmtree fn = resource_find('data/logo/kivy-icon-16.png') t = mkdtemp() source = join(t, 'source.png') symlink(fn, source) image = AsyncImage(source=source) self.render(image, framecount=2) self.assertEqual(image.texture_size, [16, 16]) unlink(source) fn = resource_find('data/logo/kivy-icon-32.png') symlink(fn, source) image.reload() self.render(image, framecount=2) self.assertEqual(image.texture_size, [32, 32]) unlink(source) rmtree(t)
def __init__(self, *args, **kwargs): super(PhotoStrip, self).__init__(size_hint=(1,1), pos_hint={'center_x': 0.5, 'center_y': 0.5}, do_scroll_x=False, *args, **kwargs) self.register_event_type('on_press') self.register_event_type('on_release') self.strip = AsyncImage(source='photos-strip.png', allow_stretch=True, size_hint_y=1.8) self.add_widget(self.strip) self.image0 = image_button() self.image0.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image0) self.image1 = image_button() self.image1.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image1) self.image2 = image_button() self.image2.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image2) self.image3 = image_button() self.image3.bind(on_press=self.press_btn, on_release=self.release_btn) self.strip.add_widget(self.image3) self.strip.bind(size=self.update_buttons,pos=self.update_buttons)
def build(self): # TODO: add a layout like this (that actually works) #self.layout = BoxLayout(orientation='vertical', spacing=10) col = Widget() self.image = AsyncImage(allow_stretch=True, keep_ratio=False, size=(480,480)) # call this function once to load the first image self.nextImage(self) scatter = Scatter(do_rotation=False, auto_bring_to_front=False, size=self.image.get_norm_image_size()) scatter.add_widget(self.image) col.add_widget(scatter) button = Button(text='Next', size_hint=(1.0, 0.1)) button.bind(on_press=self.buttonPressed) button.bind(on_release=self.nextImage) col.add_widget(button) return col
def add_image_widget(self): self.aimage = AsyncImage(source=self.get_next_file()) self.aimage.bind(source=self._on_image_load) self.add_widget(self.aimage)
class HorseShoe(App): def getJSONIterator(self, subReddit): theJsonUrl = urllib.urlopen(urlBase + subReddit + '/top/.json') jsonString = theJsonUrl.read() theJsonUrl.close() print jsonString parsed = json.loads(jsonString) print "Done" next = parsed["data"]["after"] items = parsed["data"]["children"] items = [item for item in items if item["data"]["domain"] == 'imgur.com' or item["data"]["domain"] == 'i.imgur.com'] self.items = items numItems = len(items) print "Got JSON with " + str(numItems) + " items " for item in self.items: if item is None: print "Item is NOne!" else: print "Returning next item: " + item["data"]["title"] yield item def buttonPressed(self, params): print "Pressed Button", params def nextImage(self, params): print "Relased Button", params if not hasattr(self, 'items'): print "Getting JSON" self.iterator = self.getJSONIterator('fffffffuuuuuuuuuuuu') try: nextItem = self.iterator.next() except StopIteration: print "Ran out of iterators!" sys.exit(0) itemUrl = nextItem["data"]["url"] if (itemUrl.find('.png') == -1) and (itemUrl.find('.jpg') == -1): itemUrl += ".jpg" print itemUrl self.image.source = itemUrl def build(self): # TODO: add a layout like this (that actually works) #self.layout = BoxLayout(orientation='vertical', spacing=10) col = Widget() self.image = AsyncImage(allow_stretch=True, keep_ratio=False, size=(480,480)) # call this function once to load the first image self.nextImage(self) scatter = Scatter(do_rotation=False, auto_bring_to_front=False, size=self.image.get_norm_image_size()) scatter.add_widget(self.image) col.add_widget(scatter) button = Button(text='Next', size_hint=(1.0, 0.1)) button.bind(on_press=self.buttonPressed) button.bind(on_release=self.nextImage) col.add_widget(button) return col