Reputation: 167
I don't have any experience with GUI in python.... So, I'll post the GUI code first.
from tkinter import*
def needTodo():
#Enter your code
root = Tk()
root.title('Something')
# ******** MAIN MENU ******** #
menu = Menu(root)
root.config(menu=menu)
root.minsize(320, 320)
root.geometry("320x320")
subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="Insert Image", command=needTodo)
subMenu.add_command(label="Web Cam", command=needTodo)
subMenu.add_separator()
subMenu.add_command(label="Exit", command=needTodo)
editMenu = Menu(menu)
menu.add_cascade(label="Edit", command=editMenu)
editMenu.add_command(label="Redo", command=needTodo)
# *********** Toolbar ************ #
toolbar = Frame(root, bg="gray")
insertBar = Button(toolbar, text="Insert Image", command=needTodo)
insertBar.pack(side=LEFT, padx=2, pady=2)
printBar = Button(toolbar, text="Print", command=needTodo)
printBar.pack(side=RIGHT, padx=2, pady=2)
toolbar.pack(side=TOP, fill=X)
# ********* IMAGE BACKGROUND ************ #
canvas = Canvas(width=320, height=320, bg='white')
canvas.pack()
gif1 = PhotoImage(file='D:/Rotating_brain_colored.gif')
canvas.create_image(0, 0, image=gif1, anchor=NW)
# ********* STATUS BAR ************ #
status = Label(root, text="Preparing to do work....", bd=1, relief=SUNKEN, anchor=W)
status.pack(side=BOTTOM, fill=X)
root.mainloop()
So, when in the sub menu, "web cam" option is clicked I want it to execute a function written in another file(main.py) in the same folder.
The function is called "TakeSnapAndSave()" which basically takes accesses the web cam and takes a pic under certain circumstances.
I want to keep the gui.py and main.py separate. How can I do that?
Thanks in advance.
main.py code:
import cv2
import numpy as np
import os
import matplotlib.pyplot as plt
cascade = cv2.CascadeClassifier('xcascade.xml')
def TakeSnapAndSave():
cap = cv2.VideoCapture(0)
num = 0
while num<1000:
ret, img = cap.read()
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cas = cascade.detectMultiScale(gray, 10, 10)
for(x,y,w,h) in cas:
cv2.rectangle(img,(x,y), (x+w,y+h),(255,255,0),5)
cv2.imwrite('opencv'+str(num)+'.jpg',img)
num = num+1
cv2.imshow('img',img)
cv2.waitKey(1000)
cap.release()
cv2.desrtoyAllWindows()
break
TakeSnapAndSave()
Upvotes: 0
Views: 870
Reputation: 61
The last line of code in your main.py file is calling the function TakeSnapAndSave when the file is imported rather than when the option is selected in the GUI. Remove that call to TakeSnapAndSave from main.py and Novel's advice should work:
subMenu.add_command(label="Web Cam", command=main.TakeSnapAndSave)
Check out the thread on guarding code from being automatically run: Why is Python running my module when I import it, and how do I stop it?
Upvotes: 1