0

Building a script for controlling components at the house. As an example I have 4 buttons. I am trying to figure out how I can edit the button images as a user. so the user can assign an image to a button. I have a folder of pre designed images the user can select from. I figured out how to open a filesystem, chose a photo and place that photo into a random button but I am not really sure where to go from here or if I am even going in the right direction. I am new so, example code would be very helpful with the explanation. thanks

import tkinter as tk
from tkinter import *
from PIL import ImageTk, Image
from tkinter.filedialog import askopenfilename

my_w = tk.Tk()
my_w.geometry("800x480")
my_w.title('SELECT PHOTOS')

l1 = tk.Label(my_w, text='EDIT BUTTON IMAGES')
l1.pack()
b = tk.Button(my_w, text='IMAGES', command=lambda:upload_file())
b.pack()
f1 = tk.Frame(my_w)
b1 = tk.Button(f1, text="button 1")
b2 = tk.Button(f1, text="button 2")
b3 = tk.Button(f1, text="button 3")
b4 = tk.Button(f1, text="button 4")

b1.grid(row=0, column=0, padx=5)
b2.grid(row=0, column=1, padx=5)
b3.grid(row=0, column=2, padx=5)
b4.grid(row=0, column=3, padx=5)
f1.pack(pady=30)

def upload_file():
    f_types=[('png Files', '*.png'), ('Jpg Files', '*.png')]
    filename=tk.filedialog.askopenfilename(filetypes=f_types)
    img=Image.open(filename)
    img=img.resize((100, 100))
    img=ImageTk.PhotoImage(img)
    e1=tk.Button(my_w)
    e1.pack()
    e1.image=img
    e1['image'] = img

my_w.mainloop()

Mike K
  • 1
  • 1
  • It kinda seems like you have already accomplished your goal... If a user runs your program and clicks the `b` button, then they are taken to a dialogue where they can select an image, and that image get's assigned to a button. Which part are you confused about? – Alexander Jan 08 '23 at 08:06
  • Right now your code has [this](https://stackoverflow.com/q/16424091/11106801) problem. You tried to solve it by using `e1.image = img` but if you don't keep a reference to `e1`, the problem pops up again. I suggest using a global list of `img`s. Also `command=lambda:upload_file()` can be simplified to `command=upload_file` – TheLizzard Jan 08 '23 at 10:30
  • I think you want to set the image of one of the four buttons instead of creating a new button. Is it what you want actually? – acw1668 Jan 09 '23 at 02:06
  • @acw1668 yes I want to assign 1 of the 4 existing buttons with an image. – Mike K Jan 15 '23 at 16:09
  • @TheLizzard is there a way I can set global variables, choose an image and then select 1 out of the 4 buttons i want the image to go to? – Mike K Jan 15 '23 at 16:15
  • Then you need to find a way to select which button you want to assign the image to. – acw1668 Jan 15 '23 at 23:13

0 Answers0