Python tkinter.PhotoImage() Examples

The following are 30 code examples of tkinter.PhotoImage(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tkinter , or try the search function .
Example #1
Source File: window.py    From LPHK with GNU General Public License v3.0 8 votes vote down vote up
def popup(self, window, title, image, text, button_text, end_command=None):
        popup = tk.Toplevel(window)
        popup.resizable(False, False)
        if MAIN_ICON != None:
            if os.path.splitext(MAIN_ICON)[1].lower() == ".gif":
                dummy = None
                #popup.call('wm', 'iconphoto', popup._w, tk.PhotoImage(file=MAIN_ICON))
            else:
                popup.iconbitmap(MAIN_ICON)
        popup.wm_title(title)
        popup.tkraise(window)

        def run_end():
            popup.destroy()
            if end_command != None:
                end_command()

        picture_label = tk.Label(popup, image=image)
        picture_label.photo = image
        picture_label.grid(column=0, row=0, rowspan=2, padx=10, pady=10)
        tk.Label(popup, text=text, justify=tk.CENTER).grid(column=1, row=0, padx=10, pady=10)
        tk.Button(popup, text=button_text, command=run_end).grid(column=1, row=1, padx=10, pady=10)
        popup.wait_visibility()
        popup.grab_set()
        popup.wait_window() 
Example #2
Source File: ChessView.py    From cchess-zero with MIT License 6 votes vote down vote up
def draw_board(self, board):
        self.piece_images.clear()
        self.move_images = []
        pieces = board.pieces
        for (x, y) in pieces.keys():
            self.piece_images[x, y] = tkinter.PhotoImage(file=pieces[x, y].get_image_file_name())
            self.can.create_image(board_coord(x), board_coord(y), image=self.piece_images[x, y])
        if board.selected_piece:
            for (x, y) in board.selected_piece.get_move_locs(board):
                self.move_images.append(tkinter.PhotoImage(file="images/OOS.gif"))
                self.can.create_image(board_coord(x), board_coord(y), image=self.move_images[-1])
                # self.can.create_text(board_coord(x), board_coord(y),text="Hello")

        # label = tkinter.Label(self.root, text='Hello world!')
        # label.place(x=30,y=30)
        # label.pack(fill='x', expand=1) 
Example #3
Source File: friendslist.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def load_friends(self):
        all_users = self.requester.get_all_users()

        for user in all_users:
            if user['username'] != self.username:
                friend_frame = ttk.Frame(self.canvas_frame)

                profile_photo = tk.PhotoImage(file="images/avatar.png")
                profile_photo_label = ttk.Label(friend_frame, image=profile_photo)
                profile_photo_label.image = profile_photo

                friend_name = ttk.Label(friend_frame, text=user['real_name'], anchor=tk.W)

                message_this_friend = partial(self.open_chat_window, username=user["username"], real_name=user["real_name"])

                message_button = ttk.Button(friend_frame, text="Chat", command=message_this_friend)

                profile_photo_label.pack(side=tk.LEFT)
                friend_name.pack(side=tk.LEFT)
                message_button.pack(side=tk.RIGHT)

                friend_frame.pack(fill=tk.X, expand=1) 
Example #4
Source File: friendslist.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def load_friends(self):
        friend_frame = ttk.Frame(self.canvas_frame)

        profile_photo = tk.PhotoImage(file="images/avatar.png")
        profile_photo_label = ttk.Label(friend_frame, image=profile_photo)
        profile_photo_label.image = profile_photo

        friend_name = ttk.Label(friend_frame, text="Jaden Corebyn", anchor=tk.W)

        message_button = ttk.Button(friend_frame, text="Chat", command=self.open_chat_window)

        profile_photo_label.pack(side=tk.LEFT)
        friend_name.pack(side=tk.LEFT)
        message_button.pack(side=tk.RIGHT)

        friend_frame.pack(fill=tk.X, expand=1) 
Example #5
Source File: smilieselect.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def __init__(self, master, **kwargs):
        super().__init__(**kwargs)
        self.master = master
        self.transient(master)
        self.position_window()

        smilie_files = [file for file in os.listdir(self.smilies_dir) if file.endswith(".png")]

        self.smilie_images = []

        for file in smilie_files:
            full_path = os.path.join(self.smilies_dir, file)
            image = tk.PhotoImage(file=full_path)
            self.smilie_images.append(image)

        for index, file in enumerate(self.smilie_images):
            row, col = divmod(index, 3)
            button = ttk.Button(self, image=file, command=lambda s=file: self.insert_smilie(s))
            button.grid(row=row, column=col, sticky='nsew')

        for i in range(3):
            tk.Grid.columnconfigure(self, i, weight=1)
            tk.Grid.rowconfigure(self, i, weight=1) 
Example #6
Source File: _backend_tk.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
def _Button(self, text, image_file, toggle, frame):
        if image_file is not None:
            im = Tk.PhotoImage(master=self, file=image_file)
        else:
            im = None

        if not toggle:
            b = Tk.Button(master=frame, text=text, padx=2, pady=2, image=im,
                          command=lambda: self._button_click(text))
        else:
            # There is a bug in tkinter included in some python 3.6 versions
            # that without this variable, produces a "visual" toggling of
            # other near checkbuttons
            # https://bugs.python.org/issue29402
            # https://bugs.python.org/issue25684
            var = Tk.IntVar()
            b = Tk.Checkbutton(master=frame, text=text, padx=2, pady=2,
                               image=im, indicatoron=False,
                               command=lambda: self._button_click(text),
                               variable=var)
        b._ntimage = im
        b.pack(side=Tk.LEFT)
        return b 
Example #7
Source File: smilieselect.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def __init__(self, master, **kwargs):
        super().__init__(**kwargs)
        self.master = master
        self.transient(master)
        self.position_window()

        smilie_files = [file for file in os.listdir(self.smilies_dir) if file.endswith(".png")]

        self.smilie_images = []

        for file in smilie_files:
            full_path = os.path.join(self.smilies_dir, file)
            image = tk.PhotoImage(file=full_path)
            self.smilie_images.append(image)

        for index, file in enumerate(self.smilie_images):
            row, col = divmod(index, 3)
            button = ttk.Button(self, image=file, command=lambda s=file: self.insert_smilie(s))
            button.grid(row=row, column=col, sticky='nsew')

        for i in range(3):
            tk.Grid.columnconfigure(self, i, weight=1)
            tk.Grid.rowconfigure(self, i, weight=1) 
Example #8
Source File: SlideShow_try_jpg.py    From Python-GUI-Programming-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
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
        # try: .jpeg
        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((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() 
Example #9
Source File: SlideShow.py    From Python-GUI-Programming-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
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')]

        # endlessly read in the slides so we can show them on the tkinter Label 
        chdir(resources_folder)
        self.iterableCycle = cycle((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() 
Example #10
Source File: _backend_tk.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
def _Button(self, text, image_file, toggle, frame):
        if image_file is not None:
            im = tk.PhotoImage(master=self, file=image_file)
        else:
            im = None

        if not toggle:
            b = tk.Button(master=frame, text=text, padx=2, pady=2, image=im,
                          command=lambda: self._button_click(text))
        else:
            # There is a bug in tkinter included in some python 3.6 versions
            # that without this variable, produces a "visual" toggling of
            # other near checkbuttons
            # https://bugs.python.org/issue29402
            # https://bugs.python.org/issue25684
            var = tk.IntVar()
            b = tk.Checkbutton(master=frame, text=text, padx=2, pady=2,
                               image=im, indicatoron=False,
                               command=lambda: self._button_click(text),
                               variable=var)
        b._ntimage = im
        b.pack(side=tk.LEFT)
        return b 
Example #11
Source File: wicc_view_splash.py    From WiCC with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self):
        root = tk.Tk()
        # show no frame
        root.overrideredirect(True)

        # get screen width and height
        ws = root.winfo_screenwidth()
        hs = root.winfo_screenheight()
        # calculate position x, y
        x = (ws / 2) - (self.width / 2)
        y = (hs / 2) - (self.height / 2)
        root.geometry('%dx%d+%d+%d' % (self.width, self.height, x, y))

        image = tk.PhotoImage(file=self.image_file)
        canvas = tk.Canvas(root, height=self.height, width=self.width, bg="brown")
        canvas.create_image(self.width/2, self.height/2, image=image)
        canvas.pack()

        root.after(2500, root.destroy)
        root.mainloop() 
Example #12
Source File: window.py    From LPHK with GNU General Public License v3.0 6 votes vote down vote up
def make():
    global root
    global app
    global root_destroyed
    global redetect_before_start
    root = tk.Tk()
    root_destroyed = False
    root.protocol("WM_DELETE_WINDOW", close)
    root.resizable(False, False)
    if MAIN_ICON != None:
        if os.path.splitext(MAIN_ICON)[1].lower() == ".gif":
            root.call('wm', 'iconphoto', root._w, tk.PhotoImage(file=MAIN_ICON))
        else:
            root.iconbitmap(MAIN_ICON)
    app = Main_Window(root)
    app.raise_above_all()
    app.after(100, app.connect_lp)
    app.mainloop() 
Example #13
Source File: window.py    From LPHK with GNU General Public License v3.0 6 votes vote down vote up
def popup_choice(self, window, title, image, text, choices):
        popup = tk.Toplevel(window)
        popup.resizable(False, False)
        if MAIN_ICON != None:
            if os.path.splitext(MAIN_ICON)[1].lower() == ".gif":
                dummy = None
                #popup.call('wm', 'iconphoto', popup._w, tk.PhotoImage(file=MAIN_ICON))
            else:
                popup.iconbitmap(MAIN_ICON)
        popup.wm_title(title)
        popup.tkraise(window)
        
        def run_end(func):
            popup.destroy()
            if func != None:
                func()

        picture_label = tk.Label(popup, image=image)
        picture_label.photo = image
        picture_label.grid(column=0, row=0, rowspan=2, padx=10, pady=10)
        tk.Label(popup, text=text, justify=tk.CENTER).grid(column=1, row=0, columnspan=len(choices), padx=10, pady=10)
        for idx, choice in enumerate(choices):
            run_end_func = partial(run_end, choice[1])
            tk.Button(popup, text=choice[0], command=run_end_func).grid(column=1 + idx, row=1, padx=10, pady=10)
        popup.wait_visibility()
        popup.grab_set()
        popup.wait_window() 
Example #14
Source File: chatwindow.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def receive_message(self, message, smilies):
        """
        Writes message into messages_area
        :param message: message text
        :param smilies: list of tuples of (char_index, smilie_file), where char_index is the x index of the smilie's location
                        and smilie_file is the file name only (no path)
        :return: None
        """
        self.messages_area.configure(state='normal')
        self.messages_area.insert(tk.END, message)

        if len(smilies):
            last_line_no = self.messages_area.index(tk.END)
            last_line_no = str(last_line_no).split('.')[0]
            last_line_no = str(int(last_line_no) - 2)

            for index, file in smilies:
                smilie_path = os.path.join(SmilieSelect.smilies_dir, file)
                image = tk.PhotoImage(file=smilie_path)
                smilie_index = last_line_no + '.' + index
                self.messages_area.image_create(smilie_index, image=image)

        self.messages_area.configure(state='disabled') 
Example #15
Source File: ImageTk.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _show(image, title):
    """Helper for the Image.show method."""

    class UI(tkinter.Label):
        def __init__(self, master, im):
            if im.mode == "1":
                self.image = BitmapImage(im, foreground="white", master=master)
            else:
                self.image = PhotoImage(im, master=master)
            super().__init__(master, image=self.image, bg="black", bd=0)

    if not tkinter._default_root:
        raise OSError("tkinter not initialized")
    top = tkinter.Toplevel()
    if title:
        top.title(title)
    UI(top, image).pack() 
Example #16
Source File: avatarwindow.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def __init__(self, master):
        super().__init__()

        self.master = master
        self.transient(master)

        self.title("Change Avatar")
        self.geometry("350x200")

        self.image_file_types = [
            ("Png Images", ("*.png", "*.PNG")),
        ]

        self.current_avatar_image = tk.PhotoImage(file=avatar_file_path)

        self.current_avatar = ttk.Label(self, image=self.current_avatar_image)
        choose_file_button = ttk.Button(self, text="Choose File", command=self.choose_image)

        self.current_avatar.pack()
        choose_file_button.pack() 
Example #17
Source File: avatarwindow.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def choose_image(self):
        image_file = filedialog.askopenfilename(filetypes=self.image_file_types)

        if image_file:
            avatar = Image.open(image_file)
            avatar.thumbnail((128, 128))
            avatar.save(avatar_file_path, "PNG")

            img_contents = ""
            img_b64 = ""
            with open(avatar_file_path, "rb") as img:
                img_contents = img.read()
                img_b64 = base64.urlsafe_b64encode(img_contents)

            self.master.requester.update_avatar(self.master.username, img_b64)

            self.current_avatar_image = tk.PhotoImage(file=avatar_file_path)
            self.current_avatar.configure(image=self.current_avatar_image) 
Example #18
Source File: icon_list.py    From LIFX-Control-Panel with MIT License 6 votes vote down vote up
def draw_bulb_icon(self, bulb, label):
        """ Given a bulb and a name, add the icon to the end of the row. """
        # Make room on canvas
        self.scrollx += self.icon_width
        self.canvas.configure(scrollregion=(0, 0, self.scrollx, self.scrolly))
        # Build icon
        path = self.icon_path()
        sprite = tkinter.PhotoImage(file=path, master=self.master)
        image = self.canvas.create_image(
            (self.current_icon_width + self.icon_width - self.pad, self.icon_height / 2 + 2 * self.pad), image=sprite,
            anchor=tkinter.SE, tags=[label])
        text = self.canvas.create_text(self.current_icon_width + self.pad / 2, self.icon_height / 2 + 2 * self.pad,
                                       text=label[:8], anchor=tkinter.NW, tags=[label])
        self.bulb_dict[label] = (sprite, image, text)
        self.update_icon(bulb)
        # update sizing info
        self.current_icon_width += self.icon_width 
Example #19
Source File: ImageTk.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _show(image, title):
    """Helper for the Image.show method."""

    class UI(tkinter.Label):
        def __init__(self, master, im):
            if im.mode == "1":
                self.image = BitmapImage(im, foreground="white", master=master)
            else:
                self.image = PhotoImage(im, master=master)
            tkinter.Label.__init__(self, master, image=self.image,
                                   bg="black", bd=0)

    if not tkinter._default_root:
        raise IOError("tkinter not initialized")
    top = tkinter.Toplevel()
    if title:
        top.title(title)
    UI(top, image).pack() 
Example #20
Source File: program4.py    From python-gui-demos with MIT License 6 votes vote down vote up
def __init__(self, master):
        self.button = ttk.Button(master, text = 'Click me')
        self.button.pack()
        self.button.config(command = self.buttonfunc)          # configure a command for button click
        
        self.btn1 = ttk.Button(master, text = 'Click on \'Click me\'', command = self.invokebutton)
        self.btn1.pack()
        
        self.btn2 = ttk.Button(master, text = 'Disable \'Click me\'', command = self.disableButton)
        self.btn2.pack()
        
        self.btn3 = ttk.Button(master, text = 'Enable \'Click me\'', command = self.enableButton)
        self.btn3.pack()
        
        self.btn4 = ttk.Button(master, text = 'Query state of \'Click me\'', command = self.queryButtonState)
        self.btn4.pack()
        
        self.button.img  = tk.PhotoImage(file = 'simple_gif.gif')
        self.button.img = self.button.img.subsample(10, 10) # take every 5th pixel in x and y direction of image
        
        self.btn5 = ttk.Button(master, text = 'Add image to \'Click me\'', command = self.addImage)
        self.btn5.pack()
        
        self.label = ttk.Label(master, text = 'No button pressed yet.')
        self.label.pack() 
Example #21
Source File: program3.py    From python-gui-demos with MIT License 6 votes vote down vote up
def __init__(self, master):     # constructor method
        # define list of label texts
        self.greet_list = ('Hello, World! This is python GUI.', \
                           'Hello, This is Python GUI. Sadly, I was made to say Hello only. I will love to say so much more.')
        
        # creat label as a child of root window with some text.
        self.label = ttk.Label(master, text = self.greet_list[0])
        
        self.btn = ttk.Button(master, text = 'Greet Again', command = self.handle_text) # create a button
        
        # store image in the label obj to keep it in the scope as 
        # long as label is displayed and to avoid getting the image getting garbage collected
        imgpath = 'simple_gif.gif'                                      # path of the image
        self.label.img = tk.PhotoImage(file = imgpath)                  # read_image :: saving image within label_object to prevent its garbage collection
        self.label.config(image = self.label.img)                       # display image in label widget
        self.label.config(compound = 'left')                            # to display image in left of text
        
        self.label.pack()                                               # pack label to the window with pack() geometry method of Label
        self.btn.pack()
        
        self.label.config(wraplength = 200)                             # specify wraplength of text in label
        self.label.config(justify = tk.CENTER)                          # justify text in label to (CENTER, RIGHT or LEFT)
        self.label.config(foreground = 'blue', background = 'yellow')   # insert font color (foreground) and background color
        self.label.config(font = ('Times', 10, 'bold'))                 # font = (font_name, font_size, font_type) 
Example #22
Source File: nemo_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, image, initialField, initialText):
        frm = tk.Frame(root)
        frm.config(background="white")
        self.image = tk.PhotoImage(format='gif',data=images[image.upper()])
        self.imageDimmed = tk.PhotoImage(format='gif',data=images[image])
        self.img = tk.Label(frm)
        self.img.config(borderwidth=0)
        self.img.pack(side = "left")
        self.fld = tk.Text(frm, **fieldParams)
        self.initScrollText(frm,self.fld,initialField)
        frm = tk.Frame(root)
        self.txt = tk.Text(frm, **textParams)
        self.initScrollText(frm,self.txt,initialText)
        for i in range(2):
            self.txt.tag_config(colors[i], background = colors[i])
            self.txt.tag_config("emph"+colors[i], foreground = emphColors[i]) 
Example #23
Source File: tk.py    From Jtyoui with MIT License 6 votes vote down vote up
def ui():
    root = tkinter.Tk()
    root.title('PDF和照片互转器')  # 标题
    root.resizable(width=False, height=False)  # 防止大小调整
    canvas = tkinter.Canvas(root, width=450, height=320, highlightthickness=0)  # 创建画布
    photo = tkinter.PhotoImage(file=file_zip_path + os.sep + 'pdf.png')  # 获取背景图片的网络连接
    canvas.create_image(225, 160, image=photo)

    select_dir_button = tkinter.Button(root, text="选择照片文件夹", command=select_dir, bg='yellow')  # 创建按钮
    select_pdf_button = tkinter.Button(root, text="选择PDF文件", command=select_pdf, bg='green')
    click_button = tkinter.Button(root, text="点击执行", command=start, bg='blue')

    select_dir_button.pack()  # 启动按钮
    select_pdf_button.pack()
    click_button.pack()

    canvas.create_window(240, 120, width=100, height=30, window=select_dir_button)  # 将按钮创建到画布
    canvas.create_window(240, 190, width=100, height=30, window=select_pdf_button)
    canvas.create_window(240, 260, width=100, height=30, window=click_button)
    canvas.pack()  # 启动画布
    root.mainloop()  # 主程序循环 
Example #24
Source File: client_graphics.py    From Pyro5 with MIT License 6 votes vote down vote up
def __init__(self):
        self.root = tkinter.Tk()
        self.root.title("Mandelbrot (Pyro multi CPU core version)")
        canvas = tkinter.Canvas(self.root, width=res_x, height=res_y, bg="#000000")
        canvas.pack()
        self.img = tkinter.PhotoImage(width=res_x, height=res_y)
        canvas.create_image((res_x/2, res_y/2), image=self.img, state="normal")
        with locate_ns() as ns:
            mandels = ns.yplookup(meta_any={"class:mandelbrot_calc_color"})
            mandels = list(mandels.items())
        print("{0} mandelbrot calculation servers found.".format(len(mandels)))
        if not mandels:
            raise ValueError("launch at least one mandelbrot calculation server before starting this")
        self.mandels = [uri for _, (uri, meta) in mandels]
        self.pool = futures.ThreadPoolExecutor(max_workers=len(self.mandels))
        self.tasks = []
        self.start_time = time.time()
        for line in range(res_y):
            self.tasks.append(self.calc_new_line(line))
        self.root.after(100, self.draw_results)
        tkinter.mainloop() 
Example #25
Source File: window.py    From LPHK with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, master=None):
        tk.Frame.__init__(self, master)
        self.master = master
        self.init_window()
        
        self.about_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/LPHK-banner.png"))
        self.info_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/info.png"))
        self.warning_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/warning.png"))
        self.error_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/error.png"))
        self.alert_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/alert.png"))
        self.scare_image = ImageTk.PhotoImage(Image.open(PATH + "/resources/scare.png"))
        self.grid_drawn = False
        self.grid_rects = [[None for y in range(9)] for x in range(9)]
        self.button_mode = "edit"
        self.last_clicked = None
        self.outline_box = None 
Example #26
Source File: components.py    From SEM with MIT License 6 votes vote down vote up
def __init__(self, root, main_window, button_opt):
        ttk.Frame.__init__(self, root)
        
        self.root = root
        self.main_window = main_window
        self.current_files = None
        self.button_opt = button_opt
        
        # define options for opening or saving a file
        self.file_opt = options = {}
        options['defaultextension'] = '.txt'
        options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
        options['initialdir'] = os.path.expanduser("~")
        options['parent'] = root
        options['title'] = 'Select files to annotate.'
        
        self.file_selector_button = ttk.Button(self.root, text=u"select file(s)", command=self.filenames)
        self.label = ttk.Label(self.root, text=u"selected file(s):")
        self.fa_search = tkinter.PhotoImage(file=os.path.join(self.main_window.resource_dir, "images", "fa_search_24_24.gif"))
        self.file_selector_button.config(image=self.fa_search, compound=tkinter.LEFT)
        
        self.scrollbar = ttk.Scrollbar(self.root)
        self.selected_files = tkinter.Listbox(self.root, yscrollcommand=self.scrollbar.set)
        self.scrollbar.config(command=self.selected_files.yview) 
Example #27
Source File: friendslist.py    From Tkinter-GUI-Programming-by-Example with MIT License 6 votes vote down vote up
def load_friends(self):
        my_friends = self.requester.get_friends(self.username)
        for user in my_friends["friends"]:
            if user['username'] != self.username:
                friend_frame = ttk.Frame(self.canvas_frame)

                friend_avatar_path = os.path.join(friend_avatars_dir, f"{user['username']}.png")

                if user["avatar"]:
                    with open(friend_avatar_path, 'wb') as friend_avatar:
                        img = base64.urlsafe_b64decode(user['avatar'])
                        friend_avatar.write(img)
                else:
                    friend_avatar_path = default_avatar_path

                profile_photo = tk.PhotoImage(file=friend_avatar_path)
                profile_photo_label = ttk.Label(friend_frame, image=profile_photo)
                profile_photo_label.image = profile_photo

                friend_name = ttk.Label(friend_frame, text=user['real_name'], anchor=tk.W)

                message_this_friend = partial(self.open_chat_window, username=user["username"], real_name=user["real_name"], avatar=friend_avatar_path)
                block_this_friend = partial(self.block_friend, username=user["username"])

                message_button = ttk.Button(friend_frame, text="Chat", command=message_this_friend)
                block_button = ttk.Button(friend_frame, text="Block", command=block_this_friend)

                profile_photo_label.pack(side=tk.LEFT)
                friend_name.pack(side=tk.LEFT)
                message_button.pack(side=tk.RIGHT)
                block_button.pack(side=tk.RIGHT, padx=(0, 30))

                friend_frame.pack(fill=tk.X, expand=1) 
Example #28
Source File: ImageTk.py    From teleport with Apache License 2.0 5 votes vote down vote up
def getimage(photo):
    """Copies the contents of a PhotoImage to a PIL image memory."""
    im = Image.new("RGBA", (photo.width(), photo.height()))
    block = im.im

    photo.tk.call("PyImagingPhotoGet", photo, block.id)

    return im 
Example #29
Source File: ImageTk.py    From teleport with Apache License 2.0 5 votes vote down vote up
def __init__(self, image=None, size=None, **kw):

        # Tk compatibility: file or data
        if image is None:
            image = _get_image_from_kw(kw)

        if hasattr(image, "mode") and hasattr(image, "size"):
            # got an image instead of a mode
            mode = image.mode
            if mode == "P":
                # palette mapped data
                image.load()
                try:
                    mode = image.palette.mode
                except AttributeError:
                    mode = "RGB"  # default
            size = image.size
            kw["width"], kw["height"] = size
        else:
            mode = image
            image = None

        if mode not in ["1", "L", "RGB", "RGBA"]:
            mode = Image.getmodebase(mode)

        self.__mode = mode
        self.__size = size
        self.__photo = tkinter.PhotoImage(**kw)
        self.tk = self.__photo.tk
        if image:
            self.paste(image) 
Example #30
Source File: _backend_tk.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def _Button(self, text, file, command, extension='.gif'):
        img_file = os.path.join(
            rcParams['datapath'], 'images', file + extension)
        im = tk.PhotoImage(master=self, file=img_file)
        b = tk.Button(
            master=self, text=text, padx=2, pady=2, image=im, command=command)
        b._ntimage = im
        b.pack(side=tk.LEFT)
        return b