无法创建按钮

时间:2018-01-30 10:53:07

标签: python opencv tkinter

我正在创建一个使用python opencv tkinter进行实时面部检测的简单应用程序。我可以进行实时面部检测,但是当我尝试创建一个启动实时源的按钮时,它甚至没有执行该程序。有人能帮助我吗?

from ttk import *
import Tkinter as tk
from Tkinter import *
import cv2
from PIL import Image, ImageTk
import os
import numpy as np

face_classifier = cv2.CascadeClassifier('Haarcascades/haarcascade_frontalface_default.xml')
global last_frame                                      #creating global variable
last_frame = np.zeros((480, 640, 3), dtype=np.uint8)
global cap
cap = cv2.VideoCapture(0)

def show_vid():                                        #creating a function

    if not cap.isOpened():                             
        print("cant open the camera")

    flag, frame = cap.read()
    frame = cv2.flip(frame, 1)

    if flag is None:
        print "Major error!"
    elif flag:
        global last_frame
        last_frame = frame.copy()

    pic = cv2.cvtColor(last_frame, cv2.COLOR_BGR2GRAY)     
    faces = face_classifier.detectMultiScale(pic, 1.3, 5)

    for (x,y,w,h) in faces:
        x = x - 50
        w = w + 50
        y = y - 50
        h = h + 50
        cv2.rectangle(last_frame,(x,y),(x+w,y+h),(255,0,0),2)

    last_frame=cv2.cvtColor(last_frame, cv2.COLOR_BGR2GRAY)
    img = Image.fromarray(last_frame)
    imgtk = ImageTk.PhotoImage(image=img)
    lmain.imgtk = imgtk
    lmain.configure(image=imgtk)
    lmain.after(10, show_vid)

if __name__ == '__main__':
    root=tk.Tk()                                    
    lmain = tk.Label(master=root)
    lmain.grid(column=0, rowspan=4, padx=5, pady=5)
    root.title("Live face detection")  
    button = Button(root, text = "Start", command=show_vid).pack()
    #show_vid()
    root.mainloop()                                  
   cap.release()

当我评论按钮行和未注释的show_vid()行直播面部检测工作时,但是当我做相反的情况时,它不起作用。

1 个答案:

答案 0 :(得分:0)

您应该使用按钮(row = yourrow,column = yourcolumn sticky = E)替换该行的.pack()部分,您可以在其中指定要放置按钮的列和行