python-3.xtkinteropencvphotoimagepython

PhotoImage Tkinter problem: Button not working and not displaying


im using Proxlight Designer to create Drag-n-drop GUI. It is a application that works with open-cv-python, but a Button is not displaying. It seems as if open-cv is the problem, because if you remove it the Button displays and works properly. Here is the code for the GUI:

cap = cv2.VideoCapture(0)

window = Tk()
window.geometry("700x800")
window.configure(bg = "#ffffff")
canvas = Canvas(
    window,
    bg = "#ffffff",
    height = 800,
    width = 700,
    bd = 0,
    highlightthickness = 0,
    relief = "ridge")
canvas.place(x = 0, y = 0)

l1 = Label(bg = "black")
l1.place(x = 100, y = 150, width = 500, height = 500)

img0 = PhotoImage(file = f"RES/img1.png")
b0 = Button(
    image = img0,
    borderwidth = 0,
    highlightthickness = 0,
    command = save_face,
    relief = "flat")

b0.place(
    x = 250, y = 693,
    width = 200,
    height = 75)

img1 = PhotoImage(file = f"RES/img2.png")

b1 = Button(
    image = img1,
    borderwidth = 0,
    highlightthickness = 0,
    command = encryptPass,
    relief = "flat")

b1.place(
    x = 480, y = 693,
    width = 200,
    height = 75)

img2 = PhotoImage(file = f"RES/img3.png")
b2 = Button(
    image = img2,
    borderwidth = 0,
    highlightthickness = 0,
    command = generate_key,
    relief = "flat")

b2.place(
    x = 20, y = 693,
    width = 200,
    height = 75)

window.resizable(False, False)

while True:
    img = cap.read()[1]
    img1 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img = ImageTk.PhotoImage(Image.fromarray(img1))
    l1["image"] = img
    window.update()

Solution

  • So thanks to the comments of @Matiiss and @acw1668 (thx alot btw) i got it to work. Basically the while loop was the problem. I fixed it using this instead of the while loop:

    cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    
    def show_frame():
        _, frame = cap.read()
        global cv2image
        cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
        img = Image.fromarray(cv2image)
        imgtk = ImageTk.PhotoImage(image=img)
        l1.imgtk = imgtk
        l1.configure(image=imgtk)
        l1.after(10, show_frame)
    
    window = Tk()
    window.geometry("700x800")
    window.configure(bg = "#ffffff")
    
    l1 = Label(bg = "black")
    l1.place(x = 100, y = 150, width = 500, height = 500)
    
    window.resizable(False, False)
    
    show_frame()
    window.mainloop()